theme.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155
  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.5.1 (2020-10-01)
  8. */
  9. (function () {
  10. 'use strict';
  11. var noop = function () {
  12. };
  13. var noarg = function (f) {
  14. return function () {
  15. return f();
  16. };
  17. };
  18. var compose = function (fa, fb) {
  19. return function () {
  20. var args = [];
  21. for (var _i = 0; _i < arguments.length; _i++) {
  22. args[_i] = arguments[_i];
  23. }
  24. return fa(fb.apply(null, args));
  25. };
  26. };
  27. var compose1 = function (fbc, fab) {
  28. return function (a) {
  29. return fbc(fab(a));
  30. };
  31. };
  32. var constant = function (value) {
  33. return function () {
  34. return value;
  35. };
  36. };
  37. var identity = function (x) {
  38. return x;
  39. };
  40. function curry(fn) {
  41. var initialArgs = [];
  42. for (var _i = 1; _i < arguments.length; _i++) {
  43. initialArgs[_i - 1] = arguments[_i];
  44. }
  45. return function () {
  46. var restArgs = [];
  47. for (var _i = 0; _i < arguments.length; _i++) {
  48. restArgs[_i] = arguments[_i];
  49. }
  50. var all = initialArgs.concat(restArgs);
  51. return fn.apply(null, all);
  52. };
  53. }
  54. var not = function (f) {
  55. return function (t) {
  56. return !f(t);
  57. };
  58. };
  59. var die = function (msg) {
  60. return function () {
  61. throw new Error(msg);
  62. };
  63. };
  64. var never = constant(false);
  65. var always = constant(true);
  66. var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  67. var __assign = function () {
  68. __assign = Object.assign || function __assign(t) {
  69. for (var s, i = 1, n = arguments.length; i < n; i++) {
  70. s = arguments[i];
  71. for (var p in s)
  72. if (Object.prototype.hasOwnProperty.call(s, p))
  73. t[p] = s[p];
  74. }
  75. return t;
  76. };
  77. return __assign.apply(this, arguments);
  78. };
  79. function __rest(s, e) {
  80. var t = {};
  81. for (var p in s)
  82. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  83. t[p] = s[p];
  84. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  85. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  86. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  87. t[p[i]] = s[p[i]];
  88. }
  89. return t;
  90. }
  91. function __spreadArrays() {
  92. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  93. s += arguments[i].length;
  94. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  95. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  96. r[k] = a[j];
  97. return r;
  98. }
  99. var none = function () {
  100. return NONE;
  101. };
  102. var NONE = function () {
  103. var eq = function (o) {
  104. return o.isNone();
  105. };
  106. var call = function (thunk) {
  107. return thunk();
  108. };
  109. var id = function (n) {
  110. return n;
  111. };
  112. var me = {
  113. fold: function (n, _s) {
  114. return n();
  115. },
  116. is: never,
  117. isSome: never,
  118. isNone: always,
  119. getOr: id,
  120. getOrThunk: call,
  121. getOrDie: function (msg) {
  122. throw new Error(msg || 'error: getOrDie called on none.');
  123. },
  124. getOrNull: constant(null),
  125. getOrUndefined: constant(undefined),
  126. or: id,
  127. orThunk: call,
  128. map: none,
  129. each: noop,
  130. bind: none,
  131. exists: never,
  132. forall: always,
  133. filter: none,
  134. equals: eq,
  135. equals_: eq,
  136. toArray: function () {
  137. return [];
  138. },
  139. toString: constant('none()')
  140. };
  141. return me;
  142. }();
  143. var some = function (a) {
  144. var constant_a = constant(a);
  145. var self = function () {
  146. return me;
  147. };
  148. var bind = function (f) {
  149. return f(a);
  150. };
  151. var me = {
  152. fold: function (n, s) {
  153. return s(a);
  154. },
  155. is: function (v) {
  156. return a === v;
  157. },
  158. isSome: always,
  159. isNone: never,
  160. getOr: constant_a,
  161. getOrThunk: constant_a,
  162. getOrDie: constant_a,
  163. getOrNull: constant_a,
  164. getOrUndefined: constant_a,
  165. or: self,
  166. orThunk: self,
  167. map: function (f) {
  168. return some(f(a));
  169. },
  170. each: function (f) {
  171. f(a);
  172. },
  173. bind: bind,
  174. exists: bind,
  175. forall: bind,
  176. filter: function (f) {
  177. return f(a) ? me : NONE;
  178. },
  179. toArray: function () {
  180. return [a];
  181. },
  182. toString: function () {
  183. return 'some(' + a + ')';
  184. },
  185. equals: function (o) {
  186. return o.is(a);
  187. },
  188. equals_: function (o, elementEq) {
  189. return o.fold(never, function (b) {
  190. return elementEq(a, b);
  191. });
  192. }
  193. };
  194. return me;
  195. };
  196. var from = function (value) {
  197. return value === null || value === undefined ? NONE : some(value);
  198. };
  199. var Optional = {
  200. some: some,
  201. none: none,
  202. from: from
  203. };
  204. var typeOf = function (x) {
  205. var t = typeof x;
  206. if (x === null) {
  207. return 'null';
  208. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  209. return 'array';
  210. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  211. return 'string';
  212. } else {
  213. return t;
  214. }
  215. };
  216. var isType = function (type) {
  217. return function (value) {
  218. return typeOf(value) === type;
  219. };
  220. };
  221. var isSimpleType = function (type) {
  222. return function (value) {
  223. return typeof value === type;
  224. };
  225. };
  226. var eq = function (t) {
  227. return function (a) {
  228. return t === a;
  229. };
  230. };
  231. var isString = isType('string');
  232. var isObject = isType('object');
  233. var isArray = isType('array');
  234. var isBoolean = isSimpleType('boolean');
  235. var isUndefined = eq(undefined);
  236. var isNullable = function (a) {
  237. return a === null || a === undefined;
  238. };
  239. var isNonNullable = function (a) {
  240. return !isNullable(a);
  241. };
  242. var isFunction = isSimpleType('function');
  243. var isNumber = isSimpleType('number');
  244. var isArrayOf = function (value, pred) {
  245. if (isArray(value)) {
  246. for (var i = 0, len = value.length; i < len; ++i) {
  247. if (!pred(value[i])) {
  248. return false;
  249. }
  250. }
  251. return true;
  252. }
  253. return false;
  254. };
  255. var nativeSlice = Array.prototype.slice;
  256. var nativeIndexOf = Array.prototype.indexOf;
  257. var nativePush = Array.prototype.push;
  258. var rawIndexOf = function (ts, t) {
  259. return nativeIndexOf.call(ts, t);
  260. };
  261. var indexOf = function (xs, x) {
  262. var r = rawIndexOf(xs, x);
  263. return r === -1 ? Optional.none() : Optional.some(r);
  264. };
  265. var contains = function (xs, x) {
  266. return rawIndexOf(xs, x) > -1;
  267. };
  268. var exists = function (xs, pred) {
  269. for (var i = 0, len = xs.length; i < len; i++) {
  270. var x = xs[i];
  271. if (pred(x, i)) {
  272. return true;
  273. }
  274. }
  275. return false;
  276. };
  277. var range = function (num, f) {
  278. var r = [];
  279. for (var i = 0; i < num; i++) {
  280. r.push(f(i));
  281. }
  282. return r;
  283. };
  284. var chunk = function (array, size) {
  285. var r = [];
  286. for (var i = 0; i < array.length; i += size) {
  287. var s = nativeSlice.call(array, i, i + size);
  288. r.push(s);
  289. }
  290. return r;
  291. };
  292. var map = function (xs, f) {
  293. var len = xs.length;
  294. var r = new Array(len);
  295. for (var i = 0; i < len; i++) {
  296. var x = xs[i];
  297. r[i] = f(x, i);
  298. }
  299. return r;
  300. };
  301. var each = function (xs, f) {
  302. for (var i = 0, len = xs.length; i < len; i++) {
  303. var x = xs[i];
  304. f(x, i);
  305. }
  306. };
  307. var eachr = function (xs, f) {
  308. for (var i = xs.length - 1; i >= 0; i--) {
  309. var x = xs[i];
  310. f(x, i);
  311. }
  312. };
  313. var partition = function (xs, pred) {
  314. var pass = [];
  315. var fail = [];
  316. for (var i = 0, len = xs.length; i < len; i++) {
  317. var x = xs[i];
  318. var arr = pred(x, i) ? pass : fail;
  319. arr.push(x);
  320. }
  321. return {
  322. pass: pass,
  323. fail: fail
  324. };
  325. };
  326. var filter = function (xs, pred) {
  327. var r = [];
  328. for (var i = 0, len = xs.length; i < len; i++) {
  329. var x = xs[i];
  330. if (pred(x, i)) {
  331. r.push(x);
  332. }
  333. }
  334. return r;
  335. };
  336. var foldr = function (xs, f, acc) {
  337. eachr(xs, function (x) {
  338. acc = f(acc, x);
  339. });
  340. return acc;
  341. };
  342. var foldl = function (xs, f, acc) {
  343. each(xs, function (x) {
  344. acc = f(acc, x);
  345. });
  346. return acc;
  347. };
  348. var findUntil = function (xs, pred, until) {
  349. for (var i = 0, len = xs.length; i < len; i++) {
  350. var x = xs[i];
  351. if (pred(x, i)) {
  352. return Optional.some(x);
  353. } else if (until(x, i)) {
  354. break;
  355. }
  356. }
  357. return Optional.none();
  358. };
  359. var find = function (xs, pred) {
  360. return findUntil(xs, pred, never);
  361. };
  362. var findIndex = function (xs, pred) {
  363. for (var i = 0, len = xs.length; i < len; i++) {
  364. var x = xs[i];
  365. if (pred(x, i)) {
  366. return Optional.some(i);
  367. }
  368. }
  369. return Optional.none();
  370. };
  371. var flatten = function (xs) {
  372. var r = [];
  373. for (var i = 0, len = xs.length; i < len; ++i) {
  374. if (!isArray(xs[i])) {
  375. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  376. }
  377. nativePush.apply(r, xs[i]);
  378. }
  379. return r;
  380. };
  381. var bind = function (xs, f) {
  382. return flatten(map(xs, f));
  383. };
  384. var forall = function (xs, pred) {
  385. for (var i = 0, len = xs.length; i < len; ++i) {
  386. var x = xs[i];
  387. if (pred(x, i) !== true) {
  388. return false;
  389. }
  390. }
  391. return true;
  392. };
  393. var reverse = function (xs) {
  394. var r = nativeSlice.call(xs, 0);
  395. r.reverse();
  396. return r;
  397. };
  398. var difference = function (a1, a2) {
  399. return filter(a1, function (x) {
  400. return !contains(a2, x);
  401. });
  402. };
  403. var mapToObject = function (xs, f) {
  404. var r = {};
  405. for (var i = 0, len = xs.length; i < len; i++) {
  406. var x = xs[i];
  407. r[String(x)] = f(x, i);
  408. }
  409. return r;
  410. };
  411. var sort = function (xs, comparator) {
  412. var copy = nativeSlice.call(xs, 0);
  413. copy.sort(comparator);
  414. return copy;
  415. };
  416. var head = function (xs) {
  417. return xs.length === 0 ? Optional.none() : Optional.some(xs[0]);
  418. };
  419. var last = function (xs) {
  420. return xs.length === 0 ? Optional.none() : Optional.some(xs[xs.length - 1]);
  421. };
  422. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  423. return nativeSlice.call(x);
  424. };
  425. var findMap = function (arr, f) {
  426. for (var i = 0; i < arr.length; i++) {
  427. var r = f(arr[i], i);
  428. if (r.isSome()) {
  429. return r;
  430. }
  431. }
  432. return Optional.none();
  433. };
  434. var value = function (o) {
  435. var is = function (v) {
  436. return o === v;
  437. };
  438. var or = function (_opt) {
  439. return value(o);
  440. };
  441. var orThunk = function (_f) {
  442. return value(o);
  443. };
  444. var map = function (f) {
  445. return value(f(o));
  446. };
  447. var mapError = function (_f) {
  448. return value(o);
  449. };
  450. var each = function (f) {
  451. f(o);
  452. };
  453. var bind = function (f) {
  454. return f(o);
  455. };
  456. var fold = function (_, onValue) {
  457. return onValue(o);
  458. };
  459. var exists = function (f) {
  460. return f(o);
  461. };
  462. var forall = function (f) {
  463. return f(o);
  464. };
  465. var toOptional = function () {
  466. return Optional.some(o);
  467. };
  468. return {
  469. is: is,
  470. isValue: always,
  471. isError: never,
  472. getOr: constant(o),
  473. getOrThunk: constant(o),
  474. getOrDie: constant(o),
  475. or: or,
  476. orThunk: orThunk,
  477. fold: fold,
  478. map: map,
  479. mapError: mapError,
  480. each: each,
  481. bind: bind,
  482. exists: exists,
  483. forall: forall,
  484. toOptional: toOptional
  485. };
  486. };
  487. var error = function (message) {
  488. var getOrThunk = function (f) {
  489. return f();
  490. };
  491. var getOrDie = function () {
  492. return die(String(message))();
  493. };
  494. var or = function (opt) {
  495. return opt;
  496. };
  497. var orThunk = function (f) {
  498. return f();
  499. };
  500. var map = function (_f) {
  501. return error(message);
  502. };
  503. var mapError = function (f) {
  504. return error(f(message));
  505. };
  506. var bind = function (_f) {
  507. return error(message);
  508. };
  509. var fold = function (onError, _) {
  510. return onError(message);
  511. };
  512. return {
  513. is: never,
  514. isValue: never,
  515. isError: always,
  516. getOr: identity,
  517. getOrThunk: getOrThunk,
  518. getOrDie: getOrDie,
  519. or: or,
  520. orThunk: orThunk,
  521. fold: fold,
  522. map: map,
  523. mapError: mapError,
  524. each: noop,
  525. bind: bind,
  526. exists: never,
  527. forall: always,
  528. toOptional: Optional.none
  529. };
  530. };
  531. var fromOption = function (opt, err) {
  532. return opt.fold(function () {
  533. return error(err);
  534. }, value);
  535. };
  536. var Result = {
  537. value: value,
  538. error: error,
  539. fromOption: fromOption
  540. };
  541. var SimpleResultType;
  542. (function (SimpleResultType) {
  543. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  544. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  545. }(SimpleResultType || (SimpleResultType = {})));
  546. var fold = function (res, onError, onValue) {
  547. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  548. };
  549. var partition$1 = function (results) {
  550. var values = [];
  551. var errors = [];
  552. each(results, function (obj) {
  553. fold(obj, function (err) {
  554. return errors.push(err);
  555. }, function (val) {
  556. return values.push(val);
  557. });
  558. });
  559. return {
  560. values: values,
  561. errors: errors
  562. };
  563. };
  564. var mapError = function (res, f) {
  565. if (res.stype === SimpleResultType.Error) {
  566. return {
  567. stype: SimpleResultType.Error,
  568. serror: f(res.serror)
  569. };
  570. } else {
  571. return res;
  572. }
  573. };
  574. var map$1 = function (res, f) {
  575. if (res.stype === SimpleResultType.Value) {
  576. return {
  577. stype: SimpleResultType.Value,
  578. svalue: f(res.svalue)
  579. };
  580. } else {
  581. return res;
  582. }
  583. };
  584. var bind$1 = function (res, f) {
  585. if (res.stype === SimpleResultType.Value) {
  586. return f(res.svalue);
  587. } else {
  588. return res;
  589. }
  590. };
  591. var bindError = function (res, f) {
  592. if (res.stype === SimpleResultType.Error) {
  593. return f(res.serror);
  594. } else {
  595. return res;
  596. }
  597. };
  598. var svalue = function (v) {
  599. return {
  600. stype: SimpleResultType.Value,
  601. svalue: v
  602. };
  603. };
  604. var serror = function (e) {
  605. return {
  606. stype: SimpleResultType.Error,
  607. serror: e
  608. };
  609. };
  610. var toResult = function (res) {
  611. return fold(res, Result.error, Result.value);
  612. };
  613. var fromResult = function (res) {
  614. return res.fold(serror, svalue);
  615. };
  616. var SimpleResult = {
  617. fromResult: fromResult,
  618. toResult: toResult,
  619. svalue: svalue,
  620. partition: partition$1,
  621. serror: serror,
  622. bind: bind$1,
  623. bindError: bindError,
  624. map: map$1,
  625. mapError: mapError,
  626. fold: fold
  627. };
  628. var keys = Object.keys;
  629. var hasOwnProperty = Object.hasOwnProperty;
  630. var each$1 = function (obj, f) {
  631. var props = keys(obj);
  632. for (var k = 0, len = props.length; k < len; k++) {
  633. var i = props[k];
  634. var x = obj[i];
  635. f(x, i);
  636. }
  637. };
  638. var map$2 = function (obj, f) {
  639. return tupleMap(obj, function (x, i) {
  640. return {
  641. k: i,
  642. v: f(x, i)
  643. };
  644. });
  645. };
  646. var tupleMap = function (obj, f) {
  647. var r = {};
  648. each$1(obj, function (x, i) {
  649. var tuple = f(x, i);
  650. r[tuple.k] = tuple.v;
  651. });
  652. return r;
  653. };
  654. var objAcc = function (r) {
  655. return function (x, i) {
  656. r[i] = x;
  657. };
  658. };
  659. var internalFilter = function (obj, pred, onTrue, onFalse) {
  660. var r = {};
  661. each$1(obj, function (x, i) {
  662. (pred(x, i) ? onTrue : onFalse)(x, i);
  663. });
  664. return r;
  665. };
  666. var filter$1 = function (obj, pred) {
  667. var t = {};
  668. internalFilter(obj, pred, objAcc(t), noop);
  669. return t;
  670. };
  671. var mapToArray = function (obj, f) {
  672. var r = [];
  673. each$1(obj, function (value, name) {
  674. r.push(f(value, name));
  675. });
  676. return r;
  677. };
  678. var find$1 = function (obj, pred) {
  679. var props = keys(obj);
  680. for (var k = 0, len = props.length; k < len; k++) {
  681. var i = props[k];
  682. var x = obj[i];
  683. if (pred(x, i, obj)) {
  684. return Optional.some(x);
  685. }
  686. }
  687. return Optional.none();
  688. };
  689. var values = function (obj) {
  690. return mapToArray(obj, function (v) {
  691. return v;
  692. });
  693. };
  694. var get = function (obj, key) {
  695. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  696. };
  697. var has = function (obj, key) {
  698. return hasOwnProperty.call(obj, key);
  699. };
  700. var hasNonNullableKey = function (obj, key) {
  701. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  702. };
  703. var generate = function (cases) {
  704. if (!isArray(cases)) {
  705. throw new Error('cases must be an array');
  706. }
  707. if (cases.length === 0) {
  708. throw new Error('there must be at least one case');
  709. }
  710. var constructors = [];
  711. var adt = {};
  712. each(cases, function (acase, count) {
  713. var keys$1 = keys(acase);
  714. if (keys$1.length !== 1) {
  715. throw new Error('one and only one name per case');
  716. }
  717. var key = keys$1[0];
  718. var value = acase[key];
  719. if (adt[key] !== undefined) {
  720. throw new Error('duplicate key detected:' + key);
  721. } else if (key === 'cata') {
  722. throw new Error('cannot have a case named cata (sorry)');
  723. } else if (!isArray(value)) {
  724. throw new Error('case arguments must be an array');
  725. }
  726. constructors.push(key);
  727. adt[key] = function () {
  728. var argLength = arguments.length;
  729. if (argLength !== value.length) {
  730. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  731. }
  732. var args = new Array(argLength);
  733. for (var i = 0; i < args.length; i++) {
  734. args[i] = arguments[i];
  735. }
  736. var match = function (branches) {
  737. var branchKeys = keys(branches);
  738. if (constructors.length !== branchKeys.length) {
  739. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  740. }
  741. var allReqd = forall(constructors, function (reqKey) {
  742. return contains(branchKeys, reqKey);
  743. });
  744. if (!allReqd) {
  745. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  746. }
  747. return branches[key].apply(null, args);
  748. };
  749. return {
  750. fold: function () {
  751. if (arguments.length !== cases.length) {
  752. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  753. }
  754. var target = arguments[count];
  755. return target.apply(null, args);
  756. },
  757. match: match,
  758. log: function (label) {
  759. console.log(label, {
  760. constructors: constructors,
  761. constructor: key,
  762. params: args
  763. });
  764. }
  765. };
  766. };
  767. });
  768. return adt;
  769. };
  770. var Adt = { generate: generate };
  771. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  772. var shallow = function (old, nu) {
  773. return nu;
  774. };
  775. var deep = function (old, nu) {
  776. var bothObjects = isObject(old) && isObject(nu);
  777. return bothObjects ? deepMerge(old, nu) : nu;
  778. };
  779. var baseMerge = function (merger) {
  780. return function () {
  781. var objects = new Array(arguments.length);
  782. for (var i = 0; i < objects.length; i++) {
  783. objects[i] = arguments[i];
  784. }
  785. if (objects.length === 0) {
  786. throw new Error('Can\'t merge zero objects');
  787. }
  788. var ret = {};
  789. for (var j = 0; j < objects.length; j++) {
  790. var curObject = objects[j];
  791. for (var key in curObject) {
  792. if (hasOwnProperty$1.call(curObject, key)) {
  793. ret[key] = merger(ret[key], curObject[key]);
  794. }
  795. }
  796. }
  797. return ret;
  798. };
  799. };
  800. var deepMerge = baseMerge(deep);
  801. var merge = baseMerge(shallow);
  802. var cached = function (f) {
  803. var called = false;
  804. var r;
  805. return function () {
  806. var args = [];
  807. for (var _i = 0; _i < arguments.length; _i++) {
  808. args[_i] = arguments[_i];
  809. }
  810. if (!called) {
  811. called = true;
  812. r = f.apply(null, args);
  813. }
  814. return r;
  815. };
  816. };
  817. var adt = Adt.generate([
  818. { strict: [] },
  819. { defaultedThunk: ['fallbackThunk'] },
  820. { asOption: [] },
  821. { asDefaultedOptionThunk: ['fallbackThunk'] },
  822. { mergeWithThunk: ['baseThunk'] }
  823. ]);
  824. var defaulted = function (fallback) {
  825. return adt.defaultedThunk(constant(fallback));
  826. };
  827. var mergeWith = function (base) {
  828. return adt.mergeWithThunk(constant(base));
  829. };
  830. var strict = adt.strict;
  831. var asOption = adt.asOption;
  832. var defaultedThunk = adt.defaultedThunk;
  833. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  834. var mergeWithThunk = adt.mergeWithThunk;
  835. var comparison = Adt.generate([
  836. {
  837. bothErrors: [
  838. 'error1',
  839. 'error2'
  840. ]
  841. },
  842. {
  843. firstError: [
  844. 'error1',
  845. 'value2'
  846. ]
  847. },
  848. {
  849. secondError: [
  850. 'value1',
  851. 'error2'
  852. ]
  853. },
  854. {
  855. bothValues: [
  856. 'value1',
  857. 'value2'
  858. ]
  859. }
  860. ]);
  861. var partition$2 = function (results) {
  862. var errors = [];
  863. var values = [];
  864. each(results, function (result) {
  865. result.fold(function (err) {
  866. errors.push(err);
  867. }, function (value) {
  868. values.push(value);
  869. });
  870. });
  871. return {
  872. errors: errors,
  873. values: values
  874. };
  875. };
  876. var exclude = function (obj, fields) {
  877. var r = {};
  878. each$1(obj, function (v, k) {
  879. if (!contains(fields, k)) {
  880. r[k] = v;
  881. }
  882. });
  883. return r;
  884. };
  885. var wrap = function (key, value) {
  886. var _a;
  887. return _a = {}, _a[key] = value, _a;
  888. };
  889. var wrapAll = function (keyvalues) {
  890. var r = {};
  891. each(keyvalues, function (kv) {
  892. r[kv.key] = kv.value;
  893. });
  894. return r;
  895. };
  896. var exclude$1 = function (obj, fields) {
  897. return exclude(obj, fields);
  898. };
  899. var wrap$1 = function (key, value) {
  900. return wrap(key, value);
  901. };
  902. var wrapAll$1 = function (keyvalues) {
  903. return wrapAll(keyvalues);
  904. };
  905. var mergeValues = function (values, base) {
  906. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  907. };
  908. var mergeErrors = function (errors) {
  909. return Result.error(flatten(errors));
  910. };
  911. var consolidate = function (objs, base) {
  912. var partitions = partition$2(objs);
  913. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  914. };
  915. var mergeValues$1 = function (values, base) {
  916. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  917. };
  918. var mergeErrors$1 = function (errors) {
  919. return compose(SimpleResult.serror, flatten)(errors);
  920. };
  921. var consolidateObj = function (objects, base) {
  922. var partition = SimpleResult.partition(objects);
  923. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  924. };
  925. var consolidateArr = function (objects) {
  926. var partitions = SimpleResult.partition(objects);
  927. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  928. };
  929. var ResultCombine = {
  930. consolidateObj: consolidateObj,
  931. consolidateArr: consolidateArr
  932. };
  933. var formatObj = function (input) {
  934. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  935. };
  936. var formatErrors = function (errors) {
  937. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  938. path: [],
  939. getErrorInfo: function () {
  940. return '... (only showing first ten failures)';
  941. }
  942. }]) : errors;
  943. return map(es, function (e) {
  944. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  945. });
  946. };
  947. var nu = function (path, getErrorInfo) {
  948. return SimpleResult.serror([{
  949. path: path,
  950. getErrorInfo: getErrorInfo
  951. }]);
  952. };
  953. var missingStrict = function (path, key, obj) {
  954. return nu(path, function () {
  955. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  956. });
  957. };
  958. var missingKey = function (path, key) {
  959. return nu(path, function () {
  960. return 'Choice schema did not contain choice key: "' + key + '"';
  961. });
  962. };
  963. var missingBranch = function (path, branches, branch) {
  964. return nu(path, function () {
  965. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  966. });
  967. };
  968. var unsupportedFields = function (path, unsupported) {
  969. return nu(path, function () {
  970. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  971. });
  972. };
  973. var custom = function (path, err) {
  974. return nu(path, function () {
  975. return err;
  976. });
  977. };
  978. var adt$1 = Adt.generate([
  979. {
  980. field: [
  981. 'key',
  982. 'okey',
  983. 'presence',
  984. 'prop'
  985. ]
  986. },
  987. {
  988. state: [
  989. 'okey',
  990. 'instantiator'
  991. ]
  992. }
  993. ]);
  994. var strictAccess = function (path, obj, key) {
  995. return get(obj, key).fold(function () {
  996. return missingStrict(path, key, obj);
  997. }, SimpleResult.svalue);
  998. };
  999. var fallbackAccess = function (obj, key, fallbackThunk) {
  1000. var v = get(obj, key).fold(function () {
  1001. return fallbackThunk(obj);
  1002. }, identity);
  1003. return SimpleResult.svalue(v);
  1004. };
  1005. var optionAccess = function (obj, key) {
  1006. return SimpleResult.svalue(get(obj, key));
  1007. };
  1008. var optionDefaultedAccess = function (obj, key, fallback) {
  1009. var opt = get(obj, key).map(function (val) {
  1010. return val === true ? fallback(obj) : val;
  1011. });
  1012. return SimpleResult.svalue(opt);
  1013. };
  1014. var cExtractOne = function (path, obj, field, strength) {
  1015. return field.fold(function (key, okey, presence, prop) {
  1016. var bundle = function (av) {
  1017. var result = prop.extract(path.concat([key]), strength, av);
  1018. return SimpleResult.map(result, function (res) {
  1019. return wrap(okey, strength(res));
  1020. });
  1021. };
  1022. var bundleAsOption = function (optValue) {
  1023. return optValue.fold(function () {
  1024. var outcome = wrap(okey, strength(Optional.none()));
  1025. return SimpleResult.svalue(outcome);
  1026. }, function (ov) {
  1027. var result = prop.extract(path.concat([key]), strength, ov);
  1028. return SimpleResult.map(result, function (res) {
  1029. return wrap(okey, strength(Optional.some(res)));
  1030. });
  1031. });
  1032. };
  1033. return function () {
  1034. return presence.fold(function () {
  1035. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1036. }, function (fallbackThunk) {
  1037. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1038. }, function () {
  1039. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1040. }, function (fallbackThunk) {
  1041. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1042. }, function (baseThunk) {
  1043. var base = baseThunk(obj);
  1044. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1045. return deepMerge(base, v);
  1046. });
  1047. return SimpleResult.bind(result, bundle);
  1048. });
  1049. }();
  1050. }, function (okey, instantiator) {
  1051. var state = instantiator(obj);
  1052. return SimpleResult.svalue(wrap(okey, strength(state)));
  1053. });
  1054. };
  1055. var cExtract = function (path, obj, fields, strength) {
  1056. var results = map(fields, function (field) {
  1057. return cExtractOne(path, obj, field, strength);
  1058. });
  1059. return ResultCombine.consolidateObj(results, {});
  1060. };
  1061. var valueThunk = function (getDelegate) {
  1062. var extract = function (path, strength, val) {
  1063. return getDelegate().extract(path, strength, val);
  1064. };
  1065. var toString = function () {
  1066. return getDelegate().toString();
  1067. };
  1068. return {
  1069. extract: extract,
  1070. toString: toString
  1071. };
  1072. };
  1073. var value$1 = function (validator) {
  1074. var extract = function (path, strength, val) {
  1075. return SimpleResult.bindError(validator(val, strength), function (err) {
  1076. return custom(path, err);
  1077. });
  1078. };
  1079. var toString = function () {
  1080. return 'val';
  1081. };
  1082. return {
  1083. extract: extract,
  1084. toString: toString
  1085. };
  1086. };
  1087. var getSetKeys = function (obj) {
  1088. return keys(filter$1(obj, function (value) {
  1089. return value !== undefined && value !== null;
  1090. }));
  1091. };
  1092. var objOfOnly = function (fields) {
  1093. var delegate = objOf(fields);
  1094. var fieldNames = foldr(fields, function (acc, f) {
  1095. return f.fold(function (key) {
  1096. return deepMerge(acc, wrap$1(key, true));
  1097. }, constant(acc));
  1098. }, {});
  1099. var extract = function (path, strength, o) {
  1100. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1101. var extra = filter(keys, function (k) {
  1102. return !hasNonNullableKey(fieldNames, k);
  1103. });
  1104. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1105. };
  1106. return {
  1107. extract: extract,
  1108. toString: delegate.toString
  1109. };
  1110. };
  1111. var objOf = function (fields) {
  1112. var extract = function (path, strength, o) {
  1113. return cExtract(path, o, fields, strength);
  1114. };
  1115. var toString = function () {
  1116. var fieldStrings = map(fields, function (field) {
  1117. return field.fold(function (key, okey, presence, prop) {
  1118. return key + ' -> ' + prop.toString();
  1119. }, function (okey, _instantiator) {
  1120. return 'state(' + okey + ')';
  1121. });
  1122. });
  1123. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1124. };
  1125. return {
  1126. extract: extract,
  1127. toString: toString
  1128. };
  1129. };
  1130. var arrOf = function (prop) {
  1131. var extract = function (path, strength, array) {
  1132. var results = map(array, function (a, i) {
  1133. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1134. });
  1135. return ResultCombine.consolidateArr(results);
  1136. };
  1137. var toString = function () {
  1138. return 'array(' + prop.toString() + ')';
  1139. };
  1140. return {
  1141. extract: extract,
  1142. toString: toString
  1143. };
  1144. };
  1145. var oneOf = function (props) {
  1146. var extract = function (path, strength, val) {
  1147. var errors = [];
  1148. for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  1149. var prop = props_1[_i];
  1150. var res = prop.extract(path, strength, val);
  1151. if (res.stype === SimpleResultType.Value) {
  1152. return res;
  1153. }
  1154. errors.push(res);
  1155. }
  1156. return ResultCombine.consolidateArr(errors);
  1157. };
  1158. var toString = function () {
  1159. return 'oneOf(' + map(props, function (prop) {
  1160. return prop.toString();
  1161. }).join(', ') + ')';
  1162. };
  1163. return {
  1164. extract: extract,
  1165. toString: toString
  1166. };
  1167. };
  1168. var setOf = function (validator, prop) {
  1169. var validateKeys = function (path, keys) {
  1170. return arrOf(value$1(validator)).extract(path, identity, keys);
  1171. };
  1172. var extract = function (path, strength, o) {
  1173. var keys$1 = keys(o);
  1174. var validatedKeys = validateKeys(path, keys$1);
  1175. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1176. var schema = map(validKeys, function (vk) {
  1177. return adt$1.field(vk, vk, strict(), prop);
  1178. });
  1179. return objOf(schema).extract(path, strength, o);
  1180. });
  1181. };
  1182. var toString = function () {
  1183. return 'setOf(' + prop.toString() + ')';
  1184. };
  1185. return {
  1186. extract: extract,
  1187. toString: toString
  1188. };
  1189. };
  1190. var thunk = function (desc, processor) {
  1191. var getP = cached(function () {
  1192. return processor();
  1193. });
  1194. var extract = function (path, strength, val) {
  1195. return getP().extract(path, strength, val);
  1196. };
  1197. var toString = function () {
  1198. return getP().toString();
  1199. };
  1200. return {
  1201. extract: extract,
  1202. toString: toString
  1203. };
  1204. };
  1205. var anyValue = constant(value$1(SimpleResult.svalue));
  1206. var arrOfObj = compose(arrOf, objOf);
  1207. var state = adt$1.state;
  1208. var field = adt$1.field;
  1209. var chooseFrom = function (path, strength, input, branches, ch) {
  1210. var fields = get(branches, ch);
  1211. return fields.fold(function () {
  1212. return missingBranch(path, branches, ch);
  1213. }, function (vp) {
  1214. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1215. });
  1216. };
  1217. var choose = function (key, branches) {
  1218. var extract = function (path, strength, input) {
  1219. var choice = get(input, key);
  1220. return choice.fold(function () {
  1221. return missingKey(path, key);
  1222. }, function (chosen) {
  1223. return chooseFrom(path, strength, input, branches, chosen);
  1224. });
  1225. };
  1226. var toString = function () {
  1227. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1228. };
  1229. return {
  1230. extract: extract,
  1231. toString: toString
  1232. };
  1233. };
  1234. var _anyValue = value$1(SimpleResult.svalue);
  1235. var arrOfObj$1 = function (objFields) {
  1236. return arrOfObj(objFields);
  1237. };
  1238. var arrOfVal = function () {
  1239. return arrOf(_anyValue);
  1240. };
  1241. var valueThunkOf = valueThunk;
  1242. var valueOf = function (validator) {
  1243. return value$1(function (v) {
  1244. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1245. });
  1246. };
  1247. var setOf$1 = function (validator, prop) {
  1248. return setOf(function (v) {
  1249. return SimpleResult.fromResult(validator(v));
  1250. }, prop);
  1251. };
  1252. var extract = function (label, prop, strength, obj) {
  1253. var res = prop.extract([label], strength, obj);
  1254. return SimpleResult.mapError(res, function (errs) {
  1255. return {
  1256. input: obj,
  1257. errors: errs
  1258. };
  1259. });
  1260. };
  1261. var asRaw = function (label, prop, obj) {
  1262. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1263. };
  1264. var getOrDie = function (extraction) {
  1265. return extraction.fold(function (errInfo) {
  1266. throw new Error(formatError(errInfo));
  1267. }, identity);
  1268. };
  1269. var asRawOrDie = function (label, prop, obj) {
  1270. return getOrDie(asRaw(label, prop, obj));
  1271. };
  1272. var formatError = function (errInfo) {
  1273. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1274. };
  1275. var chooseProcessor = function (key, branches) {
  1276. return choose(key, branches);
  1277. };
  1278. var choose$1 = function (key, branches) {
  1279. return choose(key, map$2(branches, objOf));
  1280. };
  1281. var thunkOf = function (desc, schema) {
  1282. return thunk(desc, schema);
  1283. };
  1284. var anyValue$1 = constant(_anyValue);
  1285. var typedValue = function (validator, expectedType) {
  1286. return value$1(function (a) {
  1287. var actualType = typeof a;
  1288. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1289. });
  1290. };
  1291. var number = typedValue(isNumber, 'number');
  1292. var string = typedValue(isString, 'string');
  1293. var boolean = typedValue(isBoolean, 'boolean');
  1294. var functionProcessor = typedValue(isFunction, 'function');
  1295. var isPostMessageable = function (val) {
  1296. var every = function (iter, callbackFn) {
  1297. var result = iter.next();
  1298. while (!result.done) {
  1299. if (!callbackFn(result.value)) {
  1300. return false;
  1301. }
  1302. result = iter.next();
  1303. }
  1304. return true;
  1305. };
  1306. if (Object(val) !== val) {
  1307. return true;
  1308. }
  1309. switch ({}.toString.call(val).slice(8, -1)) {
  1310. case 'Boolean':
  1311. case 'Number':
  1312. case 'String':
  1313. case 'Date':
  1314. case 'RegExp':
  1315. case 'Blob':
  1316. case 'FileList':
  1317. case 'ImageData':
  1318. case 'ImageBitmap':
  1319. case 'ArrayBuffer':
  1320. return true;
  1321. case 'Array':
  1322. case 'Object':
  1323. return Object.keys(val).every(function (prop) {
  1324. return isPostMessageable(val[prop]);
  1325. });
  1326. case 'Map':
  1327. return every(val.keys(), isPostMessageable) && every(val.values(), isPostMessageable);
  1328. case 'Set':
  1329. return every(val.keys(), isPostMessageable);
  1330. default:
  1331. return false;
  1332. }
  1333. };
  1334. var postMessageable = value$1(function (a) {
  1335. return isPostMessageable(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1336. });
  1337. var validateEnum = function (values) {
  1338. return valueOf(function (value) {
  1339. return contains(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  1340. });
  1341. };
  1342. var strict$1 = function (key) {
  1343. return field(key, key, strict(), anyValue());
  1344. };
  1345. var strictOf = function (key, schema) {
  1346. return field(key, key, strict(), schema);
  1347. };
  1348. var strictNumber = function (key) {
  1349. return strictOf(key, number);
  1350. };
  1351. var strictString = function (key) {
  1352. return strictOf(key, string);
  1353. };
  1354. var strictStringEnum = function (key, values) {
  1355. return field(key, key, strict(), validateEnum(values));
  1356. };
  1357. var strictBoolean = function (key) {
  1358. return strictOf(key, boolean);
  1359. };
  1360. var strictFunction = function (key) {
  1361. return strictOf(key, functionProcessor);
  1362. };
  1363. var forbid = function (key, message) {
  1364. return field(key, key, asOption(), value$1(function (_v) {
  1365. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1366. }));
  1367. };
  1368. var strictObjOf = function (key, objSchema) {
  1369. return field(key, key, strict(), objOf(objSchema));
  1370. };
  1371. var strictArrayOfObj = function (key, objFields) {
  1372. return field(key, key, strict(), arrOfObj(objFields));
  1373. };
  1374. var strictArrayOf = function (key, schema) {
  1375. return field(key, key, strict(), arrOf(schema));
  1376. };
  1377. var option = function (key) {
  1378. return field(key, key, asOption(), anyValue());
  1379. };
  1380. var optionOf = function (key, schema) {
  1381. return field(key, key, asOption(), schema);
  1382. };
  1383. var optionNumber = function (key) {
  1384. return optionOf(key, number);
  1385. };
  1386. var optionString = function (key) {
  1387. return optionOf(key, string);
  1388. };
  1389. var optionFunction = function (key) {
  1390. return optionOf(key, functionProcessor);
  1391. };
  1392. var optionArrayOf = function (key, schema) {
  1393. return optionOf(key, arrOf(schema));
  1394. };
  1395. var optionObjOf = function (key, objSchema) {
  1396. return optionOf(key, objOf(objSchema));
  1397. };
  1398. var optionObjOfOnly = function (key, objSchema) {
  1399. return optionOf(key, objOfOnly(objSchema));
  1400. };
  1401. var defaulted$1 = function (key, fallback) {
  1402. return field(key, key, defaulted(fallback), anyValue());
  1403. };
  1404. var defaultedOf = function (key, fallback, schema) {
  1405. return field(key, key, defaulted(fallback), schema);
  1406. };
  1407. var defaultedNumber = function (key, fallback) {
  1408. return defaultedOf(key, fallback, number);
  1409. };
  1410. var defaultedString = function (key, fallback) {
  1411. return defaultedOf(key, fallback, string);
  1412. };
  1413. var defaultedStringEnum = function (key, fallback, values) {
  1414. return defaultedOf(key, fallback, validateEnum(values));
  1415. };
  1416. var defaultedBoolean = function (key, fallback) {
  1417. return defaultedOf(key, fallback, boolean);
  1418. };
  1419. var defaultedFunction = function (key, fallback) {
  1420. return defaultedOf(key, fallback, functionProcessor);
  1421. };
  1422. var defaultedPostMsg = function (key, fallback) {
  1423. return defaultedOf(key, fallback, postMessageable);
  1424. };
  1425. var defaultedArrayOf = function (key, fallback, schema) {
  1426. return defaultedOf(key, fallback, arrOf(schema));
  1427. };
  1428. var defaultedObjOf = function (key, fallback, objSchema) {
  1429. return defaultedOf(key, fallback, objOf(objSchema));
  1430. };
  1431. var state$1 = function (okey, instantiator) {
  1432. return state(okey, instantiator);
  1433. };
  1434. var Cell = function (initial) {
  1435. var value = initial;
  1436. var get = function () {
  1437. return value;
  1438. };
  1439. var set = function (v) {
  1440. value = v;
  1441. };
  1442. return {
  1443. get: get,
  1444. set: set
  1445. };
  1446. };
  1447. var fromHtml = function (html, scope) {
  1448. var doc = scope || document;
  1449. var div = doc.createElement('div');
  1450. div.innerHTML = html;
  1451. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1452. console.error('HTML does not have a single root node', html);
  1453. throw new Error('HTML must have a single root node');
  1454. }
  1455. return fromDom(div.childNodes[0]);
  1456. };
  1457. var fromTag = function (tag, scope) {
  1458. var doc = scope || document;
  1459. var node = doc.createElement(tag);
  1460. return fromDom(node);
  1461. };
  1462. var fromText = function (text, scope) {
  1463. var doc = scope || document;
  1464. var node = doc.createTextNode(text);
  1465. return fromDom(node);
  1466. };
  1467. var fromDom = function (node) {
  1468. if (node === null || node === undefined) {
  1469. throw new Error('Node cannot be null or undefined');
  1470. }
  1471. return { dom: node };
  1472. };
  1473. var fromPoint = function (docElm, x, y) {
  1474. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  1475. };
  1476. var SugarElement = {
  1477. fromHtml: fromHtml,
  1478. fromTag: fromTag,
  1479. fromText: fromText,
  1480. fromDom: fromDom,
  1481. fromPoint: fromPoint
  1482. };
  1483. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  1484. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  1485. var isiPhone = os.isiOS() && !isiPad;
  1486. var isMobile = os.isiOS() || os.isAndroid();
  1487. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  1488. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  1489. var isPhone = isiPhone || isMobile && !isTablet;
  1490. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  1491. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  1492. return {
  1493. isiPad: constant(isiPad),
  1494. isiPhone: constant(isiPhone),
  1495. isTablet: constant(isTablet),
  1496. isPhone: constant(isPhone),
  1497. isTouch: constant(isTouch),
  1498. isAndroid: os.isAndroid,
  1499. isiOS: os.isiOS,
  1500. isWebView: constant(iOSwebview),
  1501. isDesktop: constant(isDesktop)
  1502. };
  1503. };
  1504. var firstMatch = function (regexes, s) {
  1505. for (var i = 0; i < regexes.length; i++) {
  1506. var x = regexes[i];
  1507. if (x.test(s)) {
  1508. return x;
  1509. }
  1510. }
  1511. return undefined;
  1512. };
  1513. var find$2 = function (regexes, agent) {
  1514. var r = firstMatch(regexes, agent);
  1515. if (!r) {
  1516. return {
  1517. major: 0,
  1518. minor: 0
  1519. };
  1520. }
  1521. var group = function (i) {
  1522. return Number(agent.replace(r, '$' + i));
  1523. };
  1524. return nu$1(group(1), group(2));
  1525. };
  1526. var detect = function (versionRegexes, agent) {
  1527. var cleanedAgent = String(agent).toLowerCase();
  1528. if (versionRegexes.length === 0) {
  1529. return unknown();
  1530. }
  1531. return find$2(versionRegexes, cleanedAgent);
  1532. };
  1533. var unknown = function () {
  1534. return nu$1(0, 0);
  1535. };
  1536. var nu$1 = function (major, minor) {
  1537. return {
  1538. major: major,
  1539. minor: minor
  1540. };
  1541. };
  1542. var Version = {
  1543. nu: nu$1,
  1544. detect: detect,
  1545. unknown: unknown
  1546. };
  1547. var detect$1 = function (candidates, userAgent) {
  1548. var agent = String(userAgent).toLowerCase();
  1549. return find(candidates, function (candidate) {
  1550. return candidate.search(agent);
  1551. });
  1552. };
  1553. var detectBrowser = function (browsers, userAgent) {
  1554. return detect$1(browsers, userAgent).map(function (browser) {
  1555. var version = Version.detect(browser.versionRegexes, userAgent);
  1556. return {
  1557. current: browser.name,
  1558. version: version
  1559. };
  1560. });
  1561. };
  1562. var detectOs = function (oses, userAgent) {
  1563. return detect$1(oses, userAgent).map(function (os) {
  1564. var version = Version.detect(os.versionRegexes, userAgent);
  1565. return {
  1566. current: os.name,
  1567. version: version
  1568. };
  1569. });
  1570. };
  1571. var UaString = {
  1572. detectBrowser: detectBrowser,
  1573. detectOs: detectOs
  1574. };
  1575. var checkRange = function (str, substr, start) {
  1576. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  1577. };
  1578. var contains$1 = function (str, substr) {
  1579. return str.indexOf(substr) !== -1;
  1580. };
  1581. var endsWith = function (str, suffix) {
  1582. return checkRange(str, suffix, str.length - suffix.length);
  1583. };
  1584. var blank = function (r) {
  1585. return function (s) {
  1586. return s.replace(r, '');
  1587. };
  1588. };
  1589. var trim = blank(/^\s+|\s+$/g);
  1590. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1591. var checkContains = function (target) {
  1592. return function (uastring) {
  1593. return contains$1(uastring, target);
  1594. };
  1595. };
  1596. var browsers = [
  1597. {
  1598. name: 'Edge',
  1599. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1600. search: function (uastring) {
  1601. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1602. }
  1603. },
  1604. {
  1605. name: 'Chrome',
  1606. versionRegexes: [
  1607. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1608. normalVersionRegex
  1609. ],
  1610. search: function (uastring) {
  1611. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1612. }
  1613. },
  1614. {
  1615. name: 'IE',
  1616. versionRegexes: [
  1617. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1618. /.*?rv:([0-9]+)\.([0-9]+).*/
  1619. ],
  1620. search: function (uastring) {
  1621. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1622. }
  1623. },
  1624. {
  1625. name: 'Opera',
  1626. versionRegexes: [
  1627. normalVersionRegex,
  1628. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1629. ],
  1630. search: checkContains('opera')
  1631. },
  1632. {
  1633. name: 'Firefox',
  1634. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1635. search: checkContains('firefox')
  1636. },
  1637. {
  1638. name: 'Safari',
  1639. versionRegexes: [
  1640. normalVersionRegex,
  1641. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1642. ],
  1643. search: function (uastring) {
  1644. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1645. }
  1646. }
  1647. ];
  1648. var oses = [
  1649. {
  1650. name: 'Windows',
  1651. search: checkContains('win'),
  1652. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1653. },
  1654. {
  1655. name: 'iOS',
  1656. search: function (uastring) {
  1657. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1658. },
  1659. versionRegexes: [
  1660. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1661. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1662. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1663. ]
  1664. },
  1665. {
  1666. name: 'Android',
  1667. search: checkContains('android'),
  1668. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1669. },
  1670. {
  1671. name: 'OSX',
  1672. search: checkContains('mac os x'),
  1673. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  1674. },
  1675. {
  1676. name: 'Linux',
  1677. search: checkContains('linux'),
  1678. versionRegexes: []
  1679. },
  1680. {
  1681. name: 'Solaris',
  1682. search: checkContains('sunos'),
  1683. versionRegexes: []
  1684. },
  1685. {
  1686. name: 'FreeBSD',
  1687. search: checkContains('freebsd'),
  1688. versionRegexes: []
  1689. },
  1690. {
  1691. name: 'ChromeOS',
  1692. search: checkContains('cros'),
  1693. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  1694. }
  1695. ];
  1696. var PlatformInfo = {
  1697. browsers: constant(browsers),
  1698. oses: constant(oses)
  1699. };
  1700. var edge = 'Edge';
  1701. var chrome = 'Chrome';
  1702. var ie = 'IE';
  1703. var opera = 'Opera';
  1704. var firefox = 'Firefox';
  1705. var safari = 'Safari';
  1706. var unknown$1 = function () {
  1707. return nu$2({
  1708. current: undefined,
  1709. version: Version.unknown()
  1710. });
  1711. };
  1712. var nu$2 = function (info) {
  1713. var current = info.current;
  1714. var version = info.version;
  1715. var isBrowser = function (name) {
  1716. return function () {
  1717. return current === name;
  1718. };
  1719. };
  1720. return {
  1721. current: current,
  1722. version: version,
  1723. isEdge: isBrowser(edge),
  1724. isChrome: isBrowser(chrome),
  1725. isIE: isBrowser(ie),
  1726. isOpera: isBrowser(opera),
  1727. isFirefox: isBrowser(firefox),
  1728. isSafari: isBrowser(safari)
  1729. };
  1730. };
  1731. var Browser = {
  1732. unknown: unknown$1,
  1733. nu: nu$2,
  1734. edge: constant(edge),
  1735. chrome: constant(chrome),
  1736. ie: constant(ie),
  1737. opera: constant(opera),
  1738. firefox: constant(firefox),
  1739. safari: constant(safari)
  1740. };
  1741. var windows = 'Windows';
  1742. var ios = 'iOS';
  1743. var android = 'Android';
  1744. var linux = 'Linux';
  1745. var osx = 'OSX';
  1746. var solaris = 'Solaris';
  1747. var freebsd = 'FreeBSD';
  1748. var chromeos = 'ChromeOS';
  1749. var unknown$2 = function () {
  1750. return nu$3({
  1751. current: undefined,
  1752. version: Version.unknown()
  1753. });
  1754. };
  1755. var nu$3 = function (info) {
  1756. var current = info.current;
  1757. var version = info.version;
  1758. var isOS = function (name) {
  1759. return function () {
  1760. return current === name;
  1761. };
  1762. };
  1763. return {
  1764. current: current,
  1765. version: version,
  1766. isWindows: isOS(windows),
  1767. isiOS: isOS(ios),
  1768. isAndroid: isOS(android),
  1769. isOSX: isOS(osx),
  1770. isLinux: isOS(linux),
  1771. isSolaris: isOS(solaris),
  1772. isFreeBSD: isOS(freebsd),
  1773. isChromeOS: isOS(chromeos)
  1774. };
  1775. };
  1776. var OperatingSystem = {
  1777. unknown: unknown$2,
  1778. nu: nu$3,
  1779. windows: constant(windows),
  1780. ios: constant(ios),
  1781. android: constant(android),
  1782. linux: constant(linux),
  1783. osx: constant(osx),
  1784. solaris: constant(solaris),
  1785. freebsd: constant(freebsd),
  1786. chromeos: constant(chromeos)
  1787. };
  1788. var detect$2 = function (userAgent, mediaMatch) {
  1789. var browsers = PlatformInfo.browsers();
  1790. var oses = PlatformInfo.oses();
  1791. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  1792. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1793. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1794. return {
  1795. browser: browser,
  1796. os: os,
  1797. deviceType: deviceType
  1798. };
  1799. };
  1800. var PlatformDetection = { detect: detect$2 };
  1801. var mediaMatch = function (query) {
  1802. return window.matchMedia(query).matches;
  1803. };
  1804. var platform = cached(function () {
  1805. return PlatformDetection.detect(navigator.userAgent, mediaMatch);
  1806. });
  1807. var detect$3 = function () {
  1808. return platform();
  1809. };
  1810. var compareDocumentPosition = function (a, b, match) {
  1811. return (a.compareDocumentPosition(b) & match) !== 0;
  1812. };
  1813. var documentPositionContainedBy = function (a, b) {
  1814. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1815. };
  1816. var DOCUMENT = 9;
  1817. var DOCUMENT_FRAGMENT = 11;
  1818. var ELEMENT = 1;
  1819. var TEXT = 3;
  1820. var is = function (element, selector) {
  1821. var dom = element.dom;
  1822. if (dom.nodeType !== ELEMENT) {
  1823. return false;
  1824. } else {
  1825. var elem = dom;
  1826. if (elem.matches !== undefined) {
  1827. return elem.matches(selector);
  1828. } else if (elem.msMatchesSelector !== undefined) {
  1829. return elem.msMatchesSelector(selector);
  1830. } else if (elem.webkitMatchesSelector !== undefined) {
  1831. return elem.webkitMatchesSelector(selector);
  1832. } else if (elem.mozMatchesSelector !== undefined) {
  1833. return elem.mozMatchesSelector(selector);
  1834. } else {
  1835. throw new Error('Browser lacks native selectors');
  1836. }
  1837. }
  1838. };
  1839. var bypassSelector = function (dom) {
  1840. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1841. };
  1842. var all = function (selector, scope) {
  1843. var base = scope === undefined ? document : scope.dom;
  1844. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  1845. };
  1846. var one = function (selector, scope) {
  1847. var base = scope === undefined ? document : scope.dom;
  1848. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1849. };
  1850. var eq$1 = function (e1, e2) {
  1851. return e1.dom === e2.dom;
  1852. };
  1853. var regularContains = function (e1, e2) {
  1854. var d1 = e1.dom;
  1855. var d2 = e2.dom;
  1856. return d1 === d2 ? false : d1.contains(d2);
  1857. };
  1858. var ieContains = function (e1, e2) {
  1859. return documentPositionContainedBy(e1.dom, e2.dom);
  1860. };
  1861. var contains$2 = function (e1, e2) {
  1862. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1863. };
  1864. var ensureIsRoot = function (isRoot) {
  1865. return isFunction(isRoot) ? isRoot : never;
  1866. };
  1867. var ancestor = function (scope, transform, isRoot) {
  1868. var element = scope.dom;
  1869. var stop = ensureIsRoot(isRoot);
  1870. while (element.parentNode) {
  1871. element = element.parentNode;
  1872. var el = SugarElement.fromDom(element);
  1873. var transformed = transform(el);
  1874. if (transformed.isSome()) {
  1875. return transformed;
  1876. } else if (stop(el)) {
  1877. break;
  1878. }
  1879. }
  1880. return Optional.none();
  1881. };
  1882. var closest = function (scope, transform, isRoot) {
  1883. var current = transform(scope);
  1884. var stop = ensureIsRoot(isRoot);
  1885. return current.orThunk(function () {
  1886. return stop(scope) ? Optional.none() : ancestor(scope, transform, stop);
  1887. });
  1888. };
  1889. var isSource = function (component, simulatedEvent) {
  1890. return eq$1(component.element, simulatedEvent.event.target);
  1891. };
  1892. var nu$4 = function (parts) {
  1893. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  1894. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1895. }
  1896. return asRawOrDie('Extracting event.handler', objOfOnly([
  1897. defaulted$1('can', always),
  1898. defaulted$1('abort', never),
  1899. defaulted$1('run', noop)
  1900. ]), parts);
  1901. };
  1902. var all$1 = function (handlers, f) {
  1903. return function () {
  1904. var args = [];
  1905. for (var _i = 0; _i < arguments.length; _i++) {
  1906. args[_i] = arguments[_i];
  1907. }
  1908. return foldl(handlers, function (acc, handler) {
  1909. return acc && f(handler).apply(undefined, args);
  1910. }, true);
  1911. };
  1912. };
  1913. var any = function (handlers, f) {
  1914. return function () {
  1915. var args = [];
  1916. for (var _i = 0; _i < arguments.length; _i++) {
  1917. args[_i] = arguments[_i];
  1918. }
  1919. return foldl(handlers, function (acc, handler) {
  1920. return acc || f(handler).apply(undefined, args);
  1921. }, false);
  1922. };
  1923. };
  1924. var read = function (handler) {
  1925. return isFunction(handler) ? {
  1926. can: constant(true),
  1927. abort: constant(false),
  1928. run: handler
  1929. } : handler;
  1930. };
  1931. var fuse = function (handlers) {
  1932. var can = all$1(handlers, function (handler) {
  1933. return handler.can;
  1934. });
  1935. var abort = any(handlers, function (handler) {
  1936. return handler.abort;
  1937. });
  1938. var run = function () {
  1939. var args = [];
  1940. for (var _i = 0; _i < arguments.length; _i++) {
  1941. args[_i] = arguments[_i];
  1942. }
  1943. each(handlers, function (handler) {
  1944. handler.run.apply(undefined, args);
  1945. });
  1946. };
  1947. return nu$4({
  1948. can: can,
  1949. abort: abort,
  1950. run: run
  1951. });
  1952. };
  1953. var constant$1 = constant;
  1954. var touchstart = constant$1('touchstart');
  1955. var touchmove = constant$1('touchmove');
  1956. var touchend = constant$1('touchend');
  1957. var touchcancel = constant$1('touchcancel');
  1958. var mousedown = constant$1('mousedown');
  1959. var mousemove = constant$1('mousemove');
  1960. var mouseout = constant$1('mouseout');
  1961. var mouseup = constant$1('mouseup');
  1962. var mouseover = constant$1('mouseover');
  1963. var focusin = constant$1('focusin');
  1964. var focusout = constant$1('focusout');
  1965. var keydown = constant$1('keydown');
  1966. var keyup = constant$1('keyup');
  1967. var input = constant$1('input');
  1968. var change = constant$1('change');
  1969. var click = constant$1('click');
  1970. var transitionend = constant$1('transitionend');
  1971. var selectstart = constant$1('selectstart');
  1972. var prefixName = function (name) {
  1973. return constant('alloy.' + name);
  1974. };
  1975. var alloy = { tap: prefixName('tap') };
  1976. var focus = prefixName('focus');
  1977. var postBlur = prefixName('blur.post');
  1978. var postPaste = prefixName('paste.post');
  1979. var receive = prefixName('receive');
  1980. var execute = prefixName('execute');
  1981. var focusItem = prefixName('focus.item');
  1982. var tap = alloy.tap;
  1983. var longpress = prefixName('longpress');
  1984. var sandboxClose = prefixName('sandbox.close');
  1985. var typeaheadCancel = prefixName('typeahead.cancel');
  1986. var systemInit = prefixName('system.init');
  1987. var documentTouchmove = prefixName('system.touchmove');
  1988. var documentTouchend = prefixName('system.touchend');
  1989. var windowScroll = prefixName('system.scroll');
  1990. var windowResize = prefixName('system.resize');
  1991. var attachedToDom = prefixName('system.attached');
  1992. var detachedFromDom = prefixName('system.detached');
  1993. var dismissRequested = prefixName('system.dismissRequested');
  1994. var repositionRequested = prefixName('system.repositionRequested');
  1995. var focusShifted = prefixName('focusmanager.shifted');
  1996. var slotVisibility = prefixName('slotcontainer.visibility');
  1997. var changeTab = prefixName('change.tab');
  1998. var dismissTab = prefixName('dismiss.tab');
  1999. var highlight = prefixName('highlight');
  2000. var dehighlight = prefixName('dehighlight');
  2001. var emit = function (component, event) {
  2002. dispatchWith(component, component.element, event, {});
  2003. };
  2004. var emitWith = function (component, event, properties) {
  2005. dispatchWith(component, component.element, event, properties);
  2006. };
  2007. var emitExecute = function (component) {
  2008. emit(component, execute());
  2009. };
  2010. var dispatch = function (component, target, event) {
  2011. dispatchWith(component, target, event, {});
  2012. };
  2013. var dispatchWith = function (component, target, event, properties) {
  2014. var data = __assign({ target: target }, properties);
  2015. component.getSystem().triggerEvent(event, target, data);
  2016. };
  2017. var dispatchEvent = function (component, target, event, simulatedEvent) {
  2018. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  2019. };
  2020. var derive = function (configs) {
  2021. return wrapAll$1(configs);
  2022. };
  2023. var abort = function (name, predicate) {
  2024. return {
  2025. key: name,
  2026. value: nu$4({ abort: predicate })
  2027. };
  2028. };
  2029. var can = function (name, predicate) {
  2030. return {
  2031. key: name,
  2032. value: nu$4({ can: predicate })
  2033. };
  2034. };
  2035. var preventDefault = function (name) {
  2036. return {
  2037. key: name,
  2038. value: nu$4({
  2039. run: function (component, simulatedEvent) {
  2040. simulatedEvent.event.prevent();
  2041. }
  2042. })
  2043. };
  2044. };
  2045. var run = function (name, handler) {
  2046. return {
  2047. key: name,
  2048. value: nu$4({ run: handler })
  2049. };
  2050. };
  2051. var runActionExtra = function (name, action, extra) {
  2052. return {
  2053. key: name,
  2054. value: nu$4({
  2055. run: function (component, simulatedEvent) {
  2056. action.apply(undefined, [
  2057. component,
  2058. simulatedEvent
  2059. ].concat(extra));
  2060. }
  2061. })
  2062. };
  2063. };
  2064. var runOnName = function (name) {
  2065. return function (handler) {
  2066. return run(name, handler);
  2067. };
  2068. };
  2069. var runOnSourceName = function (name) {
  2070. return function (handler) {
  2071. return {
  2072. key: name,
  2073. value: nu$4({
  2074. run: function (component, simulatedEvent) {
  2075. if (isSource(component, simulatedEvent)) {
  2076. handler(component, simulatedEvent);
  2077. }
  2078. }
  2079. })
  2080. };
  2081. };
  2082. };
  2083. var redirectToUid = function (name, uid) {
  2084. return run(name, function (component, simulatedEvent) {
  2085. component.getSystem().getByUid(uid).each(function (redirectee) {
  2086. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2087. });
  2088. });
  2089. };
  2090. var redirectToPart = function (name, detail, partName) {
  2091. var uid = detail.partUids[partName];
  2092. return redirectToUid(name, uid);
  2093. };
  2094. var runWithTarget = function (name, f) {
  2095. return run(name, function (component, simulatedEvent) {
  2096. var ev = simulatedEvent.event;
  2097. var target = component.getSystem().getByDom(ev.target).fold(function () {
  2098. var closest$1 = closest(ev.target, function (el) {
  2099. return component.getSystem().getByDom(el).toOptional();
  2100. }, never);
  2101. return closest$1.getOr(component);
  2102. }, function (c) {
  2103. return c;
  2104. });
  2105. f(component, target, simulatedEvent);
  2106. });
  2107. };
  2108. var cutter = function (name) {
  2109. return run(name, function (component, simulatedEvent) {
  2110. simulatedEvent.cut();
  2111. });
  2112. };
  2113. var stopper = function (name) {
  2114. return run(name, function (component, simulatedEvent) {
  2115. simulatedEvent.stop();
  2116. });
  2117. };
  2118. var runOnSource = function (name, f) {
  2119. return runOnSourceName(name)(f);
  2120. };
  2121. var runOnAttached = runOnSourceName(attachedToDom());
  2122. var runOnDetached = runOnSourceName(detachedFromDom());
  2123. var runOnInit = runOnSourceName(systemInit());
  2124. var runOnExecute = runOnName(execute());
  2125. var Global = typeof window !== 'undefined' ? window : Function('return this;')();
  2126. var name = function (element) {
  2127. var r = element.dom.nodeName;
  2128. return r.toLowerCase();
  2129. };
  2130. var type = function (element) {
  2131. return element.dom.nodeType;
  2132. };
  2133. var isType$1 = function (t) {
  2134. return function (element) {
  2135. return type(element) === t;
  2136. };
  2137. };
  2138. var isElement = isType$1(ELEMENT);
  2139. var isText = isType$1(TEXT);
  2140. var isDocument = isType$1(DOCUMENT);
  2141. var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT);
  2142. var owner = function (element) {
  2143. return SugarElement.fromDom(element.dom.ownerDocument);
  2144. };
  2145. var documentOrOwner = function (dos) {
  2146. return isDocument(dos) ? dos : owner(dos);
  2147. };
  2148. var documentElement = function (element) {
  2149. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  2150. };
  2151. var defaultView = function (element) {
  2152. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  2153. };
  2154. var parent = function (element) {
  2155. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  2156. };
  2157. var parentNode = function (element) {
  2158. return parent(element);
  2159. };
  2160. var offsetParent = function (element) {
  2161. return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  2162. };
  2163. var nextSibling = function (element) {
  2164. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  2165. };
  2166. var children = function (element) {
  2167. return map(element.dom.childNodes, SugarElement.fromDom);
  2168. };
  2169. var child = function (element, index) {
  2170. var cs = element.dom.childNodes;
  2171. return Optional.from(cs[index]).map(SugarElement.fromDom);
  2172. };
  2173. var firstChild = function (element) {
  2174. return child(element, 0);
  2175. };
  2176. var before = function (marker, element) {
  2177. var parent$1 = parent(marker);
  2178. parent$1.each(function (v) {
  2179. v.dom.insertBefore(element.dom, marker.dom);
  2180. });
  2181. };
  2182. var after = function (marker, element) {
  2183. var sibling = nextSibling(marker);
  2184. sibling.fold(function () {
  2185. var parent$1 = parent(marker);
  2186. parent$1.each(function (v) {
  2187. append(v, element);
  2188. });
  2189. }, function (v) {
  2190. before(v, element);
  2191. });
  2192. };
  2193. var prepend = function (parent, element) {
  2194. var firstChild$1 = firstChild(parent);
  2195. firstChild$1.fold(function () {
  2196. append(parent, element);
  2197. }, function (v) {
  2198. parent.dom.insertBefore(element.dom, v.dom);
  2199. });
  2200. };
  2201. var append = function (parent, element) {
  2202. parent.dom.appendChild(element.dom);
  2203. };
  2204. var appendAt = function (parent, element, index) {
  2205. child(parent, index).fold(function () {
  2206. append(parent, element);
  2207. }, function (v) {
  2208. before(v, element);
  2209. });
  2210. };
  2211. var before$1 = function (marker, elements) {
  2212. each(elements, function (x) {
  2213. before(marker, x);
  2214. });
  2215. };
  2216. var append$1 = function (parent, elements) {
  2217. each(elements, function (x) {
  2218. append(parent, x);
  2219. });
  2220. };
  2221. var empty = function (element) {
  2222. element.dom.textContent = '';
  2223. each(children(element), function (rogue) {
  2224. remove(rogue);
  2225. });
  2226. };
  2227. var remove = function (element) {
  2228. var dom = element.dom;
  2229. if (dom.parentNode !== null) {
  2230. dom.parentNode.removeChild(dom);
  2231. }
  2232. };
  2233. var unwrap = function (wrapper) {
  2234. var children$1 = children(wrapper);
  2235. if (children$1.length > 0) {
  2236. before$1(wrapper, children$1);
  2237. }
  2238. remove(wrapper);
  2239. };
  2240. var fromHtml$1 = function (html, scope) {
  2241. var doc = scope || document;
  2242. var div = doc.createElement('div');
  2243. div.innerHTML = html;
  2244. return children(SugarElement.fromDom(div));
  2245. };
  2246. var get$1 = function (element) {
  2247. return element.dom.innerHTML;
  2248. };
  2249. var set = function (element, content) {
  2250. var owner$1 = owner(element);
  2251. var docDom = owner$1.dom;
  2252. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2253. var contentElements = fromHtml$1(content, docDom);
  2254. append$1(fragment, contentElements);
  2255. empty(element);
  2256. append(element, fragment);
  2257. };
  2258. var getOuter = function (element) {
  2259. var container = SugarElement.fromTag('div');
  2260. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2261. append(container, clone);
  2262. return get$1(container);
  2263. };
  2264. var rawSet = function (dom, key, value) {
  2265. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2266. dom.setAttribute(key, value + '');
  2267. } else {
  2268. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2269. throw new Error('Attribute value was not simple');
  2270. }
  2271. };
  2272. var set$1 = function (element, key, value) {
  2273. rawSet(element.dom, key, value);
  2274. };
  2275. var setAll = function (element, attrs) {
  2276. var dom = element.dom;
  2277. each$1(attrs, function (v, k) {
  2278. rawSet(dom, k, v);
  2279. });
  2280. };
  2281. var get$2 = function (element, key) {
  2282. var v = element.dom.getAttribute(key);
  2283. return v === null ? undefined : v;
  2284. };
  2285. var getOpt = function (element, key) {
  2286. return Optional.from(get$2(element, key));
  2287. };
  2288. var has$1 = function (element, key) {
  2289. var dom = element.dom;
  2290. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2291. };
  2292. var remove$1 = function (element, key) {
  2293. element.dom.removeAttribute(key);
  2294. };
  2295. var clone = function (original, isDeep) {
  2296. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2297. };
  2298. var shallow$1 = function (original) {
  2299. return clone(original, false);
  2300. };
  2301. var getHtml = function (element) {
  2302. var clone = shallow$1(element);
  2303. return getOuter(clone);
  2304. };
  2305. var element = function (elem) {
  2306. return getHtml(elem);
  2307. };
  2308. var isRecursive = function (component, originator, target) {
  2309. return eq$1(originator, component.element) && !eq$1(originator, target);
  2310. };
  2311. var events = derive([can(focus(), function (component, simulatedEvent) {
  2312. var event = simulatedEvent.event;
  2313. var originator = event.originator;
  2314. var target = event.target;
  2315. if (isRecursive(component, originator, target)) {
  2316. console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  2317. return false;
  2318. } else {
  2319. return true;
  2320. }
  2321. })]);
  2322. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2323. __proto__: null,
  2324. events: events
  2325. });
  2326. var unique = 0;
  2327. var generate$1 = function (prefix) {
  2328. var date = new Date();
  2329. var time = date.getTime();
  2330. var random = Math.floor(Math.random() * 1000000000);
  2331. unique++;
  2332. return prefix + '_' + random + unique + String(time);
  2333. };
  2334. var prefix = constant('alloy-id-');
  2335. var idAttr = constant('data-alloy-id');
  2336. var prefix$1 = prefix();
  2337. var idAttr$1 = idAttr();
  2338. var write = function (label, elem) {
  2339. var id = generate$1(prefix$1 + label);
  2340. writeOnly(elem, id);
  2341. return id;
  2342. };
  2343. var writeOnly = function (elem, uid) {
  2344. Object.defineProperty(elem.dom, idAttr$1, {
  2345. value: uid,
  2346. writable: true
  2347. });
  2348. };
  2349. var read$1 = function (elem) {
  2350. var id = isElement(elem) ? elem.dom[idAttr$1] : null;
  2351. return Optional.from(id);
  2352. };
  2353. var generate$2 = function (prefix) {
  2354. return generate$1(prefix);
  2355. };
  2356. var make = identity;
  2357. var NoContextApi = function (getComp) {
  2358. var fail = function (event) {
  2359. return function () {
  2360. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : ''));
  2361. };
  2362. };
  2363. return {
  2364. debugInfo: constant('fake'),
  2365. triggerEvent: fail('triggerEvent'),
  2366. triggerFocus: fail('triggerFocus'),
  2367. triggerEscape: fail('triggerEscape'),
  2368. build: fail('build'),
  2369. addToWorld: fail('addToWorld'),
  2370. removeFromWorld: fail('removeFromWorld'),
  2371. addToGui: fail('addToGui'),
  2372. removeFromGui: fail('removeFromGui'),
  2373. getByUid: fail('getByUid'),
  2374. getByDom: fail('getByDom'),
  2375. broadcast: fail('broadcast'),
  2376. broadcastOn: fail('broadcastOn'),
  2377. broadcastEvent: fail('broadcastEvent'),
  2378. isConnected: never
  2379. };
  2380. };
  2381. var singleton = NoContextApi();
  2382. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2383. var delegate = apiFunction.toString();
  2384. var endIndex = delegate.indexOf(')') + 1;
  2385. var openBracketIndex = delegate.indexOf('(');
  2386. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2387. f.toFunctionAnnotation = function () {
  2388. return {
  2389. name: apiName,
  2390. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2391. };
  2392. };
  2393. return f;
  2394. };
  2395. var cleanParameters = function (parameters) {
  2396. return map(parameters, function (p) {
  2397. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2398. });
  2399. };
  2400. var markAsExtraApi = function (f, extraName) {
  2401. var delegate = f.toString();
  2402. var endIndex = delegate.indexOf(')') + 1;
  2403. var openBracketIndex = delegate.indexOf('(');
  2404. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2405. f.toFunctionAnnotation = function () {
  2406. return {
  2407. name: extraName,
  2408. parameters: cleanParameters(parameters)
  2409. };
  2410. };
  2411. return f;
  2412. };
  2413. var markAsSketchApi = function (f, apiFunction) {
  2414. var delegate = apiFunction.toString();
  2415. var endIndex = delegate.indexOf(')') + 1;
  2416. var openBracketIndex = delegate.indexOf('(');
  2417. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2418. f.toFunctionAnnotation = function () {
  2419. return {
  2420. name: 'OVERRIDE',
  2421. parameters: cleanParameters(parameters.slice(1))
  2422. };
  2423. };
  2424. return f;
  2425. };
  2426. var premadeTag = generate$1('alloy-premade');
  2427. var premade = function (comp) {
  2428. return wrap$1(premadeTag, comp);
  2429. };
  2430. var getPremade = function (spec) {
  2431. return get(spec, premadeTag);
  2432. };
  2433. var makeApi = function (f) {
  2434. return markAsSketchApi(function (component) {
  2435. var rest = [];
  2436. for (var _i = 1; _i < arguments.length; _i++) {
  2437. rest[_i - 1] = arguments[_i];
  2438. }
  2439. return f.apply(void 0, __spreadArrays([
  2440. component.getApis(),
  2441. component
  2442. ], rest));
  2443. }, f);
  2444. };
  2445. var NoState = {
  2446. init: function () {
  2447. return nu$5({
  2448. readState: function () {
  2449. return 'No State required';
  2450. }
  2451. });
  2452. }
  2453. };
  2454. var nu$5 = function (spec) {
  2455. return spec;
  2456. };
  2457. var generateFrom = function (spec, all) {
  2458. var schema = map(all, function (a) {
  2459. return optionObjOf(a.name(), [
  2460. strict$1('config'),
  2461. defaulted$1('state', NoState)
  2462. ]);
  2463. });
  2464. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2465. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2466. }, function (v) {
  2467. return v;
  2468. });
  2469. return {
  2470. list: all,
  2471. data: map$2(validated, function (optBlobThunk) {
  2472. var output = optBlobThunk.map(function (blob) {
  2473. return {
  2474. config: blob.config,
  2475. state: blob.state.init(blob.config)
  2476. };
  2477. });
  2478. return function () {
  2479. return output;
  2480. };
  2481. })
  2482. };
  2483. };
  2484. var getBehaviours = function (bData) {
  2485. return bData.list;
  2486. };
  2487. var getData = function (bData) {
  2488. return bData.data;
  2489. };
  2490. var byInnerKey = function (data, tuple) {
  2491. var r = {};
  2492. each$1(data, function (detail, key) {
  2493. each$1(detail, function (value, indexKey) {
  2494. var chain = get(r, indexKey).getOr([]);
  2495. r[indexKey] = chain.concat([tuple(key, value)]);
  2496. });
  2497. });
  2498. return r;
  2499. };
  2500. var nu$6 = function (s) {
  2501. return {
  2502. classes: s.classes !== undefined ? s.classes : [],
  2503. attributes: s.attributes !== undefined ? s.attributes : {},
  2504. styles: s.styles !== undefined ? s.styles : {}
  2505. };
  2506. };
  2507. var merge$1 = function (defnA, mod) {
  2508. return __assign(__assign({}, defnA), {
  2509. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2510. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2511. classes: defnA.classes.concat(mod.classes)
  2512. });
  2513. };
  2514. var combine = function (info, baseMod, behaviours, base) {
  2515. var modsByBehaviour = __assign({}, baseMod);
  2516. each(behaviours, function (behaviour) {
  2517. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2518. });
  2519. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  2520. return {
  2521. name: name,
  2522. modification: modification
  2523. };
  2524. });
  2525. var combineObjects = function (objects) {
  2526. return foldr(objects, function (b, a) {
  2527. return __assign(__assign({}, a.modification), b);
  2528. }, {});
  2529. };
  2530. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  2531. return a.modification.concat(b);
  2532. }, []);
  2533. var combinedAttributes = combineObjects(byAspect.attributes);
  2534. var combinedStyles = combineObjects(byAspect.styles);
  2535. return nu$6({
  2536. classes: combinedClasses,
  2537. attributes: combinedAttributes,
  2538. styles: combinedStyles
  2539. });
  2540. };
  2541. var sortKeys = function (label, keyName, array, order) {
  2542. try {
  2543. var sorted = sort(array, function (a, b) {
  2544. var aKey = a[keyName];
  2545. var bKey = b[keyName];
  2546. var aIndex = order.indexOf(aKey);
  2547. var bIndex = order.indexOf(bKey);
  2548. if (aIndex === -1) {
  2549. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2550. }
  2551. if (bIndex === -1) {
  2552. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2553. }
  2554. if (aIndex < bIndex) {
  2555. return -1;
  2556. } else if (bIndex < aIndex) {
  2557. return 1;
  2558. } else {
  2559. return 0;
  2560. }
  2561. });
  2562. return Result.value(sorted);
  2563. } catch (err) {
  2564. return Result.error([err]);
  2565. }
  2566. };
  2567. var uncurried = function (handler, purpose) {
  2568. return {
  2569. handler: handler,
  2570. purpose: purpose
  2571. };
  2572. };
  2573. var curried = function (handler, purpose) {
  2574. return {
  2575. cHandler: handler,
  2576. purpose: purpose
  2577. };
  2578. };
  2579. var curryArgs = function (descHandler, extraArgs) {
  2580. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  2581. };
  2582. var getCurried = function (descHandler) {
  2583. return descHandler.cHandler;
  2584. };
  2585. var behaviourTuple = function (name, handler) {
  2586. return {
  2587. name: name,
  2588. handler: handler
  2589. };
  2590. };
  2591. var nameToHandlers = function (behaviours, info) {
  2592. var r = {};
  2593. each(behaviours, function (behaviour) {
  2594. r[behaviour.name()] = behaviour.handlers(info);
  2595. });
  2596. return r;
  2597. };
  2598. var groupByEvents = function (info, behaviours, base) {
  2599. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  2600. return byInnerKey(behaviourEvents, behaviourTuple);
  2601. };
  2602. var combine$1 = function (info, eventOrder, behaviours, base) {
  2603. var byEventName = groupByEvents(info, behaviours, base);
  2604. return combineGroups(byEventName, eventOrder);
  2605. };
  2606. var assemble = function (rawHandler) {
  2607. var handler = read(rawHandler);
  2608. return function (component, simulatedEvent) {
  2609. var rest = [];
  2610. for (var _i = 2; _i < arguments.length; _i++) {
  2611. rest[_i - 2] = arguments[_i];
  2612. }
  2613. var args = [
  2614. component,
  2615. simulatedEvent
  2616. ].concat(rest);
  2617. if (handler.abort.apply(undefined, args)) {
  2618. simulatedEvent.stop();
  2619. } else if (handler.can.apply(undefined, args)) {
  2620. handler.run.apply(undefined, args);
  2621. }
  2622. };
  2623. };
  2624. var missingOrderError = function (eventName, tuples) {
  2625. 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(tuples, function (c) {
  2626. return c.name;
  2627. }), null, 2)]);
  2628. };
  2629. var fuse$1 = function (tuples, eventOrder, eventName) {
  2630. var order = eventOrder[eventName];
  2631. if (!order) {
  2632. return missingOrderError(eventName, tuples);
  2633. } else {
  2634. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  2635. var handlers = map(sortedTuples, function (tuple) {
  2636. return tuple.handler;
  2637. });
  2638. return fuse(handlers);
  2639. });
  2640. }
  2641. };
  2642. var combineGroups = function (byEventName, eventOrder) {
  2643. var r = mapToArray(byEventName, function (tuples, eventName) {
  2644. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse$1(tuples, eventOrder, eventName);
  2645. return combined.map(function (handler) {
  2646. var assembled = assemble(handler);
  2647. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  2648. return exists(tuples, function (t) {
  2649. return t.name === o;
  2650. });
  2651. }).join(' > ') : tuples[0].name;
  2652. return wrap$1(eventName, uncurried(assembled, purpose));
  2653. });
  2654. });
  2655. return consolidate(r, {});
  2656. };
  2657. var baseBehaviour = 'alloy.base.behaviour';
  2658. var toInfo = function (spec) {
  2659. var _a;
  2660. return asRaw('custom.definition', objOf([
  2661. field('dom', 'dom', strict(), objOf([
  2662. strict$1('tag'),
  2663. defaulted$1('styles', {}),
  2664. defaulted$1('classes', []),
  2665. defaulted$1('attributes', {}),
  2666. option('value'),
  2667. option('innerHtml')
  2668. ])),
  2669. strict$1('components'),
  2670. strict$1('uid'),
  2671. defaulted$1('events', {}),
  2672. defaulted$1('apis', {}),
  2673. field('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute()] = [
  2674. 'disabling',
  2675. baseBehaviour,
  2676. 'toggling',
  2677. 'typeaheadevents'
  2678. ], _a[focus()] = [
  2679. baseBehaviour,
  2680. 'focusing',
  2681. 'keying'
  2682. ], _a[systemInit()] = [
  2683. baseBehaviour,
  2684. 'disabling',
  2685. 'toggling',
  2686. 'representing'
  2687. ], _a[input()] = [
  2688. baseBehaviour,
  2689. 'representing',
  2690. 'streaming',
  2691. 'invalidating'
  2692. ], _a[detachedFromDom()] = [
  2693. baseBehaviour,
  2694. 'representing',
  2695. 'item-events',
  2696. 'tooltipping'
  2697. ], _a[mousedown()] = [
  2698. 'focusing',
  2699. baseBehaviour,
  2700. 'item-type-events'
  2701. ], _a[touchstart()] = [
  2702. 'focusing',
  2703. baseBehaviour,
  2704. 'item-type-events'
  2705. ], _a[mouseover()] = [
  2706. 'item-type-events',
  2707. 'tooltipping'
  2708. ], _a[receive()] = [
  2709. 'receiving',
  2710. 'reflecting',
  2711. 'tooltipping'
  2712. ], _a)), anyValue$1()),
  2713. option('domModification')
  2714. ]), spec);
  2715. };
  2716. var toDefinition = function (detail) {
  2717. return __assign(__assign({}, detail.dom), {
  2718. uid: detail.uid,
  2719. domChildren: map(detail.components, function (comp) {
  2720. return comp.element;
  2721. })
  2722. });
  2723. };
  2724. var toModification = function (detail) {
  2725. return detail.domModification.fold(function () {
  2726. return nu$6({});
  2727. }, nu$6);
  2728. };
  2729. var toEvents = function (info) {
  2730. return info.events;
  2731. };
  2732. var read$2 = function (element, attr) {
  2733. var value = get$2(element, attr);
  2734. return value === undefined || value === '' ? [] : value.split(' ');
  2735. };
  2736. var add = function (element, attr, id) {
  2737. var old = read$2(element, attr);
  2738. var nu = old.concat([id]);
  2739. set$1(element, attr, nu.join(' '));
  2740. return true;
  2741. };
  2742. var remove$2 = function (element, attr, id) {
  2743. var nu = filter(read$2(element, attr), function (v) {
  2744. return v !== id;
  2745. });
  2746. if (nu.length > 0) {
  2747. set$1(element, attr, nu.join(' '));
  2748. } else {
  2749. remove$1(element, attr);
  2750. }
  2751. return false;
  2752. };
  2753. var supports = function (element) {
  2754. return element.dom.classList !== undefined;
  2755. };
  2756. var get$3 = function (element) {
  2757. return read$2(element, 'class');
  2758. };
  2759. var add$1 = function (element, clazz) {
  2760. return add(element, 'class', clazz);
  2761. };
  2762. var remove$3 = function (element, clazz) {
  2763. return remove$2(element, 'class', clazz);
  2764. };
  2765. var add$2 = function (element, clazz) {
  2766. if (supports(element)) {
  2767. element.dom.classList.add(clazz);
  2768. } else {
  2769. add$1(element, clazz);
  2770. }
  2771. };
  2772. var cleanClass = function (element) {
  2773. var classList = supports(element) ? element.dom.classList : get$3(element);
  2774. if (classList.length === 0) {
  2775. remove$1(element, 'class');
  2776. }
  2777. };
  2778. var remove$4 = function (element, clazz) {
  2779. if (supports(element)) {
  2780. var classList = element.dom.classList;
  2781. classList.remove(clazz);
  2782. } else {
  2783. remove$3(element, clazz);
  2784. }
  2785. cleanClass(element);
  2786. };
  2787. var has$2 = function (element, clazz) {
  2788. return supports(element) && element.dom.classList.contains(clazz);
  2789. };
  2790. var add$3 = function (element, classes) {
  2791. each(classes, function (x) {
  2792. add$2(element, x);
  2793. });
  2794. };
  2795. var remove$5 = function (element, classes) {
  2796. each(classes, function (x) {
  2797. remove$4(element, x);
  2798. });
  2799. };
  2800. var isSupported = function (dom) {
  2801. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2802. };
  2803. var isShadowRoot = function (dos) {
  2804. return isDocumentFragment(dos);
  2805. };
  2806. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  2807. var isSupported$1 = constant(supported);
  2808. var getRootNode = supported ? function (e) {
  2809. return SugarElement.fromDom(e.dom.getRootNode());
  2810. } : documentOrOwner;
  2811. var getContentContainer = function (dos) {
  2812. return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  2813. };
  2814. var getShadowRoot = function (e) {
  2815. var r = getRootNode(e);
  2816. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  2817. };
  2818. var getShadowHost = function (e) {
  2819. return SugarElement.fromDom(e.dom.host);
  2820. };
  2821. var getOriginalEventTarget = function (event) {
  2822. if (isSupported$1() && isNonNullable(event.target)) {
  2823. var el = SugarElement.fromDom(event.target);
  2824. if (isElement(el) && isOpenShadowHost(el)) {
  2825. if (event.composed && event.composedPath) {
  2826. var composedPath = event.composedPath();
  2827. if (composedPath) {
  2828. return head(composedPath);
  2829. }
  2830. }
  2831. }
  2832. }
  2833. return Optional.from(event.target);
  2834. };
  2835. var isOpenShadowHost = function (element) {
  2836. return isNonNullable(element.dom.shadowRoot);
  2837. };
  2838. var inBody = function (element) {
  2839. var dom = isText(element) ? element.dom.parentNode : element.dom;
  2840. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  2841. return false;
  2842. }
  2843. var doc = dom.ownerDocument;
  2844. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  2845. return doc.body.contains(dom);
  2846. }, compose1(inBody, getShadowHost));
  2847. };
  2848. var body = function () {
  2849. return getBody(SugarElement.fromDom(document));
  2850. };
  2851. var getBody = function (doc) {
  2852. var b = doc.dom.body;
  2853. if (b === null || b === undefined) {
  2854. throw new Error('Body is not available yet');
  2855. }
  2856. return SugarElement.fromDom(b);
  2857. };
  2858. var internalSet = function (dom, property, value) {
  2859. if (!isString(value)) {
  2860. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2861. throw new Error('CSS value must be a string: ' + value);
  2862. }
  2863. if (isSupported(dom)) {
  2864. dom.style.setProperty(property, value);
  2865. }
  2866. };
  2867. var internalRemove = function (dom, property) {
  2868. if (isSupported(dom)) {
  2869. dom.style.removeProperty(property);
  2870. }
  2871. };
  2872. var set$2 = function (element, property, value) {
  2873. var dom = element.dom;
  2874. internalSet(dom, property, value);
  2875. };
  2876. var setAll$1 = function (element, css) {
  2877. var dom = element.dom;
  2878. each$1(css, function (v, k) {
  2879. internalSet(dom, k, v);
  2880. });
  2881. };
  2882. var setOptions = function (element, css) {
  2883. var dom = element.dom;
  2884. each$1(css, function (v, k) {
  2885. v.fold(function () {
  2886. internalRemove(dom, k);
  2887. }, function (value) {
  2888. internalSet(dom, k, value);
  2889. });
  2890. });
  2891. };
  2892. var get$4 = function (element, property) {
  2893. var dom = element.dom;
  2894. var styles = window.getComputedStyle(dom);
  2895. var r = styles.getPropertyValue(property);
  2896. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2897. };
  2898. var getUnsafeProperty = function (dom, property) {
  2899. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2900. };
  2901. var getRaw = function (element, property) {
  2902. var dom = element.dom;
  2903. var raw = getUnsafeProperty(dom, property);
  2904. return Optional.from(raw).filter(function (r) {
  2905. return r.length > 0;
  2906. });
  2907. };
  2908. var getAllRaw = function (element) {
  2909. var css = {};
  2910. var dom = element.dom;
  2911. if (isSupported(dom)) {
  2912. for (var i = 0; i < dom.style.length; i++) {
  2913. var ruleName = dom.style.item(i);
  2914. css[ruleName] = dom.style[ruleName];
  2915. }
  2916. }
  2917. return css;
  2918. };
  2919. var isValidValue = function (tag, property, value) {
  2920. var element = SugarElement.fromTag(tag);
  2921. set$2(element, property, value);
  2922. var style = getRaw(element, property);
  2923. return style.isSome();
  2924. };
  2925. var remove$6 = function (element, property) {
  2926. var dom = element.dom;
  2927. internalRemove(dom, property);
  2928. if (getOpt(element, 'style').map(trim).is('')) {
  2929. remove$1(element, 'style');
  2930. }
  2931. };
  2932. var reflow = function (e) {
  2933. return e.dom.offsetWidth;
  2934. };
  2935. var get$5 = function (element) {
  2936. return element.dom.value;
  2937. };
  2938. var set$3 = function (element, value) {
  2939. if (value === undefined) {
  2940. throw new Error('Value.set was undefined');
  2941. }
  2942. element.dom.value = value;
  2943. };
  2944. var renderToDom = function (definition) {
  2945. var subject = SugarElement.fromTag(definition.tag);
  2946. setAll(subject, definition.attributes);
  2947. add$3(subject, definition.classes);
  2948. setAll$1(subject, definition.styles);
  2949. definition.innerHtml.each(function (html) {
  2950. return set(subject, html);
  2951. });
  2952. var children = definition.domChildren;
  2953. append$1(subject, children);
  2954. definition.value.each(function (value) {
  2955. set$3(subject, value);
  2956. });
  2957. if (!definition.uid) {
  2958. debugger;
  2959. }
  2960. writeOnly(subject, definition.uid);
  2961. return subject;
  2962. };
  2963. var getBehaviours$1 = function (spec) {
  2964. var behaviours = get(spec, 'behaviours').getOr({});
  2965. var keys$1 = filter(keys(behaviours), function (k) {
  2966. return behaviours[k] !== undefined;
  2967. });
  2968. return map(keys$1, function (k) {
  2969. return behaviours[k].me;
  2970. });
  2971. };
  2972. var generateFrom$1 = function (spec, all) {
  2973. return generateFrom(spec, all);
  2974. };
  2975. var generate$3 = function (spec) {
  2976. var all = getBehaviours$1(spec);
  2977. return generateFrom$1(spec, all);
  2978. };
  2979. var getDomDefinition = function (info, bList, bData) {
  2980. var definition = toDefinition(info);
  2981. var infoModification = toModification(info);
  2982. var baseModification = { 'alloy.base.modification': infoModification };
  2983. var modification = bList.length > 0 ? combine(bData, baseModification, bList, definition) : infoModification;
  2984. return merge$1(definition, modification);
  2985. };
  2986. var getEvents = function (info, bList, bData) {
  2987. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  2988. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  2989. };
  2990. var build = function (spec) {
  2991. var getMe = function () {
  2992. return me;
  2993. };
  2994. var systemApi = Cell(singleton);
  2995. var info = getOrDie(toInfo(spec));
  2996. var bBlob = generate$3(spec);
  2997. var bList = getBehaviours(bBlob);
  2998. var bData = getData(bBlob);
  2999. var modDefinition = getDomDefinition(info, bList, bData);
  3000. var item = renderToDom(modDefinition);
  3001. var events = getEvents(info, bList, bData);
  3002. var subcomponents = Cell(info.components);
  3003. var connect = function (newApi) {
  3004. systemApi.set(newApi);
  3005. };
  3006. var disconnect = function () {
  3007. systemApi.set(NoContextApi(getMe));
  3008. };
  3009. var syncComponents = function () {
  3010. var children$1 = children(item);
  3011. var subs = bind(children$1, function (child) {
  3012. return systemApi.get().getByDom(child).fold(function () {
  3013. return [];
  3014. }, function (c) {
  3015. return [c];
  3016. });
  3017. });
  3018. subcomponents.set(subs);
  3019. };
  3020. var config = function (behaviour) {
  3021. var b = bData;
  3022. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3023. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3024. };
  3025. return f();
  3026. };
  3027. var hasConfigured = function (behaviour) {
  3028. return isFunction(bData[behaviour.name()]);
  3029. };
  3030. var getApis = function () {
  3031. return info.apis;
  3032. };
  3033. var readState = function (behaviourName) {
  3034. return bData[behaviourName]().map(function (b) {
  3035. return b.state.readState();
  3036. }).getOr('not enabled');
  3037. };
  3038. var me = {
  3039. getSystem: systemApi.get,
  3040. config: config,
  3041. hasConfigured: hasConfigured,
  3042. spec: spec,
  3043. readState: readState,
  3044. getApis: getApis,
  3045. connect: connect,
  3046. disconnect: disconnect,
  3047. element: item,
  3048. syncComponents: syncComponents,
  3049. components: subcomponents.get,
  3050. events: events
  3051. };
  3052. return me;
  3053. };
  3054. var buildSubcomponents = function (spec) {
  3055. var components = get(spec, 'components').getOr([]);
  3056. return map(components, build$1);
  3057. };
  3058. var buildFromSpec = function (userSpec) {
  3059. var _a = make(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3060. var components = buildSubcomponents(spec);
  3061. var completeSpec = __assign(__assign({}, spec), {
  3062. events: __assign(__assign({}, DefaultEvents), specEvents),
  3063. components: components
  3064. });
  3065. return Result.value(build(completeSpec));
  3066. };
  3067. var text = function (textContent) {
  3068. var element = SugarElement.fromText(textContent);
  3069. return external({ element: element });
  3070. };
  3071. var external = function (spec) {
  3072. var extSpec = asRawOrDie('external.component', objOfOnly([
  3073. strict$1('element'),
  3074. option('uid')
  3075. ]), spec);
  3076. var systemApi = Cell(NoContextApi());
  3077. var connect = function (newApi) {
  3078. systemApi.set(newApi);
  3079. };
  3080. var disconnect = function () {
  3081. systemApi.set(NoContextApi(function () {
  3082. return me;
  3083. }));
  3084. };
  3085. extSpec.uid.each(function (uid) {
  3086. writeOnly(extSpec.element, uid);
  3087. });
  3088. var me = {
  3089. getSystem: systemApi.get,
  3090. config: Optional.none,
  3091. hasConfigured: never,
  3092. connect: connect,
  3093. disconnect: disconnect,
  3094. getApis: function () {
  3095. return {};
  3096. },
  3097. element: extSpec.element,
  3098. spec: spec,
  3099. readState: constant('No state'),
  3100. syncComponents: noop,
  3101. components: constant([]),
  3102. events: {}
  3103. };
  3104. return premade(me);
  3105. };
  3106. var uids = generate$2;
  3107. var build$1 = function (spec) {
  3108. return getPremade(spec).fold(function () {
  3109. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  3110. return buildFromSpec(userSpecWithUid).getOrDie();
  3111. }, function (prebuilt) {
  3112. return prebuilt;
  3113. });
  3114. };
  3115. var premade$1 = premade;
  3116. function Dimension (name, getOffset) {
  3117. var set = function (element, h) {
  3118. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3119. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3120. }
  3121. var dom = element.dom;
  3122. if (isSupported(dom)) {
  3123. dom.style[name] = h + 'px';
  3124. }
  3125. };
  3126. var get = function (element) {
  3127. var r = getOffset(element);
  3128. if (r <= 0 || r === null) {
  3129. var css = get$4(element, name);
  3130. return parseFloat(css) || 0;
  3131. }
  3132. return r;
  3133. };
  3134. var getOuter = get;
  3135. var aggregate = function (element, properties) {
  3136. return foldl(properties, function (acc, property) {
  3137. var val = get$4(element, property);
  3138. var value = val === undefined ? 0 : parseInt(val, 10);
  3139. return isNaN(value) ? acc : acc + value;
  3140. }, 0);
  3141. };
  3142. var max = function (element, value, properties) {
  3143. var cumulativeInclusions = aggregate(element, properties);
  3144. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3145. return absoluteMax;
  3146. };
  3147. return {
  3148. set: set,
  3149. get: get,
  3150. getOuter: getOuter,
  3151. aggregate: aggregate,
  3152. max: max
  3153. };
  3154. }
  3155. var api = Dimension('height', function (element) {
  3156. var dom = element.dom;
  3157. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3158. });
  3159. var get$6 = function (element) {
  3160. return api.get(element);
  3161. };
  3162. var getOuter$1 = function (element) {
  3163. return api.getOuter(element);
  3164. };
  3165. var setMax = function (element, value) {
  3166. var inclusions = [
  3167. 'margin-top',
  3168. 'border-top-width',
  3169. 'padding-top',
  3170. 'padding-bottom',
  3171. 'border-bottom-width',
  3172. 'margin-bottom'
  3173. ];
  3174. var absMax = api.max(element, value, inclusions);
  3175. set$2(element, 'max-height', absMax + 'px');
  3176. };
  3177. var r = function (left, top) {
  3178. var translate = function (x, y) {
  3179. return r(left + x, top + y);
  3180. };
  3181. return {
  3182. left: left,
  3183. top: top,
  3184. translate: translate
  3185. };
  3186. };
  3187. var SugarPosition = r;
  3188. var boxPosition = function (dom) {
  3189. var box = dom.getBoundingClientRect();
  3190. return SugarPosition(box.left, box.top);
  3191. };
  3192. var firstDefinedOrZero = function (a, b) {
  3193. if (a !== undefined) {
  3194. return a;
  3195. } else {
  3196. return b !== undefined ? b : 0;
  3197. }
  3198. };
  3199. var absolute = function (element) {
  3200. var doc = element.dom.ownerDocument;
  3201. var body = doc.body;
  3202. var win = doc.defaultView;
  3203. var html = doc.documentElement;
  3204. if (body === element.dom) {
  3205. return SugarPosition(body.offsetLeft, body.offsetTop);
  3206. }
  3207. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  3208. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  3209. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  3210. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  3211. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  3212. };
  3213. var viewport = function (element) {
  3214. var dom = element.dom;
  3215. var doc = dom.ownerDocument;
  3216. var body = doc.body;
  3217. if (body === dom) {
  3218. return SugarPosition(body.offsetLeft, body.offsetTop);
  3219. }
  3220. if (!inBody(element)) {
  3221. return SugarPosition(0, 0);
  3222. }
  3223. return boxPosition(dom);
  3224. };
  3225. var api$1 = Dimension('width', function (element) {
  3226. return element.dom.offsetWidth;
  3227. });
  3228. var set$4 = function (element, h) {
  3229. return api$1.set(element, h);
  3230. };
  3231. var get$7 = function (element) {
  3232. return api$1.get(element);
  3233. };
  3234. var getOuter$2 = function (element) {
  3235. return api$1.getOuter(element);
  3236. };
  3237. var setMax$1 = function (element, value) {
  3238. var inclusions = [
  3239. 'margin-left',
  3240. 'border-left-width',
  3241. 'padding-left',
  3242. 'padding-right',
  3243. 'border-right-width',
  3244. 'margin-right'
  3245. ];
  3246. var absMax = api$1.max(element, value, inclusions);
  3247. set$2(element, 'max-width', absMax + 'px');
  3248. };
  3249. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  3250. return {
  3251. target: target,
  3252. x: x,
  3253. y: y,
  3254. stop: stop,
  3255. prevent: prevent,
  3256. kill: kill,
  3257. raw: raw
  3258. };
  3259. };
  3260. var fromRawEvent = function (rawEvent) {
  3261. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  3262. var stop = function () {
  3263. return rawEvent.stopPropagation();
  3264. };
  3265. var prevent = function () {
  3266. return rawEvent.preventDefault();
  3267. };
  3268. var kill = compose(prevent, stop);
  3269. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  3270. };
  3271. var handle = function (filter, handler) {
  3272. return function (rawEvent) {
  3273. if (filter(rawEvent)) {
  3274. handler(fromRawEvent(rawEvent));
  3275. }
  3276. };
  3277. };
  3278. var binder = function (element, event, filter, handler, useCapture) {
  3279. var wrapped = handle(filter, handler);
  3280. element.dom.addEventListener(event, wrapped, useCapture);
  3281. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  3282. };
  3283. var bind$2 = function (element, event, filter, handler) {
  3284. return binder(element, event, filter, handler, false);
  3285. };
  3286. var capture = function (element, event, filter, handler) {
  3287. return binder(element, event, filter, handler, true);
  3288. };
  3289. var unbind = function (element, event, handler, useCapture) {
  3290. element.dom.removeEventListener(event, handler, useCapture);
  3291. };
  3292. var get$8 = function (_DOC) {
  3293. var doc = _DOC !== undefined ? _DOC.dom : document;
  3294. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  3295. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  3296. return SugarPosition(x, y);
  3297. };
  3298. var to = function (x, y, _DOC) {
  3299. var doc = _DOC !== undefined ? _DOC.dom : document;
  3300. var win = doc.defaultView;
  3301. if (win) {
  3302. win.scrollTo(x, y);
  3303. }
  3304. };
  3305. var get$9 = function (_win) {
  3306. var win = _win === undefined ? window : _win;
  3307. return Optional.from(win['visualViewport']);
  3308. };
  3309. var bounds = function (x, y, width, height) {
  3310. return {
  3311. x: x,
  3312. y: y,
  3313. width: width,
  3314. height: height,
  3315. right: x + width,
  3316. bottom: y + height
  3317. };
  3318. };
  3319. var getBounds = function (_win) {
  3320. var win = _win === undefined ? window : _win;
  3321. var doc = win.document;
  3322. var scroll = get$8(SugarElement.fromDom(doc));
  3323. return get$9(win).fold(function () {
  3324. var html = win.document.documentElement;
  3325. var width = html.clientWidth;
  3326. var height = html.clientHeight;
  3327. return bounds(scroll.left, scroll.top, width, height);
  3328. }, function (visualViewport) {
  3329. return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  3330. });
  3331. };
  3332. var walkUp = function (navigation, doc) {
  3333. var frame = navigation.view(doc);
  3334. return frame.fold(constant([]), function (f) {
  3335. var parent = navigation.owner(f);
  3336. var rest = walkUp(navigation, parent);
  3337. return [f].concat(rest);
  3338. });
  3339. };
  3340. var pathTo = function (element, navigation) {
  3341. var d = navigation.owner(element);
  3342. var paths = walkUp(navigation, d);
  3343. return Optional.some(paths);
  3344. };
  3345. var view = function (doc) {
  3346. var _a;
  3347. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  3348. return element.map(SugarElement.fromDom);
  3349. };
  3350. var owner$1 = function (element) {
  3351. return owner(element);
  3352. };
  3353. var Navigation = /*#__PURE__*/Object.freeze({
  3354. __proto__: null,
  3355. view: view,
  3356. owner: owner$1
  3357. });
  3358. var find$3 = function (element) {
  3359. var doc = SugarElement.fromDom(document);
  3360. var scroll = get$8(doc);
  3361. var path = pathTo(element, Navigation);
  3362. return path.fold(curry(absolute, element), function (frames) {
  3363. var offset = viewport(element);
  3364. var r = foldr(frames, function (b, a) {
  3365. var loc = viewport(a);
  3366. return {
  3367. left: b.left + loc.left,
  3368. top: b.top + loc.top
  3369. };
  3370. }, {
  3371. left: 0,
  3372. top: 0
  3373. });
  3374. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  3375. });
  3376. };
  3377. var pointed = function (point, width, height) {
  3378. return {
  3379. point: point,
  3380. width: width,
  3381. height: height
  3382. };
  3383. };
  3384. var rect = function (x, y, width, height) {
  3385. return {
  3386. x: x,
  3387. y: y,
  3388. width: width,
  3389. height: height
  3390. };
  3391. };
  3392. var bounds$1 = function (x, y, width, height) {
  3393. return {
  3394. x: x,
  3395. y: y,
  3396. width: width,
  3397. height: height,
  3398. right: x + width,
  3399. bottom: y + height
  3400. };
  3401. };
  3402. var box = function (element) {
  3403. var xy = absolute(element);
  3404. var w = getOuter$2(element);
  3405. var h = getOuter$1(element);
  3406. return bounds$1(xy.left, xy.top, w, h);
  3407. };
  3408. var absolute$1 = function (element) {
  3409. var position = find$3(element);
  3410. var width = getOuter$2(element);
  3411. var height = getOuter$1(element);
  3412. return bounds$1(position.left, position.top, width, height);
  3413. };
  3414. var win = function () {
  3415. return getBounds(window);
  3416. };
  3417. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3418. return is(scope, a) ? Optional.some(scope) : isFunction(isRoot) && isRoot(scope) ? Optional.none() : ancestor(scope, a, isRoot);
  3419. }
  3420. var ancestor$1 = function (scope, predicate, isRoot) {
  3421. var element = scope.dom;
  3422. var stop = isFunction(isRoot) ? isRoot : never;
  3423. while (element.parentNode) {
  3424. element = element.parentNode;
  3425. var el = SugarElement.fromDom(element);
  3426. if (predicate(el)) {
  3427. return Optional.some(el);
  3428. } else if (stop(el)) {
  3429. break;
  3430. }
  3431. }
  3432. return Optional.none();
  3433. };
  3434. var closest$1 = function (scope, predicate, isRoot) {
  3435. var is = function (s, test) {
  3436. return test(s);
  3437. };
  3438. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3439. };
  3440. var descendant = function (scope, predicate) {
  3441. var descend = function (node) {
  3442. for (var i = 0; i < node.childNodes.length; i++) {
  3443. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3444. if (predicate(child_1)) {
  3445. return Optional.some(child_1);
  3446. }
  3447. var res = descend(node.childNodes[i]);
  3448. if (res.isSome()) {
  3449. return res;
  3450. }
  3451. }
  3452. return Optional.none();
  3453. };
  3454. return descend(scope.dom);
  3455. };
  3456. var closest$2 = function (scope, predicate, isRoot) {
  3457. return closest$1(scope, predicate, isRoot).isSome();
  3458. };
  3459. var ancestor$2 = function (scope, selector, isRoot) {
  3460. return ancestor$1(scope, function (e) {
  3461. return is(e, selector);
  3462. }, isRoot);
  3463. };
  3464. var descendant$1 = function (scope, selector) {
  3465. return one(selector, scope);
  3466. };
  3467. var closest$3 = function (scope, selector, isRoot) {
  3468. var is$1 = function (element, selector) {
  3469. return is(element, selector);
  3470. };
  3471. return ClosestOrAncestor(is$1, ancestor$2, scope, selector, isRoot);
  3472. };
  3473. var find$4 = function (queryElem) {
  3474. var dependent = closest$1(queryElem, function (elem) {
  3475. if (!isElement(elem)) {
  3476. return false;
  3477. }
  3478. var id = get$2(elem, 'id');
  3479. return id !== undefined && id.indexOf('aria-owns') > -1;
  3480. });
  3481. return dependent.bind(function (dep) {
  3482. var id = get$2(dep, 'id');
  3483. var dos = getRootNode(dep);
  3484. return descendant$1(dos, '[aria-owns="' + id + '"]');
  3485. });
  3486. };
  3487. var manager = function () {
  3488. var ariaId = generate$1('aria-owns');
  3489. var link = function (elem) {
  3490. set$1(elem, 'aria-owns', ariaId);
  3491. };
  3492. var unlink = function (elem) {
  3493. remove$1(elem, 'aria-owns');
  3494. };
  3495. return {
  3496. id: ariaId,
  3497. link: link,
  3498. unlink: unlink
  3499. };
  3500. };
  3501. var isAriaPartOf = function (component, queryElem) {
  3502. return find$4(queryElem).exists(function (owner) {
  3503. return isPartOf(component, owner);
  3504. });
  3505. };
  3506. var isPartOf = function (component, queryElem) {
  3507. return closest$2(queryElem, function (el) {
  3508. return eq$1(el, component.element);
  3509. }, never) || isAriaPartOf(component, queryElem);
  3510. };
  3511. var unknown$3 = 'unknown';
  3512. var EventConfiguration;
  3513. (function (EventConfiguration) {
  3514. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3515. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3516. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3517. }(EventConfiguration || (EventConfiguration = {})));
  3518. var eventConfig = Cell({});
  3519. var makeEventLogger = function (eventName, initialTarget) {
  3520. var sequence = [];
  3521. var startTime = new Date().getTime();
  3522. return {
  3523. logEventCut: function (_name, target, purpose) {
  3524. sequence.push({
  3525. outcome: 'cut',
  3526. target: target,
  3527. purpose: purpose
  3528. });
  3529. },
  3530. logEventStopped: function (_name, target, purpose) {
  3531. sequence.push({
  3532. outcome: 'stopped',
  3533. target: target,
  3534. purpose: purpose
  3535. });
  3536. },
  3537. logNoParent: function (_name, target, purpose) {
  3538. sequence.push({
  3539. outcome: 'no-parent',
  3540. target: target,
  3541. purpose: purpose
  3542. });
  3543. },
  3544. logEventNoHandlers: function (_name, target) {
  3545. sequence.push({
  3546. outcome: 'no-handlers-left',
  3547. target: target
  3548. });
  3549. },
  3550. logEventResponse: function (_name, target, purpose) {
  3551. sequence.push({
  3552. outcome: 'response',
  3553. purpose: purpose,
  3554. target: target
  3555. });
  3556. },
  3557. write: function () {
  3558. var finishTime = new Date().getTime();
  3559. if (contains([
  3560. 'mousemove',
  3561. 'mouseover',
  3562. 'mouseout',
  3563. systemInit()
  3564. ], eventName)) {
  3565. return;
  3566. }
  3567. console.log(eventName, {
  3568. event: eventName,
  3569. time: finishTime - startTime,
  3570. target: initialTarget.dom,
  3571. sequence: map(sequence, function (s) {
  3572. if (!contains([
  3573. 'cut',
  3574. 'stopped',
  3575. 'response'
  3576. ], s.outcome)) {
  3577. return s.outcome;
  3578. } else {
  3579. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3580. }
  3581. })
  3582. });
  3583. }
  3584. };
  3585. };
  3586. var processEvent = function (eventName, initialTarget, f) {
  3587. var status = get(eventConfig.get(), eventName).orThunk(function () {
  3588. var patterns = keys(eventConfig.get());
  3589. return findMap(patterns, function (p) {
  3590. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  3591. });
  3592. }).getOr(EventConfiguration.NORMAL);
  3593. switch (status) {
  3594. case EventConfiguration.NORMAL:
  3595. return f(noLogger());
  3596. case EventConfiguration.LOGGING: {
  3597. var logger = makeEventLogger(eventName, initialTarget);
  3598. var output = f(logger);
  3599. logger.write();
  3600. return output;
  3601. }
  3602. case EventConfiguration.STOP:
  3603. return true;
  3604. }
  3605. };
  3606. var path = [
  3607. 'alloy/data/Fields',
  3608. 'alloy/debugging/Debugging'
  3609. ];
  3610. var getTrace = function () {
  3611. var err = new Error();
  3612. if (err.stack !== undefined) {
  3613. var lines = err.stack.split('\n');
  3614. return find(lines, function (line) {
  3615. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3616. return line.indexOf(p) > -1;
  3617. });
  3618. }).getOr(unknown$3);
  3619. } else {
  3620. return unknown$3;
  3621. }
  3622. };
  3623. var ignoreEvent = {
  3624. logEventCut: noop,
  3625. logEventStopped: noop,
  3626. logNoParent: noop,
  3627. logEventNoHandlers: noop,
  3628. logEventResponse: noop,
  3629. write: noop
  3630. };
  3631. var monitorEvent = function (eventName, initialTarget, f) {
  3632. return processEvent(eventName, initialTarget, f);
  3633. };
  3634. var noLogger = constant(ignoreEvent);
  3635. var menuFields = constant([
  3636. strict$1('menu'),
  3637. strict$1('selectedMenu')
  3638. ]);
  3639. var itemFields = constant([
  3640. strict$1('item'),
  3641. strict$1('selectedItem')
  3642. ]);
  3643. var schema = constant(objOf(itemFields().concat(menuFields())));
  3644. var itemSchema = constant(objOf(itemFields()));
  3645. var _initSize = strictObjOf('initSize', [
  3646. strict$1('numColumns'),
  3647. strict$1('numRows')
  3648. ]);
  3649. var itemMarkers = function () {
  3650. return strictOf('markers', itemSchema());
  3651. };
  3652. var tieredMenuMarkers = function () {
  3653. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3654. };
  3655. var markers = function (required) {
  3656. return strictObjOf('markers', map(required, strict$1));
  3657. };
  3658. var onPresenceHandler = function (label, fieldName, presence) {
  3659. var trace = getTrace();
  3660. return field(fieldName, fieldName, presence, valueOf(function (f) {
  3661. return Result.value(function () {
  3662. var args = [];
  3663. for (var _i = 0; _i < arguments.length; _i++) {
  3664. args[_i] = arguments[_i];
  3665. }
  3666. return f.apply(undefined, args);
  3667. });
  3668. }));
  3669. };
  3670. var onHandler = function (fieldName) {
  3671. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  3672. };
  3673. var onKeyboardHandler = function (fieldName) {
  3674. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Optional.none));
  3675. };
  3676. var onStrictHandler = function (fieldName) {
  3677. return onPresenceHandler('onHandler', fieldName, strict());
  3678. };
  3679. var onStrictKeyboardHandler = function (fieldName) {
  3680. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  3681. };
  3682. var output = function (name, value) {
  3683. return state$1(name, constant(value));
  3684. };
  3685. var snapshot = function (name) {
  3686. return state$1(name, identity);
  3687. };
  3688. var initSize = constant(_initSize);
  3689. var nu$7 = function (x, y, bubble, direction, boundsRestriction, label) {
  3690. return {
  3691. x: x,
  3692. y: y,
  3693. bubble: bubble,
  3694. direction: direction,
  3695. boundsRestriction: boundsRestriction,
  3696. label: label
  3697. };
  3698. };
  3699. var adt$2 = Adt.generate([
  3700. { southeast: [] },
  3701. { southwest: [] },
  3702. { northeast: [] },
  3703. { northwest: [] },
  3704. { south: [] },
  3705. { north: [] },
  3706. { east: [] },
  3707. { west: [] }
  3708. ]);
  3709. var cata = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3710. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3711. };
  3712. var cataVertical = function (subject, south, middle, north) {
  3713. return subject.fold(south, south, north, north, south, north, middle, middle);
  3714. };
  3715. var cataHorizontal = function (subject, east, middle, west) {
  3716. return subject.fold(east, west, east, west, middle, middle, east, west);
  3717. };
  3718. var southeast = adt$2.southeast;
  3719. var southwest = adt$2.southwest;
  3720. var northeast = adt$2.northeast;
  3721. var northwest = adt$2.northwest;
  3722. var south = adt$2.south;
  3723. var north = adt$2.north;
  3724. var east = adt$2.east;
  3725. var west = adt$2.west;
  3726. var getRestriction = function (anchor, restriction) {
  3727. switch (restriction) {
  3728. case 1:
  3729. return anchor.x;
  3730. case 0:
  3731. return anchor.x + anchor.width;
  3732. case 2:
  3733. return anchor.y;
  3734. case 3:
  3735. return anchor.y + anchor.height;
  3736. }
  3737. };
  3738. var boundsRestriction = function (anchor, restrictions) {
  3739. return mapToObject([
  3740. 'left',
  3741. 'right',
  3742. 'top',
  3743. 'bottom'
  3744. ], function (dir) {
  3745. return get(restrictions, dir).map(function (restriction) {
  3746. return getRestriction(anchor, restriction);
  3747. });
  3748. });
  3749. };
  3750. var adjustBounds = function (bounds, boundsRestrictions, bubbleOffsets) {
  3751. var applyRestriction = function (dir, current) {
  3752. var bubbleOffset = dir === 'top' || dir === 'bottom' ? bubbleOffsets.top : bubbleOffsets.left;
  3753. return get(boundsRestrictions, dir).bind(identity).bind(function (restriction) {
  3754. if (dir === 'left' || dir === 'top') {
  3755. return restriction >= current ? Optional.some(restriction) : Optional.none();
  3756. } else {
  3757. return restriction <= current ? Optional.some(restriction) : Optional.none();
  3758. }
  3759. }).map(function (restriction) {
  3760. return restriction + bubbleOffset;
  3761. }).getOr(current);
  3762. };
  3763. var adjustedLeft = applyRestriction('left', bounds.x);
  3764. var adjustedTop = applyRestriction('top', bounds.y);
  3765. var adjustedRight = applyRestriction('right', bounds.right);
  3766. var adjustedBottom = applyRestriction('bottom', bounds.bottom);
  3767. return bounds$1(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  3768. };
  3769. var eastX = function (anchor) {
  3770. return anchor.x;
  3771. };
  3772. var middleX = function (anchor, element) {
  3773. return anchor.x + anchor.width / 2 - element.width / 2;
  3774. };
  3775. var westX = function (anchor, element) {
  3776. return anchor.x + anchor.width - element.width;
  3777. };
  3778. var northY = function (anchor, element) {
  3779. return anchor.y - element.height;
  3780. };
  3781. var southY = function (anchor) {
  3782. return anchor.y + anchor.height;
  3783. };
  3784. var centreY = function (anchor, element) {
  3785. return anchor.y + anchor.height / 2 - element.height / 2;
  3786. };
  3787. var eastEdgeX = function (anchor) {
  3788. return anchor.x + anchor.width;
  3789. };
  3790. var westEdgeX = function (anchor, element) {
  3791. return anchor.x - element.width;
  3792. };
  3793. var southeast$1 = function (anchor, element, bubbles) {
  3794. return nu$7(eastX(anchor), southY(anchor), bubbles.southeast(), southeast(), boundsRestriction(anchor, {
  3795. left: 1,
  3796. top: 3
  3797. }), 'layout-se');
  3798. };
  3799. var southwest$1 = function (anchor, element, bubbles) {
  3800. return nu$7(westX(anchor, element), southY(anchor), bubbles.southwest(), southwest(), boundsRestriction(anchor, {
  3801. right: 0,
  3802. top: 3
  3803. }), 'layout-sw');
  3804. };
  3805. var northeast$1 = function (anchor, element, bubbles) {
  3806. return nu$7(eastX(anchor), northY(anchor, element), bubbles.northeast(), northeast(), boundsRestriction(anchor, {
  3807. left: 1,
  3808. bottom: 2
  3809. }), 'layout-ne');
  3810. };
  3811. var northwest$1 = function (anchor, element, bubbles) {
  3812. return nu$7(westX(anchor, element), northY(anchor, element), bubbles.northwest(), northwest(), boundsRestriction(anchor, {
  3813. right: 0,
  3814. bottom: 2
  3815. }), 'layout-nw');
  3816. };
  3817. var north$1 = function (anchor, element, bubbles) {
  3818. return nu$7(middleX(anchor, element), northY(anchor, element), bubbles.north(), north(), boundsRestriction(anchor, { bottom: 2 }), 'layout-n');
  3819. };
  3820. var south$1 = function (anchor, element, bubbles) {
  3821. return nu$7(middleX(anchor, element), southY(anchor), bubbles.south(), south(), boundsRestriction(anchor, { top: 3 }), 'layout-s');
  3822. };
  3823. var east$1 = function (anchor, element, bubbles) {
  3824. return nu$7(eastEdgeX(anchor), centreY(anchor, element), bubbles.east(), east(), boundsRestriction(anchor, { left: 0 }), 'layout-e');
  3825. };
  3826. var west$1 = function (anchor, element, bubbles) {
  3827. return nu$7(westEdgeX(anchor, element), centreY(anchor, element), bubbles.west(), west(), boundsRestriction(anchor, { right: 1 }), 'layout-w');
  3828. };
  3829. var all$2 = function () {
  3830. return [
  3831. southeast$1,
  3832. southwest$1,
  3833. northeast$1,
  3834. northwest$1,
  3835. south$1,
  3836. north$1,
  3837. east$1,
  3838. west$1
  3839. ];
  3840. };
  3841. var allRtl = function () {
  3842. return [
  3843. southwest$1,
  3844. southeast$1,
  3845. northwest$1,
  3846. northeast$1,
  3847. south$1,
  3848. north$1,
  3849. east$1,
  3850. west$1
  3851. ];
  3852. };
  3853. var aboveOrBelow = function () {
  3854. return [
  3855. northeast$1,
  3856. northwest$1,
  3857. southeast$1,
  3858. southwest$1,
  3859. north$1,
  3860. south$1
  3861. ];
  3862. };
  3863. var aboveOrBelowRtl = function () {
  3864. return [
  3865. northwest$1,
  3866. northeast$1,
  3867. southwest$1,
  3868. southeast$1,
  3869. north$1,
  3870. south$1
  3871. ];
  3872. };
  3873. var belowOrAbove = function () {
  3874. return [
  3875. southeast$1,
  3876. southwest$1,
  3877. northeast$1,
  3878. northwest$1,
  3879. south$1,
  3880. north$1
  3881. ];
  3882. };
  3883. var belowOrAboveRtl = function () {
  3884. return [
  3885. southwest$1,
  3886. southeast$1,
  3887. northwest$1,
  3888. northeast$1,
  3889. south$1,
  3890. north$1
  3891. ];
  3892. };
  3893. var chooseChannels = function (channels, message) {
  3894. return message.universal ? channels : filter(channels, function (ch) {
  3895. return contains(message.channels, ch);
  3896. });
  3897. };
  3898. var events$1 = function (receiveConfig) {
  3899. return derive([run(receive(), function (component, message) {
  3900. var channelMap = receiveConfig.channels;
  3901. var channels = keys(channelMap);
  3902. var receivingData = message;
  3903. var targetChannels = chooseChannels(channels, receivingData);
  3904. each(targetChannels, function (ch) {
  3905. var channelInfo = channelMap[ch];
  3906. var channelSchema = channelInfo.schema;
  3907. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  3908. channelInfo.onReceive(component, data);
  3909. });
  3910. })]);
  3911. };
  3912. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3913. __proto__: null,
  3914. events: events$1
  3915. });
  3916. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  3917. onStrictHandler('onReceive'),
  3918. defaulted$1('schema', anyValue$1())
  3919. ])))];
  3920. var executeEvent = function (bConfig, bState, executor) {
  3921. return runOnExecute(function (component) {
  3922. executor(component, bConfig, bState);
  3923. });
  3924. };
  3925. var loadEvent = function (bConfig, bState, f) {
  3926. return runOnInit(function (component, _simulatedEvent) {
  3927. f(component, bConfig, bState);
  3928. });
  3929. };
  3930. var create = function (schema, name, active, apis, extra, state) {
  3931. var configSchema = objOfOnly(schema);
  3932. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  3933. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3934. };
  3935. var createModes = function (modes, name, active, apis, extra, state) {
  3936. var configSchema = modes;
  3937. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  3938. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3939. };
  3940. var wrapApi = function (bName, apiFunction, apiName) {
  3941. var f = function (component) {
  3942. var rest = [];
  3943. for (var _i = 1; _i < arguments.length; _i++) {
  3944. rest[_i - 1] = arguments[_i];
  3945. }
  3946. var args = [component].concat(rest);
  3947. return component.config({ name: constant(bName) }).fold(function () {
  3948. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  3949. }, function (info) {
  3950. var rest = Array.prototype.slice.call(args, 1);
  3951. return apiFunction.apply(undefined, [
  3952. component,
  3953. info.config,
  3954. info.state
  3955. ].concat(rest));
  3956. });
  3957. };
  3958. return markAsBehaviourApi(f, apiName, apiFunction);
  3959. };
  3960. var revokeBehaviour = function (name) {
  3961. return {
  3962. key: name,
  3963. value: undefined
  3964. };
  3965. };
  3966. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  3967. var getConfig = function (info) {
  3968. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  3969. };
  3970. var wrappedApis = map$2(apis, function (apiF, apiName) {
  3971. return wrapApi(name, apiF, apiName);
  3972. });
  3973. var wrappedExtra = map$2(extra, function (extraF, extraName) {
  3974. return markAsExtraApi(extraF, extraName);
  3975. });
  3976. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  3977. revoke: curry(revokeBehaviour, name),
  3978. config: function (spec) {
  3979. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  3980. return {
  3981. key: name,
  3982. value: {
  3983. config: prepared,
  3984. me: me,
  3985. configAsRaw: cached(function () {
  3986. return asRawOrDie(name + '-config', configSchema, spec);
  3987. }),
  3988. initialConfig: spec,
  3989. state: state
  3990. }
  3991. };
  3992. },
  3993. schema: function () {
  3994. return schemaSchema;
  3995. },
  3996. exhibit: function (info, base) {
  3997. return getConfig(info).bind(function (behaviourInfo) {
  3998. return get(active, 'exhibit').map(function (exhibitor) {
  3999. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  4000. });
  4001. }).getOr(nu$6({}));
  4002. },
  4003. name: function () {
  4004. return name;
  4005. },
  4006. handlers: function (info) {
  4007. return getConfig(info).map(function (behaviourInfo) {
  4008. var getEvents = get(active, 'events').getOr(function () {
  4009. return {};
  4010. });
  4011. return getEvents(behaviourInfo.config, behaviourInfo.state);
  4012. }).getOr({});
  4013. }
  4014. });
  4015. return me;
  4016. };
  4017. var derive$1 = function (capabilities) {
  4018. return wrapAll$1(capabilities);
  4019. };
  4020. var simpleSchema = objOfOnly([
  4021. strict$1('fields'),
  4022. strict$1('name'),
  4023. defaulted$1('active', {}),
  4024. defaulted$1('apis', {}),
  4025. defaulted$1('state', NoState),
  4026. defaulted$1('extra', {})
  4027. ]);
  4028. var create$1 = function (data) {
  4029. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  4030. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  4031. };
  4032. var modeSchema = objOfOnly([
  4033. strict$1('branchKey'),
  4034. strict$1('branches'),
  4035. strict$1('name'),
  4036. defaulted$1('active', {}),
  4037. defaulted$1('apis', {}),
  4038. defaulted$1('state', NoState),
  4039. defaulted$1('extra', {})
  4040. ]);
  4041. var createModes$1 = function (data) {
  4042. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  4043. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  4044. };
  4045. var revoke = constant(undefined);
  4046. var Receiving = create$1({
  4047. fields: ReceivingSchema,
  4048. name: 'receiving',
  4049. active: ActiveReceiving
  4050. });
  4051. var exhibit = function (base, posConfig) {
  4052. return nu$6({
  4053. classes: [],
  4054. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  4055. });
  4056. };
  4057. var ActivePosition = /*#__PURE__*/Object.freeze({
  4058. __proto__: null,
  4059. exhibit: exhibit
  4060. });
  4061. var getDocument = function () {
  4062. return SugarElement.fromDom(document);
  4063. };
  4064. var focus$1 = function (element) {
  4065. return element.dom.focus();
  4066. };
  4067. var blur = function (element) {
  4068. return element.dom.blur();
  4069. };
  4070. var hasFocus = function (element) {
  4071. var root = getRootNode(element).dom;
  4072. return element.dom === root.activeElement;
  4073. };
  4074. var active = function (root) {
  4075. if (root === void 0) {
  4076. root = getDocument();
  4077. }
  4078. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  4079. };
  4080. var search = function (element) {
  4081. return active(getRootNode(element)).filter(function (e) {
  4082. return element.dom.contains(e.dom);
  4083. });
  4084. };
  4085. var preserve = function (f, container) {
  4086. var dos = getRootNode(container);
  4087. var refocus = active(dos).bind(function (focused) {
  4088. var hasFocus = function (elem) {
  4089. return eq$1(focused, elem);
  4090. };
  4091. return hasFocus(container) ? Optional.some(container) : descendant(container, hasFocus);
  4092. });
  4093. var result = f(container);
  4094. refocus.each(function (oldFocus) {
  4095. active(dos).filter(function (newFocus) {
  4096. return eq$1(newFocus, oldFocus);
  4097. }).fold(function () {
  4098. focus$1(oldFocus);
  4099. }, noop);
  4100. });
  4101. return result;
  4102. };
  4103. var NuPositionCss = function (position, left, top, right, bottom) {
  4104. return {
  4105. position: position,
  4106. left: left,
  4107. top: top,
  4108. right: right,
  4109. bottom: bottom
  4110. };
  4111. };
  4112. var applyPositionCss = function (element, position) {
  4113. var addPx = function (num) {
  4114. return num + 'px';
  4115. };
  4116. setOptions(element, {
  4117. position: Optional.some(position.position),
  4118. left: position.left.map(addPx),
  4119. top: position.top.map(addPx),
  4120. right: position.right.map(addPx),
  4121. bottom: position.bottom.map(addPx)
  4122. });
  4123. };
  4124. var adt$3 = Adt.generate([
  4125. { none: [] },
  4126. {
  4127. relative: [
  4128. 'x',
  4129. 'y',
  4130. 'width',
  4131. 'height'
  4132. ]
  4133. },
  4134. {
  4135. fixed: [
  4136. 'x',
  4137. 'y',
  4138. 'width',
  4139. 'height'
  4140. ]
  4141. }
  4142. ]);
  4143. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4144. var decisionX = decision.x - x;
  4145. var decisionY = decision.y - y;
  4146. var decisionWidth = decision.width;
  4147. var decisionHeight = decision.height;
  4148. var decisionRight = width - (decisionX + decisionWidth);
  4149. var decisionBottom = height - (decisionY + decisionHeight);
  4150. var left = Optional.some(decisionX);
  4151. var top = Optional.some(decisionY);
  4152. var right = Optional.some(decisionRight);
  4153. var bottom = Optional.some(decisionBottom);
  4154. var none = Optional.none();
  4155. return cata(decision.direction, function () {
  4156. return NuPositionCss(posName, left, top, none, none);
  4157. }, function () {
  4158. return NuPositionCss(posName, none, top, right, none);
  4159. }, function () {
  4160. return NuPositionCss(posName, left, none, none, bottom);
  4161. }, function () {
  4162. return NuPositionCss(posName, none, none, right, bottom);
  4163. }, function () {
  4164. return NuPositionCss(posName, left, top, none, none);
  4165. }, function () {
  4166. return NuPositionCss(posName, left, none, none, bottom);
  4167. }, function () {
  4168. return NuPositionCss(posName, left, top, none, none);
  4169. }, function () {
  4170. return NuPositionCss(posName, none, top, right, none);
  4171. });
  4172. };
  4173. var reposition = function (origin, decision) {
  4174. return origin.fold(function () {
  4175. return NuPositionCss('absolute', Optional.some(decision.x), Optional.some(decision.y), Optional.none(), Optional.none());
  4176. }, function (x, y, width, height) {
  4177. return positionWithDirection('absolute', decision, x, y, width, height);
  4178. }, function (x, y, width, height) {
  4179. return positionWithDirection('fixed', decision, x, y, width, height);
  4180. });
  4181. };
  4182. var toBox = function (origin, element) {
  4183. var rel = curry(find$3, element);
  4184. var position = origin.fold(rel, rel, function () {
  4185. var scroll = get$8();
  4186. return find$3(element).translate(-scroll.left, -scroll.top);
  4187. });
  4188. var width = getOuter$2(element);
  4189. var height = getOuter$1(element);
  4190. return bounds$1(position.left, position.top, width, height);
  4191. };
  4192. var viewport$1 = function (origin, getBounds) {
  4193. return getBounds.fold(function () {
  4194. return origin.fold(win, win, bounds$1);
  4195. }, function (b) {
  4196. return origin.fold(b, b, function () {
  4197. var bounds = b();
  4198. var pos = translate(origin, bounds.x, bounds.y);
  4199. return bounds$1(pos.left, pos.top, bounds.width, bounds.height);
  4200. });
  4201. });
  4202. };
  4203. var translate = function (origin, x, y) {
  4204. var pos = SugarPosition(x, y);
  4205. var removeScroll = function () {
  4206. var outerScroll = get$8();
  4207. return pos.translate(-outerScroll.left, -outerScroll.top);
  4208. };
  4209. return origin.fold(constant(pos), constant(pos), removeScroll);
  4210. };
  4211. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4212. return subject.fold(onNone, onRelative, onFixed);
  4213. };
  4214. var none$1 = adt$3.none;
  4215. var relative = adt$3.relative;
  4216. var fixed = adt$3.fixed;
  4217. var anchor = function (anchorBox, origin) {
  4218. return {
  4219. anchorBox: anchorBox,
  4220. origin: origin
  4221. };
  4222. };
  4223. var box$1 = function (anchorBox, origin) {
  4224. return anchor(anchorBox, origin);
  4225. };
  4226. var cycleBy = function (value, delta, min, max) {
  4227. var r = value + delta;
  4228. return r > max ? min : r < min ? max : r;
  4229. };
  4230. var clamp = function (value, min, max) {
  4231. return Math.min(Math.max(value, min), max);
  4232. };
  4233. var adt$4 = Adt.generate([
  4234. { fit: ['reposition'] },
  4235. {
  4236. nofit: [
  4237. 'reposition',
  4238. 'deltaW',
  4239. 'deltaH'
  4240. ]
  4241. }
  4242. ]);
  4243. var calcReposition = function (newX, newY, width, height, bounds) {
  4244. var boundsX = bounds.x;
  4245. var boundsY = bounds.y;
  4246. var boundsWidth = bounds.width;
  4247. var boundsHeight = bounds.height;
  4248. var xInBounds = newX >= boundsX;
  4249. var yInBounds = newY >= boundsY;
  4250. var originInBounds = xInBounds && yInBounds;
  4251. var xFit = newX + width <= boundsX + boundsWidth;
  4252. var yFit = newY + height <= boundsY + boundsHeight;
  4253. var sizeInBounds = xFit && yFit;
  4254. var deltaW = Math.abs(Math.min(width, xInBounds ? boundsX + boundsWidth - newX : boundsX - (newX + width)));
  4255. var deltaH = Math.abs(Math.min(height, yInBounds ? boundsY + boundsHeight - newY : boundsY - (newY + height)));
  4256. var maxX = Math.max(bounds.x, bounds.right - width);
  4257. var maxY = Math.max(bounds.y, bounds.bottom - height);
  4258. var limitX = clamp(newX, bounds.x, maxX);
  4259. var limitY = clamp(newY, bounds.y, maxY);
  4260. return {
  4261. originInBounds: originInBounds,
  4262. sizeInBounds: sizeInBounds,
  4263. limitX: limitX,
  4264. limitY: limitY,
  4265. deltaW: deltaW,
  4266. deltaH: deltaH
  4267. };
  4268. };
  4269. var attempt = function (candidate, width, height, bounds) {
  4270. var candidateX = candidate.x;
  4271. var candidateY = candidate.y;
  4272. var bubbleOffsets = candidate.bubble.offset;
  4273. var bubbleLeft = bubbleOffsets.left;
  4274. var bubbleTop = bubbleOffsets.top;
  4275. var adjustedBounds = adjustBounds(bounds, candidate.boundsRestriction, bubbleOffsets);
  4276. var boundsY = adjustedBounds.y;
  4277. var boundsBottom = adjustedBounds.bottom;
  4278. var boundsX = adjustedBounds.x;
  4279. var boundsRight = adjustedBounds.right;
  4280. var newX = candidateX + bubbleLeft;
  4281. var newY = candidateY + bubbleTop;
  4282. var _a = calcReposition(newX, newY, width, height, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, limitX = _a.limitX, limitY = _a.limitY, deltaW = _a.deltaW, deltaH = _a.deltaH;
  4283. var upAvailable = constant(limitY + deltaH - boundsY);
  4284. var downAvailable = constant(boundsBottom - limitY);
  4285. var maxHeight = cataVertical(candidate.direction, downAvailable, downAvailable, upAvailable);
  4286. var westAvailable = constant(limitX + deltaW - boundsX);
  4287. var eastAvailable = constant(boundsRight - limitX);
  4288. var maxWidth = cataHorizontal(candidate.direction, eastAvailable, eastAvailable, westAvailable);
  4289. var reposition = {
  4290. x: limitX,
  4291. y: limitY,
  4292. width: deltaW,
  4293. height: deltaH,
  4294. maxHeight: maxHeight,
  4295. maxWidth: maxWidth,
  4296. direction: candidate.direction,
  4297. classes: {
  4298. on: candidate.bubble.classesOn,
  4299. off: candidate.bubble.classesOff
  4300. },
  4301. label: candidate.label,
  4302. candidateYforTest: newY
  4303. };
  4304. return originInBounds && sizeInBounds ? adt$4.fit(reposition) : adt$4.nofit(reposition, deltaW, deltaH);
  4305. };
  4306. var attempts = function (candidates, anchorBox, elementBox, bubbles, bounds) {
  4307. var panelWidth = elementBox.width;
  4308. var panelHeight = elementBox.height;
  4309. var attemptBestFit = function (layout, reposition, deltaW, deltaH) {
  4310. var next = layout(anchorBox, elementBox, bubbles);
  4311. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4312. return attemptLayout.fold(adt$4.fit, function (newReposition, newDeltaW, newDeltaH) {
  4313. var improved = newDeltaH > deltaH || newDeltaW > deltaW;
  4314. return improved ? adt$4.nofit(newReposition, newDeltaW, newDeltaH) : adt$4.nofit(reposition, deltaW, deltaH);
  4315. });
  4316. };
  4317. var abc = foldl(candidates, function (b, a) {
  4318. var bestNext = curry(attemptBestFit, a);
  4319. return b.fold(adt$4.fit, bestNext);
  4320. }, adt$4.nofit({
  4321. x: anchorBox.x,
  4322. y: anchorBox.y,
  4323. width: elementBox.width,
  4324. height: elementBox.height,
  4325. maxHeight: elementBox.height,
  4326. maxWidth: elementBox.width,
  4327. direction: southeast(),
  4328. classes: {
  4329. on: [],
  4330. off: []
  4331. },
  4332. label: 'none',
  4333. candidateYforTest: anchorBox.y
  4334. }, -1, -1));
  4335. return abc.fold(identity, identity);
  4336. };
  4337. var elementSize = function (p) {
  4338. return {
  4339. width: getOuter$2(p),
  4340. height: getOuter$1(p)
  4341. };
  4342. };
  4343. var layout = function (anchorBox, element, bubbles, options) {
  4344. remove$6(element, 'max-height');
  4345. remove$6(element, 'max-width');
  4346. var elementBox = elementSize(element);
  4347. return attempts(options.preference, anchorBox, elementBox, bubbles, options.bounds);
  4348. };
  4349. var setClasses = function (element, decision) {
  4350. var classInfo = decision.classes;
  4351. remove$5(element, classInfo.off);
  4352. add$3(element, classInfo.on);
  4353. };
  4354. var setHeight = function (element, decision, options) {
  4355. var maxHeightFunction = options.maxHeightFunction;
  4356. maxHeightFunction(element, decision.maxHeight);
  4357. };
  4358. var setWidth = function (element, decision, options) {
  4359. var maxWidthFunction = options.maxWidthFunction;
  4360. maxWidthFunction(element, decision.maxWidth);
  4361. };
  4362. var position = function (element, decision, options) {
  4363. applyPositionCss(element, reposition(options.origin, decision));
  4364. };
  4365. var setMaxHeight = function (element, maxHeight) {
  4366. setMax(element, Math.floor(maxHeight));
  4367. };
  4368. var anchored = constant(function (element, available) {
  4369. setMaxHeight(element, available);
  4370. setAll$1(element, {
  4371. 'overflow-x': 'hidden',
  4372. 'overflow-y': 'auto'
  4373. });
  4374. });
  4375. var expandable = constant(function (element, available) {
  4376. setMaxHeight(element, available);
  4377. });
  4378. var defaultOr = function (options, key, dephault) {
  4379. return options[key] === undefined ? dephault : options[key];
  4380. };
  4381. var simple = function (anchor, element, bubble, layouts, getBounds, overrideOptions) {
  4382. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4383. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4384. var anchorBox = anchor.anchorBox;
  4385. var origin = anchor.origin;
  4386. var options = {
  4387. bounds: viewport$1(origin, getBounds),
  4388. origin: origin,
  4389. preference: layouts,
  4390. maxHeightFunction: maxHeightFunction,
  4391. maxWidthFunction: maxWidthFunction
  4392. };
  4393. go(anchorBox, element, bubble, options);
  4394. };
  4395. var go = function (anchorBox, element, bubble, options) {
  4396. var decision = layout(anchorBox, element, bubble, options);
  4397. position(element, decision, options);
  4398. setClasses(element, decision);
  4399. setHeight(element, decision, options);
  4400. setWidth(element, decision, options);
  4401. };
  4402. var allAlignments = [
  4403. 'valignCentre',
  4404. 'alignLeft',
  4405. 'alignRight',
  4406. 'alignCentre',
  4407. 'top',
  4408. 'bottom',
  4409. 'left',
  4410. 'right'
  4411. ];
  4412. var nu$8 = function (width, yoffset, classes) {
  4413. var getClasses = function (prop) {
  4414. return get(classes, prop).getOr([]);
  4415. };
  4416. var make = function (xDelta, yDelta, alignmentsOn) {
  4417. var alignmentsOff = difference(allAlignments, alignmentsOn);
  4418. return {
  4419. offset: SugarPosition(xDelta, yDelta),
  4420. classesOn: bind(alignmentsOn, getClasses),
  4421. classesOff: bind(alignmentsOff, getClasses)
  4422. };
  4423. };
  4424. return {
  4425. southeast: function () {
  4426. return make(-width, yoffset, [
  4427. 'top',
  4428. 'alignLeft'
  4429. ]);
  4430. },
  4431. southwest: function () {
  4432. return make(width, yoffset, [
  4433. 'top',
  4434. 'alignRight'
  4435. ]);
  4436. },
  4437. south: function () {
  4438. return make(-width / 2, yoffset, [
  4439. 'top',
  4440. 'alignCentre'
  4441. ]);
  4442. },
  4443. northeast: function () {
  4444. return make(-width, -yoffset, [
  4445. 'bottom',
  4446. 'alignLeft'
  4447. ]);
  4448. },
  4449. northwest: function () {
  4450. return make(width, -yoffset, [
  4451. 'bottom',
  4452. 'alignRight'
  4453. ]);
  4454. },
  4455. north: function () {
  4456. return make(-width / 2, -yoffset, [
  4457. 'bottom',
  4458. 'alignCentre'
  4459. ]);
  4460. },
  4461. east: function () {
  4462. return make(width, -yoffset / 2, [
  4463. 'valignCentre',
  4464. 'left'
  4465. ]);
  4466. },
  4467. west: function () {
  4468. return make(-width, -yoffset / 2, [
  4469. 'valignCentre',
  4470. 'right'
  4471. ]);
  4472. },
  4473. innerNorthwest: function () {
  4474. return make(-width, yoffset, [
  4475. 'top',
  4476. 'alignRight'
  4477. ]);
  4478. },
  4479. innerNortheast: function () {
  4480. return make(width, yoffset, [
  4481. 'top',
  4482. 'alignLeft'
  4483. ]);
  4484. },
  4485. innerNorth: function () {
  4486. return make(-width / 2, yoffset, [
  4487. 'top',
  4488. 'alignCentre'
  4489. ]);
  4490. },
  4491. innerSouthwest: function () {
  4492. return make(-width, -yoffset, [
  4493. 'bottom',
  4494. 'alignRight'
  4495. ]);
  4496. },
  4497. innerSoutheast: function () {
  4498. return make(width, -yoffset, [
  4499. 'bottom',
  4500. 'alignLeft'
  4501. ]);
  4502. },
  4503. innerSouth: function () {
  4504. return make(-width / 2, -yoffset, [
  4505. 'bottom',
  4506. 'alignCentre'
  4507. ]);
  4508. },
  4509. innerWest: function () {
  4510. return make(width, -yoffset / 2, [
  4511. 'valignCentre',
  4512. 'right'
  4513. ]);
  4514. },
  4515. innerEast: function () {
  4516. return make(-width, -yoffset / 2, [
  4517. 'valignCentre',
  4518. 'left'
  4519. ]);
  4520. }
  4521. };
  4522. };
  4523. var fallback = function () {
  4524. return nu$8(0, 0, {});
  4525. };
  4526. var nu$9 = function (x) {
  4527. return x;
  4528. };
  4529. var onDirection = function (isLtr, isRtl) {
  4530. return function (element) {
  4531. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4532. };
  4533. };
  4534. var getDirection = function (element) {
  4535. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4536. };
  4537. var AttributeValue;
  4538. (function (AttributeValue) {
  4539. AttributeValue['TopToBottom'] = 'toptobottom';
  4540. AttributeValue['BottomToTop'] = 'bottomtotop';
  4541. }(AttributeValue || (AttributeValue = {})));
  4542. var Attribute = 'data-alloy-vertical-dir';
  4543. var isBottomToTopDir = function (el) {
  4544. return closest$2(el, function (current) {
  4545. return isElement(current) && get$2(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop;
  4546. });
  4547. };
  4548. var schema$1 = function () {
  4549. return optionObjOf('layouts', [
  4550. strict$1('onLtr'),
  4551. strict$1('onRtl'),
  4552. option('onBottomLtr'),
  4553. option('onBottomRtl')
  4554. ]);
  4555. };
  4556. var get$a = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  4557. var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4558. var customLtr = info.layouts.map(function (ls) {
  4559. return ls.onLtr(elem);
  4560. });
  4561. var customRtl = info.layouts.map(function (ls) {
  4562. return ls.onRtl(elem);
  4563. });
  4564. var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  4565. return ls.onBottomLtr.map(function (f) {
  4566. return f(elem);
  4567. });
  4568. }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4569. var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  4570. return ls.onBottomRtl.map(function (f) {
  4571. return f(elem);
  4572. });
  4573. }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4574. var f = onDirection(ltr, rtl);
  4575. return f(elem);
  4576. };
  4577. var placement = function (component, anchorInfo, origin) {
  4578. var hotspot = anchorInfo.hotspot;
  4579. var anchorBox = toBox(origin, hotspot.element);
  4580. var layouts = get$a(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
  4581. return Optional.some(nu$9({
  4582. anchorBox: anchorBox,
  4583. bubble: anchorInfo.bubble.getOr(fallback()),
  4584. overrides: anchorInfo.overrides,
  4585. layouts: layouts,
  4586. placer: Optional.none()
  4587. }));
  4588. };
  4589. var HotspotAnchor = [
  4590. strict$1('hotspot'),
  4591. option('bubble'),
  4592. defaulted$1('overrides', {}),
  4593. schema$1(),
  4594. output('placement', placement)
  4595. ];
  4596. var placement$1 = function (component, anchorInfo, origin) {
  4597. var pos = translate(origin, anchorInfo.x, anchorInfo.y);
  4598. var anchorBox = bounds$1(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
  4599. var layouts = get$a(component.element, anchorInfo, all$2(), allRtl(), all$2(), allRtl(), Optional.none());
  4600. return Optional.some(nu$9({
  4601. anchorBox: anchorBox,
  4602. bubble: anchorInfo.bubble,
  4603. overrides: anchorInfo.overrides,
  4604. layouts: layouts,
  4605. placer: Optional.none()
  4606. }));
  4607. };
  4608. var MakeshiftAnchor = [
  4609. strict$1('x'),
  4610. strict$1('y'),
  4611. defaulted$1('height', 0),
  4612. defaulted$1('width', 0),
  4613. defaulted$1('bubble', fallback()),
  4614. defaulted$1('overrides', {}),
  4615. schema$1(),
  4616. output('placement', placement$1)
  4617. ];
  4618. var zeroWidth = '\uFEFF';
  4619. var nbsp = '\xA0';
  4620. var create$2 = function (start, soffset, finish, foffset) {
  4621. return {
  4622. start: start,
  4623. soffset: soffset,
  4624. finish: finish,
  4625. foffset: foffset
  4626. };
  4627. };
  4628. var SimRange = { create: create$2 };
  4629. var adt$5 = Adt.generate([
  4630. { before: ['element'] },
  4631. {
  4632. on: [
  4633. 'element',
  4634. 'offset'
  4635. ]
  4636. },
  4637. { after: ['element'] }
  4638. ]);
  4639. var cata$2 = function (subject, onBefore, onOn, onAfter) {
  4640. return subject.fold(onBefore, onOn, onAfter);
  4641. };
  4642. var getStart = function (situ) {
  4643. return situ.fold(identity, identity, identity);
  4644. };
  4645. var before$2 = adt$5.before;
  4646. var on = adt$5.on;
  4647. var after$1 = adt$5.after;
  4648. var Situ = {
  4649. before: before$2,
  4650. on: on,
  4651. after: after$1,
  4652. cata: cata$2,
  4653. getStart: getStart
  4654. };
  4655. var adt$6 = Adt.generate([
  4656. { domRange: ['rng'] },
  4657. {
  4658. relative: [
  4659. 'startSitu',
  4660. 'finishSitu'
  4661. ]
  4662. },
  4663. {
  4664. exact: [
  4665. 'start',
  4666. 'soffset',
  4667. 'finish',
  4668. 'foffset'
  4669. ]
  4670. }
  4671. ]);
  4672. var exactFromRange = function (simRange) {
  4673. return adt$6.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  4674. };
  4675. var getStart$1 = function (selection) {
  4676. return selection.match({
  4677. domRange: function (rng) {
  4678. return SugarElement.fromDom(rng.startContainer);
  4679. },
  4680. relative: function (startSitu, _finishSitu) {
  4681. return Situ.getStart(startSitu);
  4682. },
  4683. exact: function (start, _soffset, _finish, _foffset) {
  4684. return start;
  4685. }
  4686. });
  4687. };
  4688. var domRange = adt$6.domRange;
  4689. var relative$1 = adt$6.relative;
  4690. var exact = adt$6.exact;
  4691. var getWin = function (selection) {
  4692. var start = getStart$1(selection);
  4693. return defaultView(start);
  4694. };
  4695. var range$1 = SimRange.create;
  4696. var SimSelection = {
  4697. domRange: domRange,
  4698. relative: relative$1,
  4699. exact: exact,
  4700. exactFromRange: exactFromRange,
  4701. getWin: getWin,
  4702. range: range$1
  4703. };
  4704. var setStart = function (rng, situ) {
  4705. situ.fold(function (e) {
  4706. rng.setStartBefore(e.dom);
  4707. }, function (e, o) {
  4708. rng.setStart(e.dom, o);
  4709. }, function (e) {
  4710. rng.setStartAfter(e.dom);
  4711. });
  4712. };
  4713. var setFinish = function (rng, situ) {
  4714. situ.fold(function (e) {
  4715. rng.setEndBefore(e.dom);
  4716. }, function (e, o) {
  4717. rng.setEnd(e.dom, o);
  4718. }, function (e) {
  4719. rng.setEndAfter(e.dom);
  4720. });
  4721. };
  4722. var relativeToNative = function (win, startSitu, finishSitu) {
  4723. var range = win.document.createRange();
  4724. setStart(range, startSitu);
  4725. setFinish(range, finishSitu);
  4726. return range;
  4727. };
  4728. var exactToNative = function (win, start, soffset, finish, foffset) {
  4729. var rng = win.document.createRange();
  4730. rng.setStart(start.dom, soffset);
  4731. rng.setEnd(finish.dom, foffset);
  4732. return rng;
  4733. };
  4734. var toRect = function (rect) {
  4735. return {
  4736. left: rect.left,
  4737. top: rect.top,
  4738. right: rect.right,
  4739. bottom: rect.bottom,
  4740. width: rect.width,
  4741. height: rect.height
  4742. };
  4743. };
  4744. var getFirstRect = function (rng) {
  4745. var rects = rng.getClientRects();
  4746. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  4747. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  4748. };
  4749. var adt$7 = Adt.generate([
  4750. {
  4751. ltr: [
  4752. 'start',
  4753. 'soffset',
  4754. 'finish',
  4755. 'foffset'
  4756. ]
  4757. },
  4758. {
  4759. rtl: [
  4760. 'start',
  4761. 'soffset',
  4762. 'finish',
  4763. 'foffset'
  4764. ]
  4765. }
  4766. ]);
  4767. var fromRange = function (win, type, range) {
  4768. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  4769. };
  4770. var getRanges = function (win, selection) {
  4771. return selection.match({
  4772. domRange: function (rng) {
  4773. return {
  4774. ltr: constant(rng),
  4775. rtl: Optional.none
  4776. };
  4777. },
  4778. relative: function (startSitu, finishSitu) {
  4779. return {
  4780. ltr: cached(function () {
  4781. return relativeToNative(win, startSitu, finishSitu);
  4782. }),
  4783. rtl: cached(function () {
  4784. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  4785. })
  4786. };
  4787. },
  4788. exact: function (start, soffset, finish, foffset) {
  4789. return {
  4790. ltr: cached(function () {
  4791. return exactToNative(win, start, soffset, finish, foffset);
  4792. }),
  4793. rtl: cached(function () {
  4794. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  4795. })
  4796. };
  4797. }
  4798. });
  4799. };
  4800. var doDiagnose = function (win, ranges) {
  4801. var rng = ranges.ltr();
  4802. if (rng.collapsed) {
  4803. var reversed = ranges.rtl().filter(function (rev) {
  4804. return rev.collapsed === false;
  4805. });
  4806. return reversed.map(function (rev) {
  4807. return adt$7.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  4808. }).getOrThunk(function () {
  4809. return fromRange(win, adt$7.ltr, rng);
  4810. });
  4811. } else {
  4812. return fromRange(win, adt$7.ltr, rng);
  4813. }
  4814. };
  4815. var diagnose = function (win, selection) {
  4816. var ranges = getRanges(win, selection);
  4817. return doDiagnose(win, ranges);
  4818. };
  4819. var asLtrRange = function (win, selection) {
  4820. var diagnosis = diagnose(win, selection);
  4821. return diagnosis.match({
  4822. ltr: function (start, soffset, finish, foffset) {
  4823. var rng = win.document.createRange();
  4824. rng.setStart(start.dom, soffset);
  4825. rng.setEnd(finish.dom, foffset);
  4826. return rng;
  4827. },
  4828. rtl: function (start, soffset, finish, foffset) {
  4829. var rng = win.document.createRange();
  4830. rng.setStart(finish.dom, foffset);
  4831. rng.setEnd(start.dom, soffset);
  4832. return rng;
  4833. }
  4834. });
  4835. };
  4836. var ltr = adt$7.ltr;
  4837. var rtl = adt$7.rtl;
  4838. function NodeValue (is, name) {
  4839. var get = function (element) {
  4840. if (!is(element)) {
  4841. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  4842. }
  4843. return getOption(element).getOr('');
  4844. };
  4845. var getOption = function (element) {
  4846. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  4847. };
  4848. var set = function (element, value) {
  4849. if (!is(element)) {
  4850. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  4851. }
  4852. element.dom.nodeValue = value;
  4853. };
  4854. return {
  4855. get: get,
  4856. getOption: getOption,
  4857. set: set
  4858. };
  4859. }
  4860. var api$2 = NodeValue(isText, 'text');
  4861. var get$b = function (element) {
  4862. return api$2.get(element);
  4863. };
  4864. var getOption = function (element) {
  4865. return api$2.getOption(element);
  4866. };
  4867. var getEnd = function (element) {
  4868. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  4869. return children(element).length;
  4870. }, function (v) {
  4871. return v.length;
  4872. });
  4873. };
  4874. var isTextNodeWithCursorPosition = function (el) {
  4875. return getOption(el).filter(function (text) {
  4876. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  4877. }).isSome();
  4878. };
  4879. var elementsWithCursorPosition = [
  4880. 'img',
  4881. 'br'
  4882. ];
  4883. var isCursorPosition = function (elem) {
  4884. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  4885. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  4886. };
  4887. var last$1 = function (element) {
  4888. return descendantRtl(element, isCursorPosition);
  4889. };
  4890. var descendantRtl = function (scope, predicate) {
  4891. var descend = function (element) {
  4892. var children$1 = children(element);
  4893. for (var i = children$1.length - 1; i >= 0; i--) {
  4894. var child = children$1[i];
  4895. if (predicate(child)) {
  4896. return Optional.some(child);
  4897. }
  4898. var res = descend(child);
  4899. if (res.isSome()) {
  4900. return res;
  4901. }
  4902. }
  4903. return Optional.none();
  4904. };
  4905. return descend(scope);
  4906. };
  4907. var descendants = function (scope, selector) {
  4908. return all(selector, scope);
  4909. };
  4910. var makeRange = function (start, soffset, finish, foffset) {
  4911. var doc = owner(start);
  4912. var rng = doc.dom.createRange();
  4913. rng.setStart(start.dom, soffset);
  4914. rng.setEnd(finish.dom, foffset);
  4915. return rng;
  4916. };
  4917. var after$2 = function (start, soffset, finish, foffset) {
  4918. var r = makeRange(start, soffset, finish, foffset);
  4919. var same = eq$1(start, finish) && soffset === foffset;
  4920. return r.collapsed && !same;
  4921. };
  4922. var getNativeSelection = function (win) {
  4923. return Optional.from(win.getSelection());
  4924. };
  4925. var readRange = function (selection) {
  4926. if (selection.rangeCount > 0) {
  4927. var firstRng = selection.getRangeAt(0);
  4928. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  4929. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  4930. } else {
  4931. return Optional.none();
  4932. }
  4933. };
  4934. var doGetExact = function (selection) {
  4935. if (selection.anchorNode === null || selection.focusNode === null) {
  4936. return readRange(selection);
  4937. } else {
  4938. var anchor = SugarElement.fromDom(selection.anchorNode);
  4939. var focus_1 = SugarElement.fromDom(selection.focusNode);
  4940. return after$2(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  4941. }
  4942. };
  4943. var getExact = function (win) {
  4944. return getNativeSelection(win).filter(function (sel) {
  4945. return sel.rangeCount > 0;
  4946. }).bind(doGetExact);
  4947. };
  4948. var getFirstRect$1 = function (win, selection) {
  4949. var rng = asLtrRange(win, selection);
  4950. return getFirstRect(rng);
  4951. };
  4952. var point = function (element, offset) {
  4953. return {
  4954. element: element,
  4955. offset: offset
  4956. };
  4957. };
  4958. var descendOnce = function (element, offset) {
  4959. var children$1 = children(element);
  4960. if (children$1.length === 0) {
  4961. return point(element, offset);
  4962. } else if (offset < children$1.length) {
  4963. return point(children$1[offset], 0);
  4964. } else {
  4965. var last = children$1[children$1.length - 1];
  4966. var len = isText(last) ? get$b(last).length : children(last).length;
  4967. return point(last, len);
  4968. }
  4969. };
  4970. var adt$8 = Adt.generate([
  4971. { screen: ['point'] },
  4972. {
  4973. absolute: [
  4974. 'point',
  4975. 'scrollLeft',
  4976. 'scrollTop'
  4977. ]
  4978. }
  4979. ]);
  4980. var toFixed = function (pos) {
  4981. return pos.fold(identity, function (point, scrollLeft, scrollTop) {
  4982. return point.translate(-scrollLeft, -scrollTop);
  4983. });
  4984. };
  4985. var toAbsolute = function (pos) {
  4986. return pos.fold(identity, identity);
  4987. };
  4988. var sum = function (points) {
  4989. return foldl(points, function (b, a) {
  4990. return b.translate(a.left, a.top);
  4991. }, SugarPosition(0, 0));
  4992. };
  4993. var sumAsFixed = function (positions) {
  4994. var points = map(positions, toFixed);
  4995. return sum(points);
  4996. };
  4997. var sumAsAbsolute = function (positions) {
  4998. var points = map(positions, toAbsolute);
  4999. return sum(points);
  5000. };
  5001. var screen = adt$8.screen;
  5002. var absolute$2 = adt$8.absolute;
  5003. var getOffset = function (component, origin, anchorInfo) {
  5004. var win = defaultView(anchorInfo.root).dom;
  5005. var hasSameOwner = function (frame) {
  5006. var frameOwner = owner(frame);
  5007. var compOwner = owner(component.element);
  5008. return eq$1(frameOwner, compOwner);
  5009. };
  5010. return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute);
  5011. };
  5012. var getRootPoint = function (component, origin, anchorInfo) {
  5013. var doc = owner(component.element);
  5014. var outerScroll = get$8(doc);
  5015. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  5016. return absolute$2(offset, outerScroll.left, outerScroll.top);
  5017. };
  5018. var capRect = function (left, top, width, height) {
  5019. var newLeft = left, newTop = top, newWidth = width, newHeight = height;
  5020. if (left < 0) {
  5021. newLeft = 0;
  5022. newWidth = width + left;
  5023. }
  5024. if (top < 0) {
  5025. newTop = 0;
  5026. newHeight = height + top;
  5027. }
  5028. var point = screen(SugarPosition(newLeft, newTop));
  5029. return Optional.some(pointed(point, newWidth, newHeight));
  5030. };
  5031. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  5032. return optBox.map(function (box) {
  5033. var points = [
  5034. rootPoint,
  5035. box.point
  5036. ];
  5037. var topLeft = cata$1(origin, function () {
  5038. return sumAsAbsolute(points);
  5039. }, function () {
  5040. return sumAsAbsolute(points);
  5041. }, function () {
  5042. return sumAsFixed(points);
  5043. });
  5044. var anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height);
  5045. var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  5046. var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
  5047. var layouts = get$a(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
  5048. return nu$9({
  5049. anchorBox: anchorBox,
  5050. bubble: anchorInfo.bubble.getOr(fallback()),
  5051. overrides: anchorInfo.overrides,
  5052. layouts: layouts,
  5053. placer: Optional.none()
  5054. });
  5055. });
  5056. };
  5057. var point$1 = function (element, offset) {
  5058. return {
  5059. element: element,
  5060. offset: offset
  5061. };
  5062. };
  5063. var descendOnce$1 = function (element, offset) {
  5064. return isText(element) ? point$1(element, offset) : descendOnce(element, offset);
  5065. };
  5066. var getAnchorSelection = function (win, anchorInfo) {
  5067. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  5068. return function () {
  5069. return getExact(win);
  5070. };
  5071. });
  5072. return getSelection().map(function (sel) {
  5073. var modStart = descendOnce$1(sel.start, sel.soffset);
  5074. var modFinish = descendOnce$1(sel.finish, sel.foffset);
  5075. return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  5076. });
  5077. };
  5078. var placement$2 = function (component, anchorInfo, origin) {
  5079. var win = defaultView(anchorInfo.root).dom;
  5080. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5081. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5082. var optRect = getFirstRect$1(win, SimSelection.exactFromRange(sel)).orThunk(function () {
  5083. var x = SugarElement.fromText(zeroWidth);
  5084. before(sel.start, x);
  5085. return getFirstRect$1(win, SimSelection.exact(x, 0, x, 1)).map(function (rect) {
  5086. remove(x);
  5087. return rect;
  5088. });
  5089. });
  5090. return optRect.bind(function (rawRect) {
  5091. return capRect(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
  5092. });
  5093. });
  5094. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5095. return isElement(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
  5096. });
  5097. var elem = targetElement.getOr(component.element);
  5098. return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  5099. };
  5100. var SelectionAnchor = [
  5101. option('getSelection'),
  5102. strict$1('root'),
  5103. option('bubble'),
  5104. schema$1(),
  5105. defaulted$1('overrides', {}),
  5106. defaulted$1('showAbove', false),
  5107. output('placement', placement$2)
  5108. ];
  5109. var placement$3 = function (component, anchorInfo, origin) {
  5110. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5111. return anchorInfo.node.bind(function (target) {
  5112. var rect = target.dom.getBoundingClientRect();
  5113. var nodeBox = capRect(rect.left, rect.top, rect.width, rect.height);
  5114. var elem = anchorInfo.node.getOr(component.element);
  5115. return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5116. });
  5117. };
  5118. var NodeAnchor = [
  5119. strict$1('node'),
  5120. strict$1('root'),
  5121. option('bubble'),
  5122. schema$1(),
  5123. defaulted$1('overrides', {}),
  5124. defaulted$1('showAbove', false),
  5125. output('placement', placement$3)
  5126. ];
  5127. var eastX$1 = function (anchor) {
  5128. return anchor.x + anchor.width;
  5129. };
  5130. var westX$1 = function (anchor, element) {
  5131. return anchor.x - element.width;
  5132. };
  5133. var northY$1 = function (anchor, element) {
  5134. return anchor.y - element.height + anchor.height;
  5135. };
  5136. var southY$1 = function (anchor) {
  5137. return anchor.y;
  5138. };
  5139. var southeast$2 = function (anchor, element, bubbles) {
  5140. return nu$7(eastX$1(anchor), southY$1(anchor), bubbles.southeast(), southeast(), boundsRestriction(anchor, {
  5141. left: 0,
  5142. top: 2
  5143. }), 'link-layout-se');
  5144. };
  5145. var southwest$2 = function (anchor, element, bubbles) {
  5146. return nu$7(westX$1(anchor, element), southY$1(anchor), bubbles.southwest(), southwest(), boundsRestriction(anchor, {
  5147. right: 1,
  5148. top: 2
  5149. }), 'link-layout-sw');
  5150. };
  5151. var northeast$2 = function (anchor, element, bubbles) {
  5152. return nu$7(eastX$1(anchor), northY$1(anchor, element), bubbles.northeast(), northeast(), boundsRestriction(anchor, {
  5153. left: 0,
  5154. bottom: 3
  5155. }), 'link-layout-ne');
  5156. };
  5157. var northwest$2 = function (anchor, element, bubbles) {
  5158. return nu$7(westX$1(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest(), boundsRestriction(anchor, {
  5159. right: 1,
  5160. bottom: 3
  5161. }), 'link-layout-nw');
  5162. };
  5163. var all$3 = function () {
  5164. return [
  5165. southeast$2,
  5166. southwest$2,
  5167. northeast$2,
  5168. northwest$2
  5169. ];
  5170. };
  5171. var allRtl$1 = function () {
  5172. return [
  5173. southwest$2,
  5174. southeast$2,
  5175. northwest$2,
  5176. northeast$2
  5177. ];
  5178. };
  5179. var placement$4 = function (component, submenuInfo, origin) {
  5180. var anchorBox = toBox(origin, submenuInfo.item.element);
  5181. var layouts = get$a(component.element, submenuInfo, all$3(), allRtl$1(), all$3(), allRtl$1(), Optional.none());
  5182. return Optional.some(nu$9({
  5183. anchorBox: anchorBox,
  5184. bubble: fallback(),
  5185. overrides: submenuInfo.overrides,
  5186. layouts: layouts,
  5187. placer: Optional.none()
  5188. }));
  5189. };
  5190. var SubmenuAnchor = [
  5191. strict$1('item'),
  5192. schema$1(),
  5193. defaulted$1('overrides', {}),
  5194. output('placement', placement$4)
  5195. ];
  5196. var AnchorSchema = choose$1('anchor', {
  5197. selection: SelectionAnchor,
  5198. node: NodeAnchor,
  5199. hotspot: HotspotAnchor,
  5200. submenu: SubmenuAnchor,
  5201. makeshift: MakeshiftAnchor
  5202. });
  5203. var getFixedOrigin = function () {
  5204. var html = document.documentElement;
  5205. return fixed(0, 0, html.clientWidth, html.clientHeight);
  5206. };
  5207. var getRelativeOrigin = function (component) {
  5208. var position = absolute(component.element);
  5209. var bounds = component.element.dom.getBoundingClientRect();
  5210. return relative(position.left, position.top, bounds.width, bounds.height);
  5211. };
  5212. var place = function (component, origin, anchoring, getBounds, placee) {
  5213. var anchor = box$1(anchoring.anchorBox, origin);
  5214. simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, getBounds, anchoring.overrides);
  5215. };
  5216. var position$1 = function (component, posConfig, posState, anchor, placee) {
  5217. positionWithin(component, posConfig, posState, anchor, placee, Optional.none());
  5218. };
  5219. var positionWithin = function (component, posConfig, posState, anchor, placee, boxElement) {
  5220. var boundsBox = boxElement.map(box);
  5221. return positionWithinBounds(component, posConfig, posState, anchor, placee, boundsBox);
  5222. };
  5223. var positionWithinBounds = function (component, posConfig, posState, anchor, placee, bounds) {
  5224. var anchorage = asRawOrDie('positioning anchor.info', AnchorSchema, anchor);
  5225. preserve(function () {
  5226. set$2(placee.element, 'position', 'fixed');
  5227. var oldVisibility = getRaw(placee.element, 'visibility');
  5228. set$2(placee.element, 'visibility', 'hidden');
  5229. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5230. var placer = anchorage.placement;
  5231. var getBounds = bounds.map(constant).or(posConfig.getBounds);
  5232. placer(component, anchorage, origin).each(function (anchoring) {
  5233. var doPlace = anchoring.placer.getOr(place);
  5234. doPlace(component, origin, anchoring, getBounds, placee);
  5235. });
  5236. oldVisibility.fold(function () {
  5237. remove$6(placee.element, 'visibility');
  5238. }, function (vis) {
  5239. set$2(placee.element, 'visibility', vis);
  5240. });
  5241. if (getRaw(placee.element, 'left').isNone() && getRaw(placee.element, 'top').isNone() && getRaw(placee.element, 'right').isNone() && getRaw(placee.element, 'bottom').isNone() && getRaw(placee.element, 'position').is('fixed')) {
  5242. remove$6(placee.element, 'position');
  5243. }
  5244. }, placee.element);
  5245. };
  5246. var getMode = function (component, pConfig, _pState) {
  5247. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5248. };
  5249. var PositionApis = /*#__PURE__*/Object.freeze({
  5250. __proto__: null,
  5251. position: position$1,
  5252. positionWithin: positionWithin,
  5253. positionWithinBounds: positionWithinBounds,
  5254. getMode: getMode
  5255. });
  5256. var PositionSchema = [
  5257. defaulted$1('useFixed', never),
  5258. option('getBounds')
  5259. ];
  5260. var Positioning = create$1({
  5261. fields: PositionSchema,
  5262. name: 'positioning',
  5263. active: ActivePosition,
  5264. apis: PositionApis
  5265. });
  5266. var fireDetaching = function (component) {
  5267. emit(component, detachedFromDom());
  5268. var children = component.components();
  5269. each(children, fireDetaching);
  5270. };
  5271. var fireAttaching = function (component) {
  5272. var children = component.components();
  5273. each(children, fireAttaching);
  5274. emit(component, attachedToDom());
  5275. };
  5276. var attach = function (parent, child) {
  5277. append(parent.element, child.element);
  5278. };
  5279. var detachChildren = function (component) {
  5280. each(component.components(), function (childComp) {
  5281. return remove(childComp.element);
  5282. });
  5283. empty(component.element);
  5284. component.syncComponents();
  5285. };
  5286. var replaceChildren = function (component, newChildren) {
  5287. var subs = component.components();
  5288. detachChildren(component);
  5289. var deleted = difference(subs, newChildren);
  5290. each(deleted, function (comp) {
  5291. fireDetaching(comp);
  5292. component.getSystem().removeFromWorld(comp);
  5293. });
  5294. each(newChildren, function (childComp) {
  5295. if (!childComp.getSystem().isConnected()) {
  5296. component.getSystem().addToWorld(childComp);
  5297. attach(component, childComp);
  5298. if (inBody(component.element)) {
  5299. fireAttaching(childComp);
  5300. }
  5301. } else {
  5302. attach(component, childComp);
  5303. }
  5304. component.syncComponents();
  5305. });
  5306. };
  5307. var attach$1 = function (parent, child) {
  5308. attachWith(parent, child, append);
  5309. };
  5310. var attachWith = function (parent, child, insertion) {
  5311. parent.getSystem().addToWorld(child);
  5312. insertion(parent.element, child.element);
  5313. if (inBody(parent.element)) {
  5314. fireAttaching(child);
  5315. }
  5316. parent.syncComponents();
  5317. };
  5318. var doDetach = function (component) {
  5319. fireDetaching(component);
  5320. remove(component.element);
  5321. component.getSystem().removeFromWorld(component);
  5322. };
  5323. var detach = function (component) {
  5324. var parent$1 = parent(component.element).bind(function (p) {
  5325. return component.getSystem().getByDom(p).toOptional();
  5326. });
  5327. doDetach(component);
  5328. parent$1.each(function (p) {
  5329. p.syncComponents();
  5330. });
  5331. };
  5332. var detachChildren$1 = function (component) {
  5333. var subs = component.components();
  5334. each(subs, doDetach);
  5335. empty(component.element);
  5336. component.syncComponents();
  5337. };
  5338. var attachSystem = function (element, guiSystem) {
  5339. attachSystemWith(element, guiSystem, append);
  5340. };
  5341. var attachSystemAfter = function (element, guiSystem) {
  5342. attachSystemWith(element, guiSystem, after);
  5343. };
  5344. var attachSystemWith = function (element, guiSystem, inserter) {
  5345. inserter(element, guiSystem.element);
  5346. var children$1 = children(guiSystem.element);
  5347. each(children$1, function (child) {
  5348. guiSystem.getByDom(child).each(fireAttaching);
  5349. });
  5350. };
  5351. var detachSystem = function (guiSystem) {
  5352. var children$1 = children(guiSystem.element);
  5353. each(children$1, function (child) {
  5354. guiSystem.getByDom(child).each(fireDetaching);
  5355. });
  5356. remove(guiSystem.element);
  5357. };
  5358. var rebuild = function (sandbox, sConfig, sState, data) {
  5359. sState.get().each(function (_data) {
  5360. detachChildren$1(sandbox);
  5361. });
  5362. var point = sConfig.getAttachPoint(sandbox);
  5363. attach$1(point, sandbox);
  5364. var built = sandbox.getSystem().build(data);
  5365. attach$1(sandbox, built);
  5366. sState.set(built);
  5367. return built;
  5368. };
  5369. var open = function (sandbox, sConfig, sState, data) {
  5370. var newState = rebuild(sandbox, sConfig, sState, data);
  5371. sConfig.onOpen(sandbox, newState);
  5372. return newState;
  5373. };
  5374. var setContent = function (sandbox, sConfig, sState, data) {
  5375. return sState.get().map(function () {
  5376. return rebuild(sandbox, sConfig, sState, data);
  5377. });
  5378. };
  5379. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5380. cloak(sandbox, sConfig);
  5381. open(sandbox, sConfig, sState, data);
  5382. transaction();
  5383. decloak(sandbox, sConfig);
  5384. };
  5385. var close = function (sandbox, sConfig, sState) {
  5386. sState.get().each(function (data) {
  5387. detachChildren$1(sandbox);
  5388. detach(sandbox);
  5389. sConfig.onClose(sandbox, data);
  5390. sState.clear();
  5391. });
  5392. };
  5393. var isOpen = function (_sandbox, _sConfig, sState) {
  5394. return sState.isOpen();
  5395. };
  5396. var isPartOf$1 = function (sandbox, sConfig, sState, queryElem) {
  5397. return isOpen(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5398. return sConfig.isPartOf(sandbox, data, queryElem);
  5399. });
  5400. };
  5401. var getState = function (_sandbox, _sConfig, sState) {
  5402. return sState.get();
  5403. };
  5404. var store = function (sandbox, cssKey, attr, newValue) {
  5405. getRaw(sandbox.element, cssKey).fold(function () {
  5406. remove$1(sandbox.element, attr);
  5407. }, function (v) {
  5408. set$1(sandbox.element, attr, v);
  5409. });
  5410. set$2(sandbox.element, cssKey, newValue);
  5411. };
  5412. var restore = function (sandbox, cssKey, attr) {
  5413. getOpt(sandbox.element, attr).fold(function () {
  5414. return remove$6(sandbox.element, cssKey);
  5415. }, function (oldValue) {
  5416. return set$2(sandbox.element, cssKey, oldValue);
  5417. });
  5418. };
  5419. var cloak = function (sandbox, sConfig, _sState) {
  5420. var sink = sConfig.getAttachPoint(sandbox);
  5421. set$2(sandbox.element, 'position', Positioning.getMode(sink));
  5422. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5423. };
  5424. var hasPosition = function (element) {
  5425. return exists([
  5426. 'top',
  5427. 'left',
  5428. 'right',
  5429. 'bottom'
  5430. ], function (pos) {
  5431. return getRaw(element, pos).isSome();
  5432. });
  5433. };
  5434. var decloak = function (sandbox, sConfig, _sState) {
  5435. if (!hasPosition(sandbox.element)) {
  5436. remove$6(sandbox.element, 'position');
  5437. }
  5438. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5439. };
  5440. var SandboxApis = /*#__PURE__*/Object.freeze({
  5441. __proto__: null,
  5442. cloak: cloak,
  5443. decloak: decloak,
  5444. open: open,
  5445. openWhileCloaked: openWhileCloaked,
  5446. close: close,
  5447. isOpen: isOpen,
  5448. isPartOf: isPartOf$1,
  5449. getState: getState,
  5450. setContent: setContent
  5451. });
  5452. var events$2 = function (sandboxConfig, sandboxState) {
  5453. return derive([run(sandboxClose(), function (sandbox, _simulatedEvent) {
  5454. close(sandbox, sandboxConfig, sandboxState);
  5455. })]);
  5456. };
  5457. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5458. __proto__: null,
  5459. events: events$2
  5460. });
  5461. var SandboxSchema = [
  5462. onHandler('onOpen'),
  5463. onHandler('onClose'),
  5464. strict$1('isPartOf'),
  5465. strict$1('getAttachPoint'),
  5466. defaulted$1('cloakVisibilityAttr', 'data-precloak-visibility')
  5467. ];
  5468. var init = function () {
  5469. var contents = Cell(Optional.none());
  5470. var readState = constant('not-implemented');
  5471. var isOpen = function () {
  5472. return contents.get().isSome();
  5473. };
  5474. var set = function (comp) {
  5475. contents.set(Optional.some(comp));
  5476. };
  5477. var get = function () {
  5478. return contents.get();
  5479. };
  5480. var clear = function () {
  5481. contents.set(Optional.none());
  5482. };
  5483. return nu$5({
  5484. readState: readState,
  5485. isOpen: isOpen,
  5486. clear: clear,
  5487. set: set,
  5488. get: get
  5489. });
  5490. };
  5491. var SandboxState = /*#__PURE__*/Object.freeze({
  5492. __proto__: null,
  5493. init: init
  5494. });
  5495. var Sandboxing = create$1({
  5496. fields: SandboxSchema,
  5497. name: 'sandboxing',
  5498. active: ActiveSandbox,
  5499. apis: SandboxApis,
  5500. state: SandboxState
  5501. });
  5502. var dismissPopups = constant('dismiss.popups');
  5503. var repositionPopups = constant('reposition.popups');
  5504. var mouseReleased = constant('mouse.released');
  5505. var schema$2 = objOfOnly([
  5506. defaulted$1('isExtraPart', never),
  5507. optionObjOf('fireEventInstead', [defaulted$1('event', dismissRequested())])
  5508. ]);
  5509. var receivingChannel = function (rawSpec) {
  5510. var _a;
  5511. var detail = asRawOrDie('Dismissal', schema$2, rawSpec);
  5512. return _a = {}, _a[dismissPopups()] = {
  5513. schema: objOfOnly([strict$1('target')]),
  5514. onReceive: function (sandbox, data) {
  5515. if (Sandboxing.isOpen(sandbox)) {
  5516. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5517. if (!isPart) {
  5518. detail.fireEventInstead.fold(function () {
  5519. return Sandboxing.close(sandbox);
  5520. }, function (fe) {
  5521. return emit(sandbox, fe.event);
  5522. });
  5523. }
  5524. }
  5525. }
  5526. }, _a;
  5527. };
  5528. var schema$3 = objOfOnly([
  5529. optionObjOf('fireEventInstead', [defaulted$1('event', repositionRequested())]),
  5530. strictFunction('doReposition')
  5531. ]);
  5532. var receivingChannel$1 = function (rawSpec) {
  5533. var _a;
  5534. var detail = asRawOrDie('Reposition', schema$3, rawSpec);
  5535. return _a = {}, _a[repositionPopups()] = {
  5536. onReceive: function (sandbox) {
  5537. if (Sandboxing.isOpen(sandbox)) {
  5538. detail.fireEventInstead.fold(function () {
  5539. return detail.doReposition(sandbox);
  5540. }, function (fe) {
  5541. return emit(sandbox, fe.event);
  5542. });
  5543. }
  5544. }
  5545. }, _a;
  5546. };
  5547. var onLoad = function (component, repConfig, repState) {
  5548. repConfig.store.manager.onLoad(component, repConfig, repState);
  5549. };
  5550. var onUnload = function (component, repConfig, repState) {
  5551. repConfig.store.manager.onUnload(component, repConfig, repState);
  5552. };
  5553. var setValue = function (component, repConfig, repState, data) {
  5554. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5555. };
  5556. var getValue = function (component, repConfig, repState) {
  5557. return repConfig.store.manager.getValue(component, repConfig, repState);
  5558. };
  5559. var getState$1 = function (component, repConfig, repState) {
  5560. return repState;
  5561. };
  5562. var RepresentApis = /*#__PURE__*/Object.freeze({
  5563. __proto__: null,
  5564. onLoad: onLoad,
  5565. onUnload: onUnload,
  5566. setValue: setValue,
  5567. getValue: getValue,
  5568. getState: getState$1
  5569. });
  5570. var events$3 = function (repConfig, repState) {
  5571. var es = repConfig.resetOnDom ? [
  5572. runOnAttached(function (comp, _se) {
  5573. onLoad(comp, repConfig, repState);
  5574. }),
  5575. runOnDetached(function (comp, _se) {
  5576. onUnload(comp, repConfig, repState);
  5577. })
  5578. ] : [loadEvent(repConfig, repState, onLoad)];
  5579. return derive(es);
  5580. };
  5581. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5582. __proto__: null,
  5583. events: events$3
  5584. });
  5585. var memory = function () {
  5586. var data = Cell(null);
  5587. var readState = function () {
  5588. return {
  5589. mode: 'memory',
  5590. value: data.get()
  5591. };
  5592. };
  5593. var isNotSet = function () {
  5594. return data.get() === null;
  5595. };
  5596. var clear = function () {
  5597. data.set(null);
  5598. };
  5599. return nu$5({
  5600. set: data.set,
  5601. get: data.get,
  5602. isNotSet: isNotSet,
  5603. clear: clear,
  5604. readState: readState
  5605. });
  5606. };
  5607. var manual = function () {
  5608. var readState = function () {
  5609. };
  5610. return nu$5({ readState: readState });
  5611. };
  5612. var dataset = function () {
  5613. var dataByValue = Cell({});
  5614. var dataByText = Cell({});
  5615. var readState = function () {
  5616. return {
  5617. mode: 'dataset',
  5618. dataByValue: dataByValue.get(),
  5619. dataByText: dataByText.get()
  5620. };
  5621. };
  5622. var clear = function () {
  5623. dataByValue.set({});
  5624. dataByText.set({});
  5625. };
  5626. var lookup = function (itemString) {
  5627. return get(dataByValue.get(), itemString).orThunk(function () {
  5628. return get(dataByText.get(), itemString);
  5629. });
  5630. };
  5631. var update = function (items) {
  5632. var currentDataByValue = dataByValue.get();
  5633. var currentDataByText = dataByText.get();
  5634. var newDataByValue = {};
  5635. var newDataByText = {};
  5636. each(items, function (item) {
  5637. newDataByValue[item.value] = item;
  5638. get(item, 'meta').each(function (meta) {
  5639. get(meta, 'text').each(function (text) {
  5640. newDataByText[text] = item;
  5641. });
  5642. });
  5643. });
  5644. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5645. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5646. };
  5647. return nu$5({
  5648. readState: readState,
  5649. lookup: lookup,
  5650. update: update,
  5651. clear: clear
  5652. });
  5653. };
  5654. var init$1 = function (spec) {
  5655. return spec.store.manager.state(spec);
  5656. };
  5657. var RepresentState = /*#__PURE__*/Object.freeze({
  5658. __proto__: null,
  5659. memory: memory,
  5660. dataset: dataset,
  5661. manual: manual,
  5662. init: init$1
  5663. });
  5664. var setValue$1 = function (component, repConfig, repState, data) {
  5665. var store = repConfig.store;
  5666. repState.update([data]);
  5667. store.setValue(component, data);
  5668. repConfig.onSetValue(component, data);
  5669. };
  5670. var getValue$1 = function (component, repConfig, repState) {
  5671. var store = repConfig.store;
  5672. var key = store.getDataKey(component);
  5673. return repState.lookup(key).fold(function () {
  5674. return store.getFallbackEntry(key);
  5675. }, function (data) {
  5676. return data;
  5677. });
  5678. };
  5679. var onLoad$1 = function (component, repConfig, repState) {
  5680. var store = repConfig.store;
  5681. store.initialValue.each(function (data) {
  5682. setValue$1(component, repConfig, repState, data);
  5683. });
  5684. };
  5685. var onUnload$1 = function (component, repConfig, repState) {
  5686. repState.clear();
  5687. };
  5688. var DatasetStore = [
  5689. option('initialValue'),
  5690. strict$1('getFallbackEntry'),
  5691. strict$1('getDataKey'),
  5692. strict$1('setValue'),
  5693. output('manager', {
  5694. setValue: setValue$1,
  5695. getValue: getValue$1,
  5696. onLoad: onLoad$1,
  5697. onUnload: onUnload$1,
  5698. state: dataset
  5699. })
  5700. ];
  5701. var getValue$2 = function (component, repConfig, _repState) {
  5702. return repConfig.store.getValue(component);
  5703. };
  5704. var setValue$2 = function (component, repConfig, _repState, data) {
  5705. repConfig.store.setValue(component, data);
  5706. repConfig.onSetValue(component, data);
  5707. };
  5708. var onLoad$2 = function (component, repConfig, _repState) {
  5709. repConfig.store.initialValue.each(function (data) {
  5710. repConfig.store.setValue(component, data);
  5711. });
  5712. };
  5713. var ManualStore = [
  5714. strict$1('getValue'),
  5715. defaulted$1('setValue', noop),
  5716. option('initialValue'),
  5717. output('manager', {
  5718. setValue: setValue$2,
  5719. getValue: getValue$2,
  5720. onLoad: onLoad$2,
  5721. onUnload: noop,
  5722. state: NoState.init
  5723. })
  5724. ];
  5725. var setValue$3 = function (component, repConfig, repState, data) {
  5726. repState.set(data);
  5727. repConfig.onSetValue(component, data);
  5728. };
  5729. var getValue$3 = function (component, repConfig, repState) {
  5730. return repState.get();
  5731. };
  5732. var onLoad$3 = function (component, repConfig, repState) {
  5733. repConfig.store.initialValue.each(function (initVal) {
  5734. if (repState.isNotSet()) {
  5735. repState.set(initVal);
  5736. }
  5737. });
  5738. };
  5739. var onUnload$2 = function (component, repConfig, repState) {
  5740. repState.clear();
  5741. };
  5742. var MemoryStore = [
  5743. option('initialValue'),
  5744. output('manager', {
  5745. setValue: setValue$3,
  5746. getValue: getValue$3,
  5747. onLoad: onLoad$3,
  5748. onUnload: onUnload$2,
  5749. state: memory
  5750. })
  5751. ];
  5752. var RepresentSchema = [
  5753. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5754. memory: MemoryStore,
  5755. manual: ManualStore,
  5756. dataset: DatasetStore
  5757. })),
  5758. onHandler('onSetValue'),
  5759. defaulted$1('resetOnDom', false)
  5760. ];
  5761. var Representing = create$1({
  5762. fields: RepresentSchema,
  5763. name: 'representing',
  5764. active: ActiveRepresenting,
  5765. apis: RepresentApis,
  5766. extra: {
  5767. setValueFrom: function (component, source) {
  5768. var value = Representing.getValue(source);
  5769. Representing.setValue(component, value);
  5770. }
  5771. },
  5772. state: RepresentState
  5773. });
  5774. var field$1 = function (name, forbidden) {
  5775. return defaultedObjOf(name, {}, map(forbidden, function (f) {
  5776. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  5777. }).concat([state$1('dump', identity)]));
  5778. };
  5779. var get$c = function (data) {
  5780. return data.dump;
  5781. };
  5782. var augment = function (data, original) {
  5783. return __assign(__assign({}, data.dump), derive$1(original));
  5784. };
  5785. var SketchBehaviours = {
  5786. field: field$1,
  5787. augment: augment,
  5788. get: get$c
  5789. };
  5790. var _placeholder = 'placeholder';
  5791. var adt$9 = Adt.generate([
  5792. {
  5793. single: [
  5794. 'required',
  5795. 'valueThunk'
  5796. ]
  5797. },
  5798. {
  5799. multiple: [
  5800. 'required',
  5801. 'valueThunks'
  5802. ]
  5803. }
  5804. ]);
  5805. var isSubstituted = function (spec) {
  5806. return has(spec, 'uiType');
  5807. };
  5808. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  5809. if (owner.exists(function (o) {
  5810. return o !== compSpec.owner;
  5811. })) {
  5812. return adt$9.single(true, constant(compSpec));
  5813. }
  5814. return get(placeholders, compSpec.name).fold(function () {
  5815. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  5816. }, function (newSpec) {
  5817. return newSpec.replace();
  5818. });
  5819. };
  5820. var scan = function (owner, detail, compSpec, placeholders) {
  5821. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  5822. return subPlaceholder(owner, detail, compSpec, placeholders);
  5823. } else {
  5824. return adt$9.single(false, constant(compSpec));
  5825. }
  5826. };
  5827. var substitute = function (owner, detail, compSpec, placeholders) {
  5828. var base = scan(owner, detail, compSpec, placeholders);
  5829. return base.fold(function (req, valueThunk) {
  5830. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  5831. var childSpecs = get(value, 'components').getOr([]);
  5832. var substituted = bind(childSpecs, function (c) {
  5833. return substitute(owner, detail, c, placeholders);
  5834. });
  5835. return [__assign(__assign({}, value), { components: substituted })];
  5836. }, function (req, valuesThunk) {
  5837. if (isSubstituted(compSpec)) {
  5838. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5839. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  5840. return preprocessor(values);
  5841. } else {
  5842. return valuesThunk(detail);
  5843. }
  5844. });
  5845. };
  5846. var substituteAll = function (owner, detail, components, placeholders) {
  5847. return bind(components, function (c) {
  5848. return substitute(owner, detail, c, placeholders);
  5849. });
  5850. };
  5851. var oneReplace = function (label, replacements) {
  5852. var called = false;
  5853. var used = function () {
  5854. return called;
  5855. };
  5856. var replace = function () {
  5857. if (called) {
  5858. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5859. }
  5860. called = true;
  5861. return replacements;
  5862. };
  5863. var required = function () {
  5864. return replacements.fold(function (req, _) {
  5865. return req;
  5866. }, function (req, _) {
  5867. return req;
  5868. });
  5869. };
  5870. return {
  5871. name: constant(label),
  5872. required: required,
  5873. used: used,
  5874. replace: replace
  5875. };
  5876. };
  5877. var substitutePlaces = function (owner, detail, components, placeholders) {
  5878. var ps = map$2(placeholders, function (ph, name) {
  5879. return oneReplace(name, ph);
  5880. });
  5881. var outcome = substituteAll(owner, detail, components, ps);
  5882. each$1(ps, function (p) {
  5883. if (p.used() === false && p.required()) {
  5884. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  5885. }
  5886. });
  5887. return outcome;
  5888. };
  5889. var single = adt$9.single;
  5890. var multiple = adt$9.multiple;
  5891. var placeholder = constant(_placeholder);
  5892. var adt$a = Adt.generate([
  5893. { required: ['data'] },
  5894. { external: ['data'] },
  5895. { optional: ['data'] },
  5896. { group: ['data'] }
  5897. ]);
  5898. var fFactory = defaulted$1('factory', { sketch: identity });
  5899. var fSchema = defaulted$1('schema', []);
  5900. var fName = strict$1('name');
  5901. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  5902. return '<alloy.' + generate$1(typeSpec.name) + '>';
  5903. }), anyValue$1());
  5904. var fGroupSchema = state$1('schema', function () {
  5905. return [option('preprocess')];
  5906. });
  5907. var fDefaults = defaulted$1('defaults', constant({}));
  5908. var fOverrides = defaulted$1('overrides', constant({}));
  5909. var requiredSpec = objOf([
  5910. fFactory,
  5911. fSchema,
  5912. fName,
  5913. fPname,
  5914. fDefaults,
  5915. fOverrides
  5916. ]);
  5917. var externalSpec = objOf([
  5918. fFactory,
  5919. fSchema,
  5920. fName,
  5921. fDefaults,
  5922. fOverrides
  5923. ]);
  5924. var optionalSpec = objOf([
  5925. fFactory,
  5926. fSchema,
  5927. fName,
  5928. fPname,
  5929. fDefaults,
  5930. fOverrides
  5931. ]);
  5932. var groupSpec = objOf([
  5933. fFactory,
  5934. fGroupSchema,
  5935. fName,
  5936. strict$1('unit'),
  5937. fPname,
  5938. fDefaults,
  5939. fOverrides
  5940. ]);
  5941. var asNamedPart = function (part) {
  5942. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  5943. };
  5944. var name$1 = function (part) {
  5945. var get = function (data) {
  5946. return data.name;
  5947. };
  5948. return part.fold(get, get, get, get);
  5949. };
  5950. var asCommon = function (part) {
  5951. return part.fold(identity, identity, identity, identity);
  5952. };
  5953. var convert = function (adtConstructor, partSchema) {
  5954. return function (spec) {
  5955. var data = asRawOrDie('Converting part type', partSchema, spec);
  5956. return adtConstructor(data);
  5957. };
  5958. };
  5959. var required = convert(adt$a.required, requiredSpec);
  5960. var external$1 = convert(adt$a.external, externalSpec);
  5961. var optional = convert(adt$a.optional, optionalSpec);
  5962. var group = convert(adt$a.group, groupSpec);
  5963. var original = constant('entirety');
  5964. var PartType = /*#__PURE__*/Object.freeze({
  5965. __proto__: null,
  5966. required: required,
  5967. external: external$1,
  5968. optional: optional,
  5969. group: group,
  5970. asNamedPart: asNamedPart,
  5971. name: name$1,
  5972. asCommon: asCommon,
  5973. original: original
  5974. });
  5975. var combine$2 = function (detail, data, partSpec, partValidated) {
  5976. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5977. };
  5978. var subs = function (owner, detail, parts) {
  5979. var internals = {};
  5980. var externals = {};
  5981. each(parts, function (part) {
  5982. part.fold(function (data) {
  5983. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  5984. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5985. });
  5986. }, function (data) {
  5987. var partSpec = detail.parts[data.name];
  5988. externals[data.name] = constant(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  5989. }, function (data) {
  5990. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  5991. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5992. });
  5993. }, function (data) {
  5994. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  5995. var units = detail[data.name];
  5996. return map(units, function (u) {
  5997. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  5998. });
  5999. });
  6000. });
  6001. });
  6002. return {
  6003. internals: constant(internals),
  6004. externals: constant(externals)
  6005. };
  6006. };
  6007. var generate$4 = function (owner, parts) {
  6008. var r = {};
  6009. each(parts, function (part) {
  6010. asNamedPart(part).each(function (np) {
  6011. var g = doGenerateOne(owner, np.pname);
  6012. r[np.name] = function (config) {
  6013. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  6014. return __assign(__assign({}, g), {
  6015. config: config,
  6016. validated: validated
  6017. });
  6018. };
  6019. });
  6020. });
  6021. return r;
  6022. };
  6023. var doGenerateOne = function (owner, pname) {
  6024. return {
  6025. uiType: placeholder(),
  6026. owner: owner,
  6027. name: pname
  6028. };
  6029. };
  6030. var generateOne = function (owner, pname, config) {
  6031. return {
  6032. uiType: placeholder(),
  6033. owner: owner,
  6034. name: pname,
  6035. config: config,
  6036. validated: {}
  6037. };
  6038. };
  6039. var schemas = function (parts) {
  6040. return bind(parts, function (part) {
  6041. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  6042. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  6043. }).toArray();
  6044. });
  6045. };
  6046. var names = function (parts) {
  6047. return map(parts, name$1);
  6048. };
  6049. var substitutes = function (owner, detail, parts) {
  6050. return subs(owner, detail, parts);
  6051. };
  6052. var components = function (owner, detail, internals) {
  6053. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  6054. };
  6055. var getPart = function (component, detail, partKey) {
  6056. var uid = detail.partUids[partKey];
  6057. return component.getSystem().getByUid(uid).toOptional();
  6058. };
  6059. var getPartOrDie = function (component, detail, partKey) {
  6060. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  6061. };
  6062. var getParts = function (component, detail, partKeys) {
  6063. var r = {};
  6064. var uids = detail.partUids;
  6065. var system = component.getSystem();
  6066. each(partKeys, function (pk) {
  6067. r[pk] = constant(system.getByUid(uids[pk]));
  6068. });
  6069. return r;
  6070. };
  6071. var getAllParts = function (component, detail) {
  6072. var system = component.getSystem();
  6073. return map$2(detail.partUids, function (pUid, _k) {
  6074. return constant(system.getByUid(pUid));
  6075. });
  6076. };
  6077. var getAllPartNames = function (detail) {
  6078. return keys(detail.partUids);
  6079. };
  6080. var getPartsOrDie = function (component, detail, partKeys) {
  6081. var r = {};
  6082. var uids = detail.partUids;
  6083. var system = component.getSystem();
  6084. each(partKeys, function (pk) {
  6085. r[pk] = constant(system.getByUid(uids[pk]).getOrDie());
  6086. });
  6087. return r;
  6088. };
  6089. var defaultUids = function (baseUid, partTypes) {
  6090. var partNames = names(partTypes);
  6091. return wrapAll$1(map(partNames, function (pn) {
  6092. return {
  6093. key: pn,
  6094. value: baseUid + '-' + pn
  6095. };
  6096. }));
  6097. };
  6098. var defaultUidsSchema = function (partTypes) {
  6099. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  6100. return defaultUids(spec.uid, partTypes);
  6101. }), anyValue$1());
  6102. };
  6103. var AlloyParts = /*#__PURE__*/Object.freeze({
  6104. __proto__: null,
  6105. generate: generate$4,
  6106. generateOne: generateOne,
  6107. schemas: schemas,
  6108. names: names,
  6109. substitutes: substitutes,
  6110. components: components,
  6111. defaultUids: defaultUids,
  6112. defaultUidsSchema: defaultUidsSchema,
  6113. getAllParts: getAllParts,
  6114. getAllPartNames: getAllPartNames,
  6115. getPart: getPart,
  6116. getPartOrDie: getPartOrDie,
  6117. getParts: getParts,
  6118. getPartsOrDie: getPartsOrDie
  6119. });
  6120. var base = function (partSchemas, partUidsSchemas) {
  6121. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  6122. return ps.concat([
  6123. strict$1('uid'),
  6124. defaulted$1('dom', {}),
  6125. defaulted$1('components', []),
  6126. snapshot('originalSpec'),
  6127. defaulted$1('debug.sketcher', {})
  6128. ]).concat(partUidsSchemas);
  6129. };
  6130. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6131. var baseS = base(partSchemas, partUidsSchemas);
  6132. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6133. };
  6134. var single$1 = function (owner, schema, factory, spec) {
  6135. var specWithUid = supplyUid(spec);
  6136. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  6137. return factory(detail, specWithUid);
  6138. };
  6139. var composite = function (owner, schema, partTypes, factory, spec) {
  6140. var specWithUid = supplyUid(spec);
  6141. var partSchemas = schemas(partTypes);
  6142. var partUidsSchema = defaultUidsSchema(partTypes);
  6143. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6144. var subs = substitutes(owner, detail, partTypes);
  6145. var components$1 = components(owner, detail, subs.internals());
  6146. return factory(detail, components$1, specWithUid, subs.externals());
  6147. };
  6148. var hasUid = function (spec) {
  6149. return has(spec, 'uid');
  6150. };
  6151. var supplyUid = function (spec) {
  6152. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  6153. };
  6154. function isSketchSpec(spec) {
  6155. return spec.uid !== undefined;
  6156. }
  6157. var singleSchema = objOfOnly([
  6158. strict$1('name'),
  6159. strict$1('factory'),
  6160. strict$1('configFields'),
  6161. defaulted$1('apis', {}),
  6162. defaulted$1('extraApis', {})
  6163. ]);
  6164. var compositeSchema = objOfOnly([
  6165. strict$1('name'),
  6166. strict$1('factory'),
  6167. strict$1('configFields'),
  6168. strict$1('partFields'),
  6169. defaulted$1('apis', {}),
  6170. defaulted$1('extraApis', {})
  6171. ]);
  6172. var single$2 = function (rawConfig) {
  6173. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6174. var sketch = function (spec) {
  6175. return single$1(config.name, config.configFields, config.factory, spec);
  6176. };
  6177. var apis = map$2(config.apis, makeApi);
  6178. var extraApis = map$2(config.extraApis, function (f, k) {
  6179. return markAsExtraApi(f, k);
  6180. });
  6181. return __assign(__assign({
  6182. name: config.name,
  6183. configFields: config.configFields,
  6184. sketch: sketch
  6185. }, apis), extraApis);
  6186. };
  6187. var composite$1 = function (rawConfig) {
  6188. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6189. var sketch = function (spec) {
  6190. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  6191. };
  6192. var parts = generate$4(config.name, config.partFields);
  6193. var apis = map$2(config.apis, makeApi);
  6194. var extraApis = map$2(config.extraApis, function (f, k) {
  6195. return markAsExtraApi(f, k);
  6196. });
  6197. return __assign(__assign({
  6198. name: config.name,
  6199. partFields: config.partFields,
  6200. configFields: config.configFields,
  6201. sketch: sketch,
  6202. parts: parts
  6203. }, apis), extraApis);
  6204. };
  6205. var cat = function (arr) {
  6206. var r = [];
  6207. var push = function (x) {
  6208. r.push(x);
  6209. };
  6210. for (var i = 0; i < arr.length; i++) {
  6211. arr[i].each(push);
  6212. }
  6213. return r;
  6214. };
  6215. var sequence = function (arr) {
  6216. var r = [];
  6217. for (var i = 0; i < arr.length; i++) {
  6218. var x = arr[i];
  6219. if (x.isSome()) {
  6220. r.push(x.getOrDie());
  6221. } else {
  6222. return Optional.none();
  6223. }
  6224. }
  6225. return Optional.some(r);
  6226. };
  6227. var lift2 = function (oa, ob, f) {
  6228. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  6229. };
  6230. var lift3 = function (oa, ob, oc, f) {
  6231. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  6232. };
  6233. var mapFrom = function (a, f) {
  6234. return a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none();
  6235. };
  6236. var someIf = function (b, a) {
  6237. return b ? Optional.some(a) : Optional.none();
  6238. };
  6239. var inside = function (target) {
  6240. return name(target) === 'input' && get$2(target, 'type') !== 'radio' || name(target) === 'textarea';
  6241. };
  6242. var getCurrent = function (component, composeConfig, _composeState) {
  6243. return composeConfig.find(component);
  6244. };
  6245. var ComposeApis = /*#__PURE__*/Object.freeze({
  6246. __proto__: null,
  6247. getCurrent: getCurrent
  6248. });
  6249. var ComposeSchema = [strict$1('find')];
  6250. var Composing = create$1({
  6251. fields: ComposeSchema,
  6252. name: 'composing',
  6253. apis: ComposeApis
  6254. });
  6255. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6256. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  6257. each(highlighted, function (h) {
  6258. if (!exists(skip, function (skipComp) {
  6259. return skipComp.element === h;
  6260. })) {
  6261. remove$4(h, hConfig.highlightClass);
  6262. component.getSystem().getByDom(h).each(function (target) {
  6263. hConfig.onDehighlight(component, target);
  6264. emit(target, dehighlight());
  6265. });
  6266. }
  6267. });
  6268. };
  6269. var dehighlightAll = function (component, hConfig, hState) {
  6270. return dehighlightAllExcept(component, hConfig, hState, []);
  6271. };
  6272. var dehighlight$1 = function (component, hConfig, hState, target) {
  6273. if (isHighlighted(component, hConfig, hState, target)) {
  6274. remove$4(target.element, hConfig.highlightClass);
  6275. hConfig.onDehighlight(component, target);
  6276. emit(target, dehighlight());
  6277. }
  6278. };
  6279. var highlight$1 = function (component, hConfig, hState, target) {
  6280. dehighlightAllExcept(component, hConfig, hState, [target]);
  6281. if (!isHighlighted(component, hConfig, hState, target)) {
  6282. add$2(target.element, hConfig.highlightClass);
  6283. hConfig.onHighlight(component, target);
  6284. emit(target, highlight());
  6285. }
  6286. };
  6287. var highlightFirst = function (component, hConfig, hState) {
  6288. getFirst(component, hConfig).each(function (firstComp) {
  6289. highlight$1(component, hConfig, hState, firstComp);
  6290. });
  6291. };
  6292. var highlightLast = function (component, hConfig, hState) {
  6293. getLast(component, hConfig).each(function (lastComp) {
  6294. highlight$1(component, hConfig, hState, lastComp);
  6295. });
  6296. };
  6297. var highlightAt = function (component, hConfig, hState, index) {
  6298. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6299. throw new Error(err);
  6300. }, function (firstComp) {
  6301. highlight$1(component, hConfig, hState, firstComp);
  6302. });
  6303. };
  6304. var highlightBy = function (component, hConfig, hState, predicate) {
  6305. var candidates = getCandidates(component, hConfig);
  6306. var targetComp = find(candidates, predicate);
  6307. targetComp.each(function (c) {
  6308. highlight$1(component, hConfig, hState, c);
  6309. });
  6310. };
  6311. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6312. return has$2(queryTarget.element, hConfig.highlightClass);
  6313. };
  6314. var getHighlighted = function (component, hConfig, _hState) {
  6315. return descendant$1(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  6316. return component.getSystem().getByDom(e).toOptional();
  6317. });
  6318. };
  6319. var getByIndex = function (component, hConfig, hState, index) {
  6320. var items = descendants(component.element, '.' + hConfig.itemClass);
  6321. return Optional.from(items[index]).fold(function () {
  6322. return Result.error('No element found with index ' + index);
  6323. }, component.getSystem().getByDom);
  6324. };
  6325. var getFirst = function (component, hConfig, _hState) {
  6326. return descendant$1(component.element, '.' + hConfig.itemClass).bind(function (e) {
  6327. return component.getSystem().getByDom(e).toOptional();
  6328. });
  6329. };
  6330. var getLast = function (component, hConfig, _hState) {
  6331. var items = descendants(component.element, '.' + hConfig.itemClass);
  6332. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  6333. return last.bind(function (c) {
  6334. return component.getSystem().getByDom(c).toOptional();
  6335. });
  6336. };
  6337. var getDelta = function (component, hConfig, hState, delta) {
  6338. var items = descendants(component.element, '.' + hConfig.itemClass);
  6339. var current = findIndex(items, function (item) {
  6340. return has$2(item, hConfig.highlightClass);
  6341. });
  6342. return current.bind(function (selected) {
  6343. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6344. return component.getSystem().getByDom(items[dest]).toOptional();
  6345. });
  6346. };
  6347. var getPrevious = function (component, hConfig, hState) {
  6348. return getDelta(component, hConfig, hState, -1);
  6349. };
  6350. var getNext = function (component, hConfig, hState) {
  6351. return getDelta(component, hConfig, hState, +1);
  6352. };
  6353. var getCandidates = function (component, hConfig, _hState) {
  6354. var items = descendants(component.element, '.' + hConfig.itemClass);
  6355. return cat(map(items, function (i) {
  6356. return component.getSystem().getByDom(i).toOptional();
  6357. }));
  6358. };
  6359. var HighlightApis = /*#__PURE__*/Object.freeze({
  6360. __proto__: null,
  6361. dehighlightAll: dehighlightAll,
  6362. dehighlight: dehighlight$1,
  6363. highlight: highlight$1,
  6364. highlightFirst: highlightFirst,
  6365. highlightLast: highlightLast,
  6366. highlightAt: highlightAt,
  6367. highlightBy: highlightBy,
  6368. isHighlighted: isHighlighted,
  6369. getHighlighted: getHighlighted,
  6370. getFirst: getFirst,
  6371. getLast: getLast,
  6372. getPrevious: getPrevious,
  6373. getNext: getNext,
  6374. getCandidates: getCandidates
  6375. });
  6376. var HighlightSchema = [
  6377. strict$1('highlightClass'),
  6378. strict$1('itemClass'),
  6379. onHandler('onHighlight'),
  6380. onHandler('onDehighlight')
  6381. ];
  6382. var Highlighting = create$1({
  6383. fields: HighlightSchema,
  6384. name: 'highlighting',
  6385. apis: HighlightApis
  6386. });
  6387. var BACKSPACE = [8];
  6388. var TAB = [9];
  6389. var ENTER = [13];
  6390. var ESCAPE = [27];
  6391. var SPACE = [32];
  6392. var LEFT = [37];
  6393. var UP = [38];
  6394. var RIGHT = [39];
  6395. var DOWN = [40];
  6396. var cyclePrev = function (values, index, predicate) {
  6397. var before = reverse(values.slice(0, index));
  6398. var after = reverse(values.slice(index + 1));
  6399. return find(before.concat(after), predicate);
  6400. };
  6401. var tryPrev = function (values, index, predicate) {
  6402. var before = reverse(values.slice(0, index));
  6403. return find(before, predicate);
  6404. };
  6405. var cycleNext = function (values, index, predicate) {
  6406. var before = values.slice(0, index);
  6407. var after = values.slice(index + 1);
  6408. return find(after.concat(before), predicate);
  6409. };
  6410. var tryNext = function (values, index, predicate) {
  6411. var after = values.slice(index + 1);
  6412. return find(after, predicate);
  6413. };
  6414. var inSet = function (keys) {
  6415. return function (event) {
  6416. var raw = event.raw;
  6417. return contains(keys, raw.which);
  6418. };
  6419. };
  6420. var and = function (preds) {
  6421. return function (event) {
  6422. return forall(preds, function (pred) {
  6423. return pred(event);
  6424. });
  6425. };
  6426. };
  6427. var isShift = function (event) {
  6428. var raw = event.raw;
  6429. return raw.shiftKey === true;
  6430. };
  6431. var isControl = function (event) {
  6432. var raw = event.raw;
  6433. return raw.ctrlKey === true;
  6434. };
  6435. var isNotShift = not(isShift);
  6436. var rule = function (matches, action) {
  6437. return {
  6438. matches: matches,
  6439. classification: action
  6440. };
  6441. };
  6442. var choose$2 = function (transitions, event) {
  6443. var transition = find(transitions, function (t) {
  6444. return t.matches(event);
  6445. });
  6446. return transition.map(function (t) {
  6447. return t.classification;
  6448. });
  6449. };
  6450. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6451. var noChange = prevFocus.exists(function (p) {
  6452. return newFocus.exists(function (n) {
  6453. return eq$1(n, p);
  6454. });
  6455. });
  6456. if (!noChange) {
  6457. emitWith(component, focusShifted(), {
  6458. prevFocus: prevFocus,
  6459. newFocus: newFocus
  6460. });
  6461. }
  6462. };
  6463. var dom = function () {
  6464. var get = function (component) {
  6465. return search(component.element);
  6466. };
  6467. var set = function (component, focusee) {
  6468. var prevFocus = get(component);
  6469. component.getSystem().triggerFocus(focusee, component.element);
  6470. var newFocus = get(component);
  6471. reportFocusShifting(component, prevFocus, newFocus);
  6472. };
  6473. return {
  6474. get: get,
  6475. set: set
  6476. };
  6477. };
  6478. var highlights = function () {
  6479. var get = function (component) {
  6480. return Highlighting.getHighlighted(component).map(function (item) {
  6481. return item.element;
  6482. });
  6483. };
  6484. var set = function (component, element) {
  6485. var prevFocus = get(component);
  6486. component.getSystem().getByDom(element).fold(noop, function (item) {
  6487. Highlighting.highlight(component, item);
  6488. });
  6489. var newFocus = get(component);
  6490. reportFocusShifting(component, prevFocus, newFocus);
  6491. };
  6492. return {
  6493. get: get,
  6494. set: set
  6495. };
  6496. };
  6497. var FocusInsideModes;
  6498. (function (FocusInsideModes) {
  6499. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6500. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6501. FocusInsideModes['OnApiMode'] = 'onApi';
  6502. }(FocusInsideModes || (FocusInsideModes = {})));
  6503. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6504. var schema = function () {
  6505. return infoSchema.concat([
  6506. defaulted$1('focusManager', dom()),
  6507. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6508. return contains([
  6509. 'onFocus',
  6510. 'onEnterOrSpace',
  6511. 'onApi'
  6512. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6513. })),
  6514. output('handler', me),
  6515. output('state', stateInit),
  6516. output('sendFocusIn', optFocusIn)
  6517. ]);
  6518. };
  6519. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6520. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6521. return choose$2(rules, simulatedEvent.event).bind(function (rule) {
  6522. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6523. });
  6524. };
  6525. var toEvents = function (keyingConfig, keyingState) {
  6526. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6527. return run(focus(), function (component, simulatedEvent) {
  6528. focusIn(component, keyingConfig, keyingState);
  6529. simulatedEvent.stop();
  6530. });
  6531. });
  6532. var tryGoInsideComponent = function (component, simulatedEvent) {
  6533. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  6534. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6535. optFocusIn(keyingConfig).each(function (focusIn) {
  6536. focusIn(component, keyingConfig, keyingState);
  6537. simulatedEvent.stop();
  6538. });
  6539. }
  6540. };
  6541. var keyboardEvents = [
  6542. run(keydown(), function (component, simulatedEvent) {
  6543. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6544. tryGoInsideComponent(component, simulatedEvent);
  6545. }, function (_) {
  6546. simulatedEvent.stop();
  6547. });
  6548. }),
  6549. run(keyup(), function (component, simulatedEvent) {
  6550. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6551. simulatedEvent.stop();
  6552. });
  6553. })
  6554. ];
  6555. return derive(onFocusHandler.toArray().concat(keyboardEvents));
  6556. };
  6557. var me = {
  6558. schema: schema,
  6559. processKey: processKey,
  6560. toEvents: toEvents
  6561. };
  6562. return me;
  6563. };
  6564. var create$3 = function (cyclicField) {
  6565. var schema = [
  6566. option('onEscape'),
  6567. option('onEnter'),
  6568. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6569. defaulted$1('firstTabstop', 0),
  6570. defaulted$1('useTabstopAt', always),
  6571. option('visibilitySelector')
  6572. ].concat([cyclicField]);
  6573. var isVisible = function (tabbingConfig, element) {
  6574. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6575. return closest$3(element, sel);
  6576. }).getOr(element);
  6577. return get$6(target) > 0;
  6578. };
  6579. var findInitial = function (component, tabbingConfig) {
  6580. var tabstops = descendants(component.element, tabbingConfig.selector);
  6581. var visibles = filter(tabstops, function (elem) {
  6582. return isVisible(tabbingConfig, elem);
  6583. });
  6584. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  6585. };
  6586. var findCurrent = function (component, tabbingConfig) {
  6587. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  6588. return closest$3(elem, tabbingConfig.selector);
  6589. });
  6590. };
  6591. var isTabstop = function (tabbingConfig, element) {
  6592. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  6593. };
  6594. var focusIn = function (component, tabbingConfig, _tabbingState) {
  6595. findInitial(component, tabbingConfig).each(function (target) {
  6596. tabbingConfig.focusManager.set(component, target);
  6597. });
  6598. };
  6599. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  6600. return cycle(tabstops, stopIndex, function (elem) {
  6601. return isTabstop(tabbingConfig, elem);
  6602. }).fold(function () {
  6603. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  6604. }, function (target) {
  6605. tabbingConfig.focusManager.set(component, target);
  6606. return Optional.some(true);
  6607. });
  6608. };
  6609. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  6610. var tabstops = descendants(component.element, tabbingConfig.selector);
  6611. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  6612. var optStopIndex = findIndex(tabstops, curry(eq$1, tabstop));
  6613. return optStopIndex.bind(function (stopIndex) {
  6614. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  6615. });
  6616. });
  6617. };
  6618. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  6619. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  6620. return go(component, simulatedEvent, tabbingConfig, navigate);
  6621. };
  6622. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  6623. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  6624. return go(component, simulatedEvent, tabbingConfig, navigate);
  6625. };
  6626. var execute = function (component, simulatedEvent, tabbingConfig) {
  6627. return tabbingConfig.onEnter.bind(function (f) {
  6628. return f(component, simulatedEvent);
  6629. });
  6630. };
  6631. var exit = function (component, simulatedEvent, tabbingConfig) {
  6632. return tabbingConfig.onEscape.bind(function (f) {
  6633. return f(component, simulatedEvent);
  6634. });
  6635. };
  6636. var getKeydownRules = constant([
  6637. rule(and([
  6638. isShift,
  6639. inSet(TAB)
  6640. ]), goBackwards),
  6641. rule(inSet(TAB), goForwards),
  6642. rule(inSet(ESCAPE), exit),
  6643. rule(and([
  6644. isNotShift,
  6645. inSet(ENTER)
  6646. ]), execute)
  6647. ]);
  6648. var getKeyupRules = constant([]);
  6649. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  6650. return Optional.some(focusIn);
  6651. });
  6652. };
  6653. var AcyclicType = create$3(state$1('cyclic', never));
  6654. var CyclicType = create$3(state$1('cyclic', always));
  6655. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  6656. dispatch(component, focused, execute());
  6657. return Optional.some(true);
  6658. };
  6659. var defaultExecute = function (component, simulatedEvent, focused) {
  6660. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  6661. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  6662. };
  6663. var stopEventForFirefox = function (_component, _simulatedEvent) {
  6664. return Optional.some(true);
  6665. };
  6666. var schema$4 = [
  6667. defaulted$1('execute', defaultExecute),
  6668. defaulted$1('useSpace', false),
  6669. defaulted$1('useEnter', true),
  6670. defaulted$1('useControlEnter', false),
  6671. defaulted$1('useDown', false)
  6672. ];
  6673. var execute$1 = function (component, simulatedEvent, executeConfig) {
  6674. return executeConfig.execute(component, simulatedEvent, component.element);
  6675. };
  6676. var getKeydownRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  6677. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  6678. var enterExec = executeConfig.useEnter ? ENTER : [];
  6679. var downExec = executeConfig.useDown ? DOWN : [];
  6680. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  6681. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  6682. isControl,
  6683. inSet(ENTER)
  6684. ]), execute$1)] : []);
  6685. };
  6686. var getKeyupRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  6687. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  6688. };
  6689. var ExecutionType = typical(schema$4, NoState.init, getKeydownRules, getKeyupRules, function () {
  6690. return Optional.none();
  6691. });
  6692. var flatgrid = function () {
  6693. var dimensions = Cell(Optional.none());
  6694. var setGridSize = function (numRows, numColumns) {
  6695. dimensions.set(Optional.some({
  6696. numRows: numRows,
  6697. numColumns: numColumns
  6698. }));
  6699. };
  6700. var getNumRows = function () {
  6701. return dimensions.get().map(function (d) {
  6702. return d.numRows;
  6703. });
  6704. };
  6705. var getNumColumns = function () {
  6706. return dimensions.get().map(function (d) {
  6707. return d.numColumns;
  6708. });
  6709. };
  6710. return nu$5({
  6711. readState: function () {
  6712. return dimensions.get().map(function (d) {
  6713. return {
  6714. numRows: String(d.numRows),
  6715. numColumns: String(d.numColumns)
  6716. };
  6717. }).getOr({
  6718. numRows: '?',
  6719. numColumns: '?'
  6720. });
  6721. },
  6722. setGridSize: setGridSize,
  6723. getNumRows: getNumRows,
  6724. getNumColumns: getNumColumns
  6725. });
  6726. };
  6727. var init$2 = function (spec) {
  6728. return spec.state(spec);
  6729. };
  6730. var KeyingState = /*#__PURE__*/Object.freeze({
  6731. __proto__: null,
  6732. flatgrid: flatgrid,
  6733. init: init$2
  6734. });
  6735. var useH = function (movement) {
  6736. return function (component, simulatedEvent, config, state) {
  6737. var move = movement(component.element);
  6738. return use(move, component, simulatedEvent, config, state);
  6739. };
  6740. };
  6741. var west$2 = function (moveLeft, moveRight) {
  6742. var movement = onDirection(moveLeft, moveRight);
  6743. return useH(movement);
  6744. };
  6745. var east$2 = function (moveLeft, moveRight) {
  6746. var movement = onDirection(moveRight, moveLeft);
  6747. return useH(movement);
  6748. };
  6749. var useV = function (move) {
  6750. return function (component, simulatedEvent, config, state) {
  6751. return use(move, component, simulatedEvent, config, state);
  6752. };
  6753. };
  6754. var use = function (move, component, simulatedEvent, config, state) {
  6755. var outcome = config.focusManager.get(component).bind(function (focused) {
  6756. return move(component.element, focused, config, state);
  6757. });
  6758. return outcome.map(function (newFocus) {
  6759. config.focusManager.set(component, newFocus);
  6760. return true;
  6761. });
  6762. };
  6763. var north$2 = useV;
  6764. var south$2 = useV;
  6765. var move = useV;
  6766. var isHidden = function (dom) {
  6767. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  6768. };
  6769. var isVisible = function (element) {
  6770. return !isHidden(element.dom);
  6771. };
  6772. var locate = function (candidates, predicate) {
  6773. return findIndex(candidates, predicate).map(function (index) {
  6774. return {
  6775. index: index,
  6776. candidates: candidates
  6777. };
  6778. });
  6779. };
  6780. var locateVisible = function (container, current, selector) {
  6781. var predicate = function (x) {
  6782. return eq$1(x, current);
  6783. };
  6784. var candidates = descendants(container, selector);
  6785. var visible = filter(candidates, isVisible);
  6786. return locate(visible, predicate);
  6787. };
  6788. var findIndex$1 = function (elements, target) {
  6789. return findIndex(elements, function (elem) {
  6790. return eq$1(target, elem);
  6791. });
  6792. };
  6793. var withGrid = function (values, index, numCols, f) {
  6794. var oldRow = Math.floor(index / numCols);
  6795. var oldColumn = index % numCols;
  6796. return f(oldRow, oldColumn).bind(function (address) {
  6797. var newIndex = address.row * numCols + address.column;
  6798. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  6799. });
  6800. };
  6801. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  6802. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6803. var onLastRow = oldRow === numRows - 1;
  6804. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  6805. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  6806. return Optional.some({
  6807. row: oldRow,
  6808. column: newColumn
  6809. });
  6810. });
  6811. };
  6812. var cycleVertical = function (values, index, numRows, numCols, delta) {
  6813. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6814. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  6815. var onLastRow = newRow === numRows - 1;
  6816. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  6817. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  6818. return Optional.some({
  6819. row: newRow,
  6820. column: newCol
  6821. });
  6822. });
  6823. };
  6824. var cycleRight = function (values, index, numRows, numCols) {
  6825. return cycleHorizontal(values, index, numRows, numCols, +1);
  6826. };
  6827. var cycleLeft = function (values, index, numRows, numCols) {
  6828. return cycleHorizontal(values, index, numRows, numCols, -1);
  6829. };
  6830. var cycleUp = function (values, index, numRows, numCols) {
  6831. return cycleVertical(values, index, numRows, numCols, -1);
  6832. };
  6833. var cycleDown = function (values, index, numRows, numCols) {
  6834. return cycleVertical(values, index, numRows, numCols, +1);
  6835. };
  6836. var schema$5 = [
  6837. strict$1('selector'),
  6838. defaulted$1('execute', defaultExecute),
  6839. onKeyboardHandler('onEscape'),
  6840. defaulted$1('captureTab', false),
  6841. initSize()
  6842. ];
  6843. var focusIn = function (component, gridConfig, _gridState) {
  6844. descendant$1(component.element, gridConfig.selector).each(function (first) {
  6845. gridConfig.focusManager.set(component, first);
  6846. });
  6847. };
  6848. var findCurrent = function (component, gridConfig) {
  6849. return gridConfig.focusManager.get(component).bind(function (elem) {
  6850. return closest$3(elem, gridConfig.selector);
  6851. });
  6852. };
  6853. var execute$2 = function (component, simulatedEvent, gridConfig, _gridState) {
  6854. return findCurrent(component, gridConfig).bind(function (focused) {
  6855. return gridConfig.execute(component, simulatedEvent, focused);
  6856. });
  6857. };
  6858. var doMove = function (cycle) {
  6859. return function (element, focused, gridConfig, gridState) {
  6860. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  6861. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  6862. });
  6863. };
  6864. };
  6865. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  6866. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  6867. };
  6868. var doEscape = function (component, simulatedEvent, gridConfig) {
  6869. return gridConfig.onEscape(component, simulatedEvent);
  6870. };
  6871. var moveLeft = doMove(cycleLeft);
  6872. var moveRight = doMove(cycleRight);
  6873. var moveNorth = doMove(cycleUp);
  6874. var moveSouth = doMove(cycleDown);
  6875. var getKeydownRules$1 = constant([
  6876. rule(inSet(LEFT), west$2(moveLeft, moveRight)),
  6877. rule(inSet(RIGHT), east$2(moveLeft, moveRight)),
  6878. rule(inSet(UP), north$2(moveNorth)),
  6879. rule(inSet(DOWN), south$2(moveSouth)),
  6880. rule(and([
  6881. isShift,
  6882. inSet(TAB)
  6883. ]), handleTab),
  6884. rule(and([
  6885. isNotShift,
  6886. inSet(TAB)
  6887. ]), handleTab),
  6888. rule(inSet(ESCAPE), doEscape),
  6889. rule(inSet(SPACE.concat(ENTER)), execute$2)
  6890. ]);
  6891. var getKeyupRules$1 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  6892. var FlatgridType = typical(schema$5, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  6893. return Optional.some(focusIn);
  6894. });
  6895. var horizontal = function (container, selector, current, delta) {
  6896. var isDisabledButton = function (candidate) {
  6897. return name(candidate) === 'button' && get$2(candidate, 'disabled') === 'disabled';
  6898. };
  6899. var tryCycle = function (initial, index, candidates) {
  6900. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  6901. if (newIndex === initial) {
  6902. return Optional.none();
  6903. } else {
  6904. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  6905. }
  6906. };
  6907. return locateVisible(container, current, selector).bind(function (identified) {
  6908. var index = identified.index;
  6909. var candidates = identified.candidates;
  6910. return tryCycle(index, index, candidates);
  6911. });
  6912. };
  6913. var schema$6 = [
  6914. strict$1('selector'),
  6915. defaulted$1('getInitial', Optional.none),
  6916. defaulted$1('execute', defaultExecute),
  6917. onKeyboardHandler('onEscape'),
  6918. defaulted$1('executeOnMove', false),
  6919. defaulted$1('allowVertical', true)
  6920. ];
  6921. var findCurrent$1 = function (component, flowConfig) {
  6922. return flowConfig.focusManager.get(component).bind(function (elem) {
  6923. return closest$3(elem, flowConfig.selector);
  6924. });
  6925. };
  6926. var execute$3 = function (component, simulatedEvent, flowConfig) {
  6927. return findCurrent$1(component, flowConfig).bind(function (focused) {
  6928. return flowConfig.execute(component, simulatedEvent, focused);
  6929. });
  6930. };
  6931. var focusIn$1 = function (component, flowConfig, _state) {
  6932. flowConfig.getInitial(component).orThunk(function () {
  6933. return descendant$1(component.element, flowConfig.selector);
  6934. }).each(function (first) {
  6935. flowConfig.focusManager.set(component, first);
  6936. });
  6937. };
  6938. var moveLeft$1 = function (element, focused, info) {
  6939. return horizontal(element, info.selector, focused, -1);
  6940. };
  6941. var moveRight$1 = function (element, focused, info) {
  6942. return horizontal(element, info.selector, focused, +1);
  6943. };
  6944. var doMove$1 = function (movement) {
  6945. return function (component, simulatedEvent, flowConfig, flowState) {
  6946. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  6947. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Optional.some(true);
  6948. });
  6949. };
  6950. };
  6951. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  6952. return flowConfig.onEscape(component, simulatedEvent);
  6953. };
  6954. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  6955. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  6956. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  6957. return [
  6958. rule(inSet(westMovers), doMove$1(west$2(moveLeft$1, moveRight$1))),
  6959. rule(inSet(eastMovers), doMove$1(east$2(moveLeft$1, moveRight$1))),
  6960. rule(inSet(ENTER), execute$3),
  6961. rule(inSet(SPACE), execute$3),
  6962. rule(inSet(ESCAPE), doEscape$1)
  6963. ];
  6964. };
  6965. var getKeyupRules$2 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  6966. var FlowType = typical(schema$6, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  6967. return Optional.some(focusIn$1);
  6968. });
  6969. var toCell = function (matrix, rowIndex, columnIndex) {
  6970. return Optional.from(matrix[rowIndex]).bind(function (row) {
  6971. return Optional.from(row[columnIndex]).map(function (cell) {
  6972. return {
  6973. rowIndex: rowIndex,
  6974. columnIndex: columnIndex,
  6975. cell: cell
  6976. };
  6977. });
  6978. });
  6979. };
  6980. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  6981. var row = matrix[rowIndex];
  6982. var colsInRow = row.length;
  6983. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  6984. return toCell(matrix, rowIndex, newColIndex);
  6985. };
  6986. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  6987. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  6988. var colsInNextRow = matrix[nextRowIndex].length;
  6989. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6990. return toCell(matrix, nextRowIndex, nextColIndex);
  6991. };
  6992. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  6993. var row = matrix[rowIndex];
  6994. var colsInRow = row.length;
  6995. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  6996. return toCell(matrix, rowIndex, newColIndex);
  6997. };
  6998. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  6999. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  7000. var colsInNextRow = matrix[nextRowIndex].length;
  7001. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  7002. return toCell(matrix, nextRowIndex, nextColIndex);
  7003. };
  7004. var cycleRight$1 = function (matrix, startRow, startCol) {
  7005. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  7006. };
  7007. var cycleLeft$1 = function (matrix, startRow, startCol) {
  7008. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  7009. };
  7010. var cycleUp$1 = function (matrix, startRow, startCol) {
  7011. return cycleVertical$1(matrix, startCol, startRow, -1);
  7012. };
  7013. var cycleDown$1 = function (matrix, startRow, startCol) {
  7014. return cycleVertical$1(matrix, startCol, startRow, +1);
  7015. };
  7016. var moveLeft$2 = function (matrix, startRow, startCol) {
  7017. return moveHorizontal(matrix, startRow, startCol, -1);
  7018. };
  7019. var moveRight$2 = function (matrix, startRow, startCol) {
  7020. return moveHorizontal(matrix, startRow, startCol, +1);
  7021. };
  7022. var moveUp = function (matrix, startRow, startCol) {
  7023. return moveVertical(matrix, startCol, startRow, -1);
  7024. };
  7025. var moveDown = function (matrix, startRow, startCol) {
  7026. return moveVertical(matrix, startCol, startRow, +1);
  7027. };
  7028. var schema$7 = [
  7029. strictObjOf('selectors', [
  7030. strict$1('row'),
  7031. strict$1('cell')
  7032. ]),
  7033. defaulted$1('cycles', true),
  7034. defaulted$1('previousSelector', Optional.none),
  7035. defaulted$1('execute', defaultExecute)
  7036. ];
  7037. var focusIn$2 = function (component, matrixConfig, _state) {
  7038. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  7039. var selectors = matrixConfig.selectors;
  7040. return descendant$1(component.element, selectors.cell);
  7041. });
  7042. focused.each(function (cell) {
  7043. matrixConfig.focusManager.set(component, cell);
  7044. });
  7045. };
  7046. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  7047. return search(component.element).bind(function (focused) {
  7048. return matrixConfig.execute(component, simulatedEvent, focused);
  7049. });
  7050. };
  7051. var toMatrix = function (rows, matrixConfig) {
  7052. return map(rows, function (row) {
  7053. return descendants(row, matrixConfig.selectors.cell);
  7054. });
  7055. };
  7056. var doMove$2 = function (ifCycle, ifMove) {
  7057. return function (element, focused, matrixConfig) {
  7058. var move = matrixConfig.cycles ? ifCycle : ifMove;
  7059. return closest$3(focused, matrixConfig.selectors.row).bind(function (inRow) {
  7060. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  7061. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  7062. var allRows = descendants(element, matrixConfig.selectors.row);
  7063. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  7064. var matrix = toMatrix(allRows, matrixConfig);
  7065. return move(matrix, rowIndex, colIndex).map(function (next) {
  7066. return next.cell;
  7067. });
  7068. });
  7069. });
  7070. });
  7071. };
  7072. };
  7073. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  7074. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  7075. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  7076. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  7077. var getKeydownRules$3 = constant([
  7078. rule(inSet(LEFT), west$2(moveLeft$3, moveRight$3)),
  7079. rule(inSet(RIGHT), east$2(moveLeft$3, moveRight$3)),
  7080. rule(inSet(UP), north$2(moveNorth$1)),
  7081. rule(inSet(DOWN), south$2(moveSouth$1)),
  7082. rule(inSet(SPACE.concat(ENTER)), execute$4)
  7083. ]);
  7084. var getKeyupRules$3 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  7085. var MatrixType = typical(schema$7, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7086. return Optional.some(focusIn$2);
  7087. });
  7088. var schema$8 = [
  7089. strict$1('selector'),
  7090. defaulted$1('execute', defaultExecute),
  7091. defaulted$1('moveOnTab', false)
  7092. ];
  7093. var execute$5 = function (component, simulatedEvent, menuConfig) {
  7094. return menuConfig.focusManager.get(component).bind(function (focused) {
  7095. return menuConfig.execute(component, simulatedEvent, focused);
  7096. });
  7097. };
  7098. var focusIn$3 = function (component, menuConfig, _state) {
  7099. descendant$1(component.element, menuConfig.selector).each(function (first) {
  7100. menuConfig.focusManager.set(component, first);
  7101. });
  7102. };
  7103. var moveUp$1 = function (element, focused, info) {
  7104. return horizontal(element, info.selector, focused, -1);
  7105. };
  7106. var moveDown$1 = function (element, focused, info) {
  7107. return horizontal(element, info.selector, focused, +1);
  7108. };
  7109. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7110. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7111. };
  7112. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7113. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7114. };
  7115. var getKeydownRules$4 = constant([
  7116. rule(inSet(UP), move(moveUp$1)),
  7117. rule(inSet(DOWN), move(moveDown$1)),
  7118. rule(and([
  7119. isShift,
  7120. inSet(TAB)
  7121. ]), fireShiftTab),
  7122. rule(and([
  7123. isNotShift,
  7124. inSet(TAB)
  7125. ]), fireTab),
  7126. rule(inSet(ENTER), execute$5),
  7127. rule(inSet(SPACE), execute$5)
  7128. ]);
  7129. var getKeyupRules$4 = constant([rule(inSet(SPACE), stopEventForFirefox)]);
  7130. var MenuType = typical(schema$8, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  7131. return Optional.some(focusIn$3);
  7132. });
  7133. var schema$9 = [
  7134. onKeyboardHandler('onSpace'),
  7135. onKeyboardHandler('onEnter'),
  7136. onKeyboardHandler('onShiftEnter'),
  7137. onKeyboardHandler('onLeft'),
  7138. onKeyboardHandler('onRight'),
  7139. onKeyboardHandler('onTab'),
  7140. onKeyboardHandler('onShiftTab'),
  7141. onKeyboardHandler('onUp'),
  7142. onKeyboardHandler('onDown'),
  7143. onKeyboardHandler('onEscape'),
  7144. defaulted$1('stopSpaceKeyup', false),
  7145. option('focusIn')
  7146. ];
  7147. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  7148. return [
  7149. rule(inSet(SPACE), specialInfo.onSpace),
  7150. rule(and([
  7151. isNotShift,
  7152. inSet(ENTER)
  7153. ]), specialInfo.onEnter),
  7154. rule(and([
  7155. isShift,
  7156. inSet(ENTER)
  7157. ]), specialInfo.onShiftEnter),
  7158. rule(and([
  7159. isShift,
  7160. inSet(TAB)
  7161. ]), specialInfo.onShiftTab),
  7162. rule(and([
  7163. isNotShift,
  7164. inSet(TAB)
  7165. ]), specialInfo.onTab),
  7166. rule(inSet(UP), specialInfo.onUp),
  7167. rule(inSet(DOWN), specialInfo.onDown),
  7168. rule(inSet(LEFT), specialInfo.onLeft),
  7169. rule(inSet(RIGHT), specialInfo.onRight),
  7170. rule(inSet(SPACE), specialInfo.onSpace),
  7171. rule(inSet(ESCAPE), specialInfo.onEscape)
  7172. ];
  7173. };
  7174. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  7175. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7176. };
  7177. var SpecialType = typical(schema$9, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  7178. return specialInfo.focusIn;
  7179. });
  7180. var acyclic = AcyclicType.schema();
  7181. var cyclic = CyclicType.schema();
  7182. var flow = FlowType.schema();
  7183. var flatgrid$1 = FlatgridType.schema();
  7184. var matrix = MatrixType.schema();
  7185. var execution = ExecutionType.schema();
  7186. var menu = MenuType.schema();
  7187. var special = SpecialType.schema();
  7188. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7189. __proto__: null,
  7190. acyclic: acyclic,
  7191. cyclic: cyclic,
  7192. flow: flow,
  7193. flatgrid: flatgrid$1,
  7194. matrix: matrix,
  7195. execution: execution,
  7196. menu: menu,
  7197. special: special
  7198. });
  7199. var isFlatgridState = function (keyState) {
  7200. return hasNonNullableKey(keyState, 'setGridSize');
  7201. };
  7202. var Keying = createModes$1({
  7203. branchKey: 'mode',
  7204. branches: KeyboardBranches,
  7205. name: 'keying',
  7206. active: {
  7207. events: function (keyingConfig, keyingState) {
  7208. var handler = keyingConfig.handler;
  7209. return handler.toEvents(keyingConfig, keyingState);
  7210. }
  7211. },
  7212. apis: {
  7213. focusIn: function (component, keyConfig, keyState) {
  7214. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7215. component.getSystem().triggerFocus(component.element, component.element);
  7216. }, function (sendFocusIn) {
  7217. sendFocusIn(component, keyConfig, keyState);
  7218. });
  7219. },
  7220. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7221. if (!isFlatgridState(keyState)) {
  7222. console.error('Layout does not support setGridSize');
  7223. } else {
  7224. keyState.setGridSize(numRows, numColumns);
  7225. }
  7226. }
  7227. },
  7228. state: KeyingState
  7229. });
  7230. var set$5 = function (component, replaceConfig, replaceState, data) {
  7231. preserve(function () {
  7232. var newChildren = map(data, component.getSystem().build);
  7233. replaceChildren(component, newChildren);
  7234. }, component.element);
  7235. };
  7236. var insert = function (component, replaceConfig, insertion, childSpec) {
  7237. var child = component.getSystem().build(childSpec);
  7238. attachWith(component, child, insertion);
  7239. };
  7240. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  7241. insert(component, replaceConfig, append, appendee);
  7242. };
  7243. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  7244. insert(component, replaceConfig, prepend, prependee);
  7245. };
  7246. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  7247. var children = contents(component);
  7248. var foundChild = find(children, function (child) {
  7249. return eq$1(removee.element, child.element);
  7250. });
  7251. foundChild.each(detach);
  7252. };
  7253. var contents = function (component, _replaceConfig) {
  7254. return component.components();
  7255. };
  7256. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7257. var children = contents(component);
  7258. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  7259. remove$7(component, replaceConfig, replaceState, replacee);
  7260. replacer.each(function (r) {
  7261. insert(component, replaceConfig, function (p, c) {
  7262. appendAt(p, c, replaceeIndex);
  7263. }, r);
  7264. });
  7265. return replacee;
  7266. });
  7267. };
  7268. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7269. var children = contents(component);
  7270. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  7271. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7272. });
  7273. };
  7274. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7275. __proto__: null,
  7276. append: append$2,
  7277. prepend: prepend$1,
  7278. remove: remove$7,
  7279. replaceAt: replaceAt,
  7280. replaceBy: replaceBy,
  7281. set: set$5,
  7282. contents: contents
  7283. });
  7284. var Replacing = create$1({
  7285. fields: [],
  7286. name: 'replacing',
  7287. apis: ReplaceApis
  7288. });
  7289. var events$4 = function (name, eventHandlers) {
  7290. var events = derive(eventHandlers);
  7291. return create$1({
  7292. fields: [strict$1('enabled')],
  7293. name: name,
  7294. active: { events: constant(events) }
  7295. });
  7296. };
  7297. var config = function (name, eventHandlers) {
  7298. var me = events$4(name, eventHandlers);
  7299. return {
  7300. key: name,
  7301. value: {
  7302. config: {},
  7303. me: me,
  7304. configAsRaw: constant({}),
  7305. initialConfig: {},
  7306. state: NoState
  7307. }
  7308. };
  7309. };
  7310. var focus$2 = function (component, focusConfig) {
  7311. if (!focusConfig.ignore) {
  7312. focus$1(component.element);
  7313. focusConfig.onFocus(component);
  7314. }
  7315. };
  7316. var blur$1 = function (component, focusConfig) {
  7317. if (!focusConfig.ignore) {
  7318. blur(component.element);
  7319. }
  7320. };
  7321. var isFocused = function (component) {
  7322. return hasFocus(component.element);
  7323. };
  7324. var FocusApis = /*#__PURE__*/Object.freeze({
  7325. __proto__: null,
  7326. focus: focus$2,
  7327. blur: blur$1,
  7328. isFocused: isFocused
  7329. });
  7330. var exhibit$1 = function (base, focusConfig) {
  7331. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7332. return nu$6(mod);
  7333. };
  7334. var events$5 = function (focusConfig) {
  7335. return derive([run(focus(), function (component, simulatedEvent) {
  7336. focus$2(component, focusConfig);
  7337. simulatedEvent.stop();
  7338. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  7339. simulatedEvent.event.prevent();
  7340. })] : []));
  7341. };
  7342. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7343. __proto__: null,
  7344. exhibit: exhibit$1,
  7345. events: events$5
  7346. });
  7347. var FocusSchema = [
  7348. onHandler('onFocus'),
  7349. defaulted$1('stopMousedown', false),
  7350. defaulted$1('ignore', false)
  7351. ];
  7352. var Focusing = create$1({
  7353. fields: FocusSchema,
  7354. name: 'focusing',
  7355. active: ActiveFocus,
  7356. apis: FocusApis
  7357. });
  7358. var SetupBehaviourCellState = function (initialState) {
  7359. var init = function () {
  7360. var cell = Cell(initialState);
  7361. var get = function () {
  7362. return cell.get();
  7363. };
  7364. var set = function (newState) {
  7365. return cell.set(newState);
  7366. };
  7367. var clear = function () {
  7368. return cell.set(initialState);
  7369. };
  7370. var readState = function () {
  7371. return cell.get();
  7372. };
  7373. return {
  7374. get: get,
  7375. set: set,
  7376. clear: clear,
  7377. readState: readState
  7378. };
  7379. };
  7380. return { init: init };
  7381. };
  7382. var updateAriaState = function (component, toggleConfig, toggleState) {
  7383. var ariaInfo = toggleConfig.aria;
  7384. ariaInfo.update(component, ariaInfo, toggleState.get());
  7385. };
  7386. var updateClass = function (component, toggleConfig, toggleState) {
  7387. toggleConfig.toggleClass.each(function (toggleClass) {
  7388. if (toggleState.get()) {
  7389. add$2(component.element, toggleClass);
  7390. } else {
  7391. remove$4(component.element, toggleClass);
  7392. }
  7393. });
  7394. };
  7395. var toggle = function (component, toggleConfig, toggleState) {
  7396. set$6(component, toggleConfig, toggleState, !toggleState.get());
  7397. };
  7398. var on$1 = function (component, toggleConfig, toggleState) {
  7399. toggleState.set(true);
  7400. updateClass(component, toggleConfig, toggleState);
  7401. updateAriaState(component, toggleConfig, toggleState);
  7402. };
  7403. var off = function (component, toggleConfig, toggleState) {
  7404. toggleState.set(false);
  7405. updateClass(component, toggleConfig, toggleState);
  7406. updateAriaState(component, toggleConfig, toggleState);
  7407. };
  7408. var set$6 = function (component, toggleConfig, toggleState, state) {
  7409. var action = state ? on$1 : off;
  7410. action(component, toggleConfig, toggleState);
  7411. };
  7412. var isOn = function (component, toggleConfig, toggleState) {
  7413. return toggleState.get();
  7414. };
  7415. var onLoad$4 = function (component, toggleConfig, toggleState) {
  7416. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  7417. };
  7418. var ToggleApis = /*#__PURE__*/Object.freeze({
  7419. __proto__: null,
  7420. onLoad: onLoad$4,
  7421. toggle: toggle,
  7422. isOn: isOn,
  7423. on: on$1,
  7424. off: off,
  7425. set: set$6
  7426. });
  7427. var exhibit$2 = function () {
  7428. return nu$6({});
  7429. };
  7430. var events$6 = function (toggleConfig, toggleState) {
  7431. var execute = executeEvent(toggleConfig, toggleState, toggle);
  7432. var load = loadEvent(toggleConfig, toggleState, onLoad$4);
  7433. return derive(flatten([
  7434. toggleConfig.toggleOnExecute ? [execute] : [],
  7435. [load]
  7436. ]));
  7437. };
  7438. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7439. __proto__: null,
  7440. exhibit: exhibit$2,
  7441. events: events$6
  7442. });
  7443. var updatePressed = function (component, ariaInfo, status) {
  7444. set$1(component.element, 'aria-pressed', status);
  7445. if (ariaInfo.syncWithExpanded) {
  7446. updateExpanded(component, ariaInfo, status);
  7447. }
  7448. };
  7449. var updateSelected = function (component, ariaInfo, status) {
  7450. set$1(component.element, 'aria-selected', status);
  7451. };
  7452. var updateChecked = function (component, ariaInfo, status) {
  7453. set$1(component.element, 'aria-checked', status);
  7454. };
  7455. var updateExpanded = function (component, ariaInfo, status) {
  7456. set$1(component.element, 'aria-expanded', status);
  7457. };
  7458. var ToggleSchema = [
  7459. defaulted$1('selected', false),
  7460. option('toggleClass'),
  7461. defaulted$1('toggleOnExecute', true),
  7462. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7463. pressed: [
  7464. defaulted$1('syncWithExpanded', false),
  7465. output('update', updatePressed)
  7466. ],
  7467. checked: [output('update', updateChecked)],
  7468. expanded: [output('update', updateExpanded)],
  7469. selected: [output('update', updateSelected)],
  7470. none: [output('update', noop)]
  7471. }))
  7472. ];
  7473. var Toggling = create$1({
  7474. fields: ToggleSchema,
  7475. name: 'toggling',
  7476. active: ActiveToggle,
  7477. apis: ToggleApis,
  7478. state: SetupBehaviourCellState(false)
  7479. });
  7480. var pointerEvents = function () {
  7481. var onClick = function (component, simulatedEvent) {
  7482. simulatedEvent.stop();
  7483. emitExecute(component);
  7484. };
  7485. return [
  7486. run(click(), onClick),
  7487. run(tap(), onClick),
  7488. cutter(touchstart()),
  7489. cutter(mousedown())
  7490. ];
  7491. };
  7492. var events$7 = function (optAction) {
  7493. var executeHandler = function (action) {
  7494. return runOnExecute(function (component, simulatedEvent) {
  7495. action(component);
  7496. simulatedEvent.stop();
  7497. });
  7498. };
  7499. return derive(flatten([
  7500. optAction.map(executeHandler).toArray(),
  7501. pointerEvents()
  7502. ]));
  7503. };
  7504. var hoverEvent = 'alloy.item-hover';
  7505. var focusEvent = 'alloy.item-focus';
  7506. var onHover = function (item) {
  7507. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7508. if (!Focusing.isFocused(item)) {
  7509. Focusing.focus(item);
  7510. }
  7511. emitWith(item, hoverEvent, { item: item });
  7512. }
  7513. };
  7514. var onFocus = function (item) {
  7515. emitWith(item, focusEvent, { item: item });
  7516. };
  7517. var hover = constant(hoverEvent);
  7518. var focus$3 = constant(focusEvent);
  7519. var builder = function (detail) {
  7520. return {
  7521. dom: detail.dom,
  7522. 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 } : {}) }),
  7523. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7524. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7525. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7526. }),
  7527. Focusing.config({
  7528. ignore: detail.ignoreFocus,
  7529. stopMousedown: detail.ignoreFocus,
  7530. onFocus: function (component) {
  7531. onFocus(component);
  7532. }
  7533. }),
  7534. Keying.config({ mode: 'execution' }),
  7535. Representing.config({
  7536. store: {
  7537. mode: 'memory',
  7538. initialValue: detail.data
  7539. }
  7540. }),
  7541. config('item-type-events', __spreadArrays(pointerEvents(), [
  7542. run(mouseover(), onHover),
  7543. run(focusItem(), Focusing.focus)
  7544. ]))
  7545. ]),
  7546. components: detail.components,
  7547. eventOrder: detail.eventOrder
  7548. };
  7549. };
  7550. var schema$a = [
  7551. strict$1('data'),
  7552. strict$1('components'),
  7553. strict$1('dom'),
  7554. defaulted$1('hasSubmenu', false),
  7555. option('toggling'),
  7556. SketchBehaviours.field('itemBehaviours', [
  7557. Toggling,
  7558. Focusing,
  7559. Keying,
  7560. Representing
  7561. ]),
  7562. defaulted$1('ignoreFocus', false),
  7563. defaulted$1('domModification', {}),
  7564. output('builder', builder),
  7565. defaulted$1('eventOrder', {})
  7566. ];
  7567. var builder$1 = function (detail) {
  7568. return {
  7569. dom: detail.dom,
  7570. components: detail.components,
  7571. events: derive([stopper(focusItem())])
  7572. };
  7573. };
  7574. var schema$b = [
  7575. strict$1('dom'),
  7576. strict$1('components'),
  7577. output('builder', builder$1)
  7578. ];
  7579. var owner$2 = function () {
  7580. return 'item-widget';
  7581. };
  7582. var parts = constant([required({
  7583. name: 'widget',
  7584. overrides: function (detail) {
  7585. return {
  7586. behaviours: derive$1([Representing.config({
  7587. store: {
  7588. mode: 'manual',
  7589. getValue: function (_component) {
  7590. return detail.data;
  7591. },
  7592. setValue: function () {
  7593. }
  7594. }
  7595. })])
  7596. };
  7597. }
  7598. })]);
  7599. var builder$2 = function (detail) {
  7600. var subs = substitutes(owner$2(), detail, parts());
  7601. var components$1 = components(owner$2(), detail, subs.internals());
  7602. var focusWidget = function (component) {
  7603. return getPart(component, detail, 'widget').map(function (widget) {
  7604. Keying.focusIn(widget);
  7605. return widget;
  7606. });
  7607. };
  7608. var onHorizontalArrow = function (component, simulatedEvent) {
  7609. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  7610. if (detail.autofocus) {
  7611. simulatedEvent.setSource(component.element);
  7612. return Optional.none();
  7613. } else {
  7614. return Optional.none();
  7615. }
  7616. }();
  7617. };
  7618. return {
  7619. dom: detail.dom,
  7620. components: components$1,
  7621. domModification: detail.domModification,
  7622. events: derive([
  7623. runOnExecute(function (component, simulatedEvent) {
  7624. focusWidget(component).each(function (_widget) {
  7625. simulatedEvent.stop();
  7626. });
  7627. }),
  7628. run(mouseover(), onHover),
  7629. run(focusItem(), function (component, _simulatedEvent) {
  7630. if (detail.autofocus) {
  7631. focusWidget(component);
  7632. } else {
  7633. Focusing.focus(component);
  7634. }
  7635. })
  7636. ]),
  7637. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7638. Representing.config({
  7639. store: {
  7640. mode: 'memory',
  7641. initialValue: detail.data
  7642. }
  7643. }),
  7644. Focusing.config({
  7645. ignore: detail.ignoreFocus,
  7646. onFocus: function (component) {
  7647. onFocus(component);
  7648. }
  7649. }),
  7650. Keying.config({
  7651. mode: 'special',
  7652. focusIn: detail.autofocus ? function (component) {
  7653. focusWidget(component);
  7654. } : revoke(),
  7655. onLeft: onHorizontalArrow,
  7656. onRight: onHorizontalArrow,
  7657. onEscape: function (component, simulatedEvent) {
  7658. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7659. Focusing.focus(component);
  7660. return Optional.some(true);
  7661. } else if (detail.autofocus) {
  7662. simulatedEvent.setSource(component.element);
  7663. return Optional.none();
  7664. } else {
  7665. return Optional.none();
  7666. }
  7667. }
  7668. })
  7669. ])
  7670. };
  7671. };
  7672. var schema$c = [
  7673. strict$1('uid'),
  7674. strict$1('data'),
  7675. strict$1('components'),
  7676. strict$1('dom'),
  7677. defaulted$1('autofocus', false),
  7678. defaulted$1('ignoreFocus', false),
  7679. SketchBehaviours.field('widgetBehaviours', [
  7680. Representing,
  7681. Focusing,
  7682. Keying
  7683. ]),
  7684. defaulted$1('domModification', {}),
  7685. defaultUidsSchema(parts()),
  7686. output('builder', builder$2)
  7687. ];
  7688. var itemSchema$1 = choose$1('type', {
  7689. widget: schema$c,
  7690. item: schema$a,
  7691. separator: schema$b
  7692. });
  7693. var configureGrid = function (detail, movementInfo) {
  7694. return {
  7695. mode: 'flatgrid',
  7696. selector: '.' + detail.markers.item,
  7697. initSize: {
  7698. numColumns: movementInfo.initSize.numColumns,
  7699. numRows: movementInfo.initSize.numRows
  7700. },
  7701. focusManager: detail.focusManager
  7702. };
  7703. };
  7704. var configureMatrix = function (detail, movementInfo) {
  7705. return {
  7706. mode: 'matrix',
  7707. selectors: {
  7708. row: movementInfo.rowSelector,
  7709. cell: '.' + detail.markers.item
  7710. },
  7711. focusManager: detail.focusManager
  7712. };
  7713. };
  7714. var configureMenu = function (detail, movementInfo) {
  7715. return {
  7716. mode: 'menu',
  7717. selector: '.' + detail.markers.item,
  7718. moveOnTab: movementInfo.moveOnTab,
  7719. focusManager: detail.focusManager
  7720. };
  7721. };
  7722. var parts$1 = constant([group({
  7723. factory: {
  7724. sketch: function (spec) {
  7725. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7726. return itemInfo.builder(itemInfo);
  7727. }
  7728. },
  7729. name: 'items',
  7730. unit: 'item',
  7731. defaults: function (detail, u) {
  7732. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  7733. },
  7734. overrides: function (detail, u) {
  7735. return {
  7736. type: u.type,
  7737. ignoreFocus: detail.fakeFocus,
  7738. domModification: { classes: [detail.markers.item] }
  7739. };
  7740. }
  7741. })]);
  7742. var schema$d = constant([
  7743. strict$1('value'),
  7744. strict$1('items'),
  7745. strict$1('dom'),
  7746. strict$1('components'),
  7747. defaulted$1('eventOrder', {}),
  7748. field$1('menuBehaviours', [
  7749. Highlighting,
  7750. Representing,
  7751. Composing,
  7752. Keying
  7753. ]),
  7754. defaultedOf('movement', {
  7755. mode: 'menu',
  7756. moveOnTab: true
  7757. }, choose$1('mode', {
  7758. grid: [
  7759. initSize(),
  7760. output('config', configureGrid)
  7761. ],
  7762. matrix: [
  7763. output('config', configureMatrix),
  7764. strict$1('rowSelector')
  7765. ],
  7766. menu: [
  7767. defaulted$1('moveOnTab', true),
  7768. output('config', configureMenu)
  7769. ]
  7770. })),
  7771. itemMarkers(),
  7772. defaulted$1('fakeFocus', false),
  7773. defaulted$1('focusManager', dom()),
  7774. onHandler('onHighlight')
  7775. ]);
  7776. var focus$4 = constant('alloy.menu-focus');
  7777. var make$1 = function (detail, components, _spec, _externals) {
  7778. return {
  7779. uid: detail.uid,
  7780. dom: detail.dom,
  7781. markers: detail.markers,
  7782. behaviours: augment(detail.menuBehaviours, [
  7783. Highlighting.config({
  7784. highlightClass: detail.markers.selectedItem,
  7785. itemClass: detail.markers.item,
  7786. onHighlight: detail.onHighlight
  7787. }),
  7788. Representing.config({
  7789. store: {
  7790. mode: 'memory',
  7791. initialValue: detail.value
  7792. }
  7793. }),
  7794. Composing.config({ find: Optional.some }),
  7795. Keying.config(detail.movement.config(detail, detail.movement))
  7796. ]),
  7797. events: derive([
  7798. run(focus$3(), function (menu, simulatedEvent) {
  7799. var event = simulatedEvent.event;
  7800. menu.getSystem().getByDom(event.target).each(function (item) {
  7801. Highlighting.highlight(menu, item);
  7802. simulatedEvent.stop();
  7803. emitWith(menu, focus$4(), {
  7804. menu: menu,
  7805. item: item
  7806. });
  7807. });
  7808. }),
  7809. run(hover(), function (menu, simulatedEvent) {
  7810. var item = simulatedEvent.event.item;
  7811. Highlighting.highlight(menu, item);
  7812. })
  7813. ]),
  7814. components: components,
  7815. eventOrder: detail.eventOrder,
  7816. domModification: { attributes: { role: 'menu' } }
  7817. };
  7818. };
  7819. var Menu = composite$1({
  7820. name: 'Menu',
  7821. configFields: schema$d(),
  7822. partFields: parts$1(),
  7823. factory: make$1
  7824. });
  7825. var transpose = function (obj) {
  7826. return tupleMap(obj, function (v, k) {
  7827. return {
  7828. k: v,
  7829. v: k
  7830. };
  7831. });
  7832. };
  7833. var trace = function (items, byItem, byMenu, finish) {
  7834. return get(byMenu, finish).bind(function (triggerItem) {
  7835. return get(items, triggerItem).bind(function (triggerMenu) {
  7836. var rest = trace(items, byItem, byMenu, triggerMenu);
  7837. return Optional.some([triggerMenu].concat(rest));
  7838. });
  7839. }).getOr([]);
  7840. };
  7841. var generate$5 = function (menus, expansions) {
  7842. var items = {};
  7843. each$1(menus, function (menuItems, menu) {
  7844. each(menuItems, function (item) {
  7845. items[item] = menu;
  7846. });
  7847. });
  7848. var byItem = expansions;
  7849. var byMenu = transpose(expansions);
  7850. var menuPaths = map$2(byMenu, function (_triggerItem, submenu) {
  7851. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  7852. });
  7853. return map$2(items, function (menu) {
  7854. return get(menuPaths, menu).getOr([menu]);
  7855. });
  7856. };
  7857. var init$3 = function () {
  7858. var expansions = Cell({});
  7859. var menus = Cell({});
  7860. var paths = Cell({});
  7861. var primary = Cell(Optional.none());
  7862. var directory = Cell({});
  7863. var clear = function () {
  7864. expansions.set({});
  7865. menus.set({});
  7866. paths.set({});
  7867. primary.set(Optional.none());
  7868. };
  7869. var isClear = function () {
  7870. return primary.get().isNone();
  7871. };
  7872. var setMenuBuilt = function (menuName, built) {
  7873. var _a;
  7874. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  7875. type: 'prepared',
  7876. menu: built
  7877. }, _a)));
  7878. };
  7879. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  7880. primary.set(Optional.some(sPrimary));
  7881. expansions.set(sExpansions);
  7882. menus.set(sMenus);
  7883. directory.set(dir);
  7884. var sPaths = generate$5(dir, sExpansions);
  7885. paths.set(sPaths);
  7886. };
  7887. var getTriggeringItem = function (menuValue) {
  7888. return find$1(expansions.get(), function (v, _k) {
  7889. return v === menuValue;
  7890. });
  7891. };
  7892. var getTriggerData = function (menuValue, getItemByValue, path) {
  7893. return getPreparedMenu(menuValue).bind(function (menu) {
  7894. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  7895. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  7896. return {
  7897. triggeredMenu: menu,
  7898. triggeringItem: triggeredItem,
  7899. triggeringPath: path
  7900. };
  7901. });
  7902. });
  7903. });
  7904. };
  7905. var getTriggeringPath = function (itemValue, getItemByValue) {
  7906. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  7907. return getPreparedMenu(menuValue).isSome();
  7908. });
  7909. return get(paths.get(), itemValue).bind(function (path) {
  7910. var revPath = reverse(extraPath.concat(path));
  7911. var triggers = bind(revPath, function (menuValue, menuIndex) {
  7912. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  7913. return primary.get().is(menuValue) ? [] : [Optional.none()];
  7914. }, function (data) {
  7915. return [Optional.some(data)];
  7916. });
  7917. });
  7918. return sequence(triggers);
  7919. });
  7920. };
  7921. var expand = function (itemValue) {
  7922. return get(expansions.get(), itemValue).map(function (menu) {
  7923. var current = get(paths.get(), itemValue).getOr([]);
  7924. return [menu].concat(current);
  7925. });
  7926. };
  7927. var collapse = function (itemValue) {
  7928. return get(paths.get(), itemValue).bind(function (path) {
  7929. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  7930. });
  7931. };
  7932. var refresh = function (itemValue) {
  7933. return get(paths.get(), itemValue);
  7934. };
  7935. var getPreparedMenu = function (menuValue) {
  7936. return lookupMenu(menuValue).bind(extractPreparedMenu);
  7937. };
  7938. var lookupMenu = function (menuValue) {
  7939. return get(menus.get(), menuValue);
  7940. };
  7941. var lookupItem = function (itemValue) {
  7942. return get(expansions.get(), itemValue);
  7943. };
  7944. var otherMenus = function (path) {
  7945. var menuValues = directory.get();
  7946. return difference(keys(menuValues), path);
  7947. };
  7948. var getPrimary = function () {
  7949. return primary.get().bind(getPreparedMenu);
  7950. };
  7951. var getMenus = function () {
  7952. return menus.get();
  7953. };
  7954. return {
  7955. setMenuBuilt: setMenuBuilt,
  7956. setContents: setContents,
  7957. expand: expand,
  7958. refresh: refresh,
  7959. collapse: collapse,
  7960. lookupMenu: lookupMenu,
  7961. lookupItem: lookupItem,
  7962. otherMenus: otherMenus,
  7963. getPrimary: getPrimary,
  7964. getMenus: getMenus,
  7965. clear: clear,
  7966. isClear: isClear,
  7967. getTriggeringPath: getTriggeringPath
  7968. };
  7969. };
  7970. var extractPreparedMenu = function (prep) {
  7971. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  7972. };
  7973. var LayeredState = {
  7974. init: init$3,
  7975. extractPreparedMenu: extractPreparedMenu
  7976. };
  7977. var make$2 = function (detail, _rawUiSpec) {
  7978. var submenuParentItems = Cell(Optional.none());
  7979. var buildMenus = function (container, primaryName, menus) {
  7980. return map$2(menus, function (spec, name) {
  7981. var makeSketch = function () {
  7982. return Menu.sketch(__assign(__assign({}, spec), {
  7983. value: name,
  7984. markers: detail.markers,
  7985. fakeFocus: detail.fakeFocus,
  7986. onHighlight: detail.onHighlight,
  7987. focusManager: detail.fakeFocus ? highlights() : dom()
  7988. }));
  7989. };
  7990. return name === primaryName ? {
  7991. type: 'prepared',
  7992. menu: container.getSystem().build(makeSketch())
  7993. } : {
  7994. type: 'notbuilt',
  7995. nbMenu: makeSketch
  7996. };
  7997. });
  7998. };
  7999. var layeredState = LayeredState.init();
  8000. var setup = function (container) {
  8001. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8002. var directory = toDirectory();
  8003. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8004. return layeredState.getPrimary();
  8005. };
  8006. var getItemValue = function (item) {
  8007. return Representing.getValue(item).value;
  8008. };
  8009. var getItemByValue = function (_container, menus, itemValue) {
  8010. return findMap(menus, function (menu) {
  8011. if (!menu.getSystem().isConnected()) {
  8012. return Optional.none();
  8013. }
  8014. var candidates = Highlighting.getCandidates(menu);
  8015. return find(candidates, function (c) {
  8016. return getItemValue(c) === itemValue;
  8017. });
  8018. });
  8019. };
  8020. var toDirectory = function (_container) {
  8021. return map$2(detail.data.menus, function (data, _menuName) {
  8022. return bind(data.items, function (item) {
  8023. return item.type === 'separator' ? [] : [item.data.value];
  8024. });
  8025. });
  8026. };
  8027. var setActiveMenu = function (container, menu) {
  8028. Highlighting.highlight(container, menu);
  8029. Highlighting.getHighlighted(menu).orThunk(function () {
  8030. return Highlighting.getFirst(menu);
  8031. }).each(function (item) {
  8032. dispatch(container, item.element, focusItem());
  8033. });
  8034. };
  8035. var getMenus = function (state, menuValues) {
  8036. return cat(map(menuValues, function (mv) {
  8037. return state.lookupMenu(mv).bind(function (prep) {
  8038. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8039. });
  8040. }));
  8041. };
  8042. var closeOthers = function (container, state, path) {
  8043. var others = getMenus(state, state.otherMenus(path));
  8044. each(others, function (o) {
  8045. remove$5(o.element, [detail.markers.backgroundMenu]);
  8046. if (!detail.stayInDom) {
  8047. Replacing.remove(container, o);
  8048. }
  8049. });
  8050. };
  8051. var getSubmenuParents = function (container) {
  8052. return submenuParentItems.get().getOrThunk(function () {
  8053. var r = {};
  8054. var items = descendants(container.element, '.' + detail.markers.item);
  8055. var parentItems = filter(items, function (i) {
  8056. return get$2(i, 'aria-haspopup') === 'true';
  8057. });
  8058. each(parentItems, function (i) {
  8059. container.getSystem().getByDom(i).each(function (itemComp) {
  8060. var key = getItemValue(itemComp);
  8061. r[key] = itemComp;
  8062. });
  8063. });
  8064. submenuParentItems.set(Optional.some(r));
  8065. return r;
  8066. });
  8067. };
  8068. var updateAriaExpansions = function (container, path) {
  8069. var parentItems = getSubmenuParents(container);
  8070. each$1(parentItems, function (v, k) {
  8071. var expanded = contains(path, k);
  8072. set$1(v.element, 'aria-expanded', expanded);
  8073. });
  8074. };
  8075. var updateMenuPath = function (container, state, path) {
  8076. return Optional.from(path[0]).bind(function (latestMenuName) {
  8077. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8078. if (menuPrep.type === 'notbuilt') {
  8079. return Optional.none();
  8080. } else {
  8081. var activeMenu = menuPrep.menu;
  8082. var rest = getMenus(state, path.slice(1));
  8083. each(rest, function (r) {
  8084. add$2(r.element, detail.markers.backgroundMenu);
  8085. });
  8086. if (!inBody(activeMenu.element)) {
  8087. Replacing.append(container, premade$1(activeMenu));
  8088. }
  8089. remove$5(activeMenu.element, [detail.markers.backgroundMenu]);
  8090. setActiveMenu(container, activeMenu);
  8091. closeOthers(container, state, path);
  8092. return Optional.some(activeMenu);
  8093. }
  8094. });
  8095. });
  8096. };
  8097. var ExpandHighlightDecision;
  8098. (function (ExpandHighlightDecision) {
  8099. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8100. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8101. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8102. var buildIfRequired = function (container, menuName, menuPrep) {
  8103. if (menuPrep.type === 'notbuilt') {
  8104. var menu = container.getSystem().build(menuPrep.nbMenu());
  8105. layeredState.setMenuBuilt(menuName, menu);
  8106. return menu;
  8107. } else {
  8108. return menuPrep.menu;
  8109. }
  8110. };
  8111. var expandRight = function (container, item, decision) {
  8112. if (decision === void 0) {
  8113. decision = ExpandHighlightDecision.HighlightSubmenu;
  8114. }
  8115. var value = getItemValue(item);
  8116. return layeredState.expand(value).bind(function (path) {
  8117. updateAriaExpansions(container, path);
  8118. return Optional.from(path[0]).bind(function (menuName) {
  8119. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8120. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8121. if (!inBody(activeMenu.element)) {
  8122. Replacing.append(container, premade$1(activeMenu));
  8123. }
  8124. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8125. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8126. Highlighting.highlightFirst(activeMenu);
  8127. return updateMenuPath(container, layeredState, path);
  8128. } else {
  8129. Highlighting.dehighlightAll(activeMenu);
  8130. return Optional.some(item);
  8131. }
  8132. });
  8133. });
  8134. });
  8135. };
  8136. var collapseLeft = function (container, item) {
  8137. var value = getItemValue(item);
  8138. return layeredState.collapse(value).bind(function (path) {
  8139. updateAriaExpansions(container, path);
  8140. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8141. detail.onCollapseMenu(container, item, activeMenu);
  8142. return activeMenu;
  8143. });
  8144. });
  8145. };
  8146. var updateView = function (container, item) {
  8147. var value = getItemValue(item);
  8148. return layeredState.refresh(value).bind(function (path) {
  8149. updateAriaExpansions(container, path);
  8150. return updateMenuPath(container, layeredState, path);
  8151. });
  8152. };
  8153. var onRight = function (container, item) {
  8154. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8155. };
  8156. var onLeft = function (container, item) {
  8157. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8158. };
  8159. var onEscape = function (container, item) {
  8160. return collapseLeft(container, item).orThunk(function () {
  8161. return detail.onEscape(container, item).map(function () {
  8162. return container;
  8163. });
  8164. });
  8165. };
  8166. var keyOnItem = function (f) {
  8167. return function (container, simulatedEvent) {
  8168. return closest$3(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8169. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8170. return f(container, item).map(function () {
  8171. return true;
  8172. });
  8173. });
  8174. });
  8175. };
  8176. };
  8177. var events = derive([
  8178. run(focus$4(), function (sandbox, simulatedEvent) {
  8179. var item = simulatedEvent.event.item;
  8180. layeredState.lookupItem(getItemValue(item)).each(function () {
  8181. var menu = simulatedEvent.event.menu;
  8182. Highlighting.highlight(sandbox, menu);
  8183. var value = getItemValue(simulatedEvent.event.item);
  8184. layeredState.refresh(value).each(function (path) {
  8185. return closeOthers(sandbox, layeredState, path);
  8186. });
  8187. });
  8188. }),
  8189. runOnExecute(function (component, simulatedEvent) {
  8190. var target = simulatedEvent.event.target;
  8191. component.getSystem().getByDom(target).each(function (item) {
  8192. var itemValue = getItemValue(item);
  8193. if (itemValue.indexOf('collapse-item') === 0) {
  8194. collapseLeft(component, item);
  8195. }
  8196. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8197. detail.onExecute(component, item);
  8198. }, function () {
  8199. });
  8200. });
  8201. }),
  8202. runOnAttached(function (container, _simulatedEvent) {
  8203. setup(container).each(function (primary) {
  8204. Replacing.append(container, premade$1(primary));
  8205. detail.onOpenMenu(container, primary);
  8206. if (detail.highlightImmediately) {
  8207. setActiveMenu(container, primary);
  8208. }
  8209. });
  8210. })
  8211. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8212. var item = simulatedEvent.event.item;
  8213. updateView(sandbox, item);
  8214. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8215. detail.onHover(sandbox, item);
  8216. })] : []));
  8217. var getActiveItem = function (container) {
  8218. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8219. };
  8220. var collapseMenuApi = function (container) {
  8221. getActiveItem(container).each(function (currentItem) {
  8222. collapseLeft(container, currentItem);
  8223. });
  8224. };
  8225. var highlightPrimary = function (container) {
  8226. layeredState.getPrimary().each(function (primary) {
  8227. setActiveMenu(container, primary);
  8228. });
  8229. };
  8230. var extractMenuFromContainer = function (container) {
  8231. return Optional.from(container.components()[0]).filter(function (comp) {
  8232. return get$2(comp.element, 'role') === 'menu';
  8233. });
  8234. };
  8235. var repositionMenus = function (container) {
  8236. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8237. return getActiveItem(container).bind(function (currentItem) {
  8238. var itemValue = getItemValue(currentItem);
  8239. var allMenus = values(layeredState.getMenus());
  8240. var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu));
  8241. return layeredState.getTriggeringPath(itemValue, function (v) {
  8242. return getItemByValue(container, preparedMenus, v);
  8243. });
  8244. }).map(function (triggeringPath) {
  8245. return {
  8246. primary: primary,
  8247. triggeringPath: triggeringPath
  8248. };
  8249. });
  8250. });
  8251. maybeActivePrimary.fold(function () {
  8252. extractMenuFromContainer(container).each(function (primaryMenu) {
  8253. detail.onRepositionMenu(container, primaryMenu, []);
  8254. });
  8255. }, function (_a) {
  8256. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8257. detail.onRepositionMenu(container, primary, triggeringPath);
  8258. });
  8259. };
  8260. var apis = {
  8261. collapseMenu: collapseMenuApi,
  8262. highlightPrimary: highlightPrimary,
  8263. repositionMenus: repositionMenus
  8264. };
  8265. return {
  8266. uid: detail.uid,
  8267. dom: detail.dom,
  8268. markers: detail.markers,
  8269. behaviours: augment(detail.tmenuBehaviours, [
  8270. Keying.config({
  8271. mode: 'special',
  8272. onRight: keyOnItem(onRight),
  8273. onLeft: keyOnItem(onLeft),
  8274. onEscape: keyOnItem(onEscape),
  8275. focusIn: function (container, _keyInfo) {
  8276. layeredState.getPrimary().each(function (primary) {
  8277. dispatch(container, primary.element, focusItem());
  8278. });
  8279. }
  8280. }),
  8281. Highlighting.config({
  8282. highlightClass: detail.markers.selectedMenu,
  8283. itemClass: detail.markers.menu
  8284. }),
  8285. Composing.config({
  8286. find: function (container) {
  8287. return Highlighting.getHighlighted(container);
  8288. }
  8289. }),
  8290. Replacing.config({})
  8291. ]),
  8292. eventOrder: detail.eventOrder,
  8293. apis: apis,
  8294. events: events
  8295. };
  8296. };
  8297. var collapseItem = constant('collapse-item');
  8298. var tieredData = function (primary, menus, expansions) {
  8299. return {
  8300. primary: primary,
  8301. menus: menus,
  8302. expansions: expansions
  8303. };
  8304. };
  8305. var singleData = function (name, menu) {
  8306. return {
  8307. primary: name,
  8308. menus: wrap$1(name, menu),
  8309. expansions: {}
  8310. };
  8311. };
  8312. var collapseItem$1 = function (text) {
  8313. return {
  8314. value: generate$1(collapseItem()),
  8315. meta: { text: text }
  8316. };
  8317. };
  8318. var tieredMenu = single$2({
  8319. name: 'TieredMenu',
  8320. configFields: [
  8321. onStrictKeyboardHandler('onExecute'),
  8322. onStrictKeyboardHandler('onEscape'),
  8323. onStrictHandler('onOpenMenu'),
  8324. onStrictHandler('onOpenSubmenu'),
  8325. onHandler('onRepositionMenu'),
  8326. onHandler('onCollapseMenu'),
  8327. defaulted$1('highlightImmediately', true),
  8328. strictObjOf('data', [
  8329. strict$1('primary'),
  8330. strict$1('menus'),
  8331. strict$1('expansions')
  8332. ]),
  8333. defaulted$1('fakeFocus', false),
  8334. onHandler('onHighlight'),
  8335. onHandler('onHover'),
  8336. tieredMenuMarkers(),
  8337. strict$1('dom'),
  8338. defaulted$1('navigateOnHover', true),
  8339. defaulted$1('stayInDom', false),
  8340. field$1('tmenuBehaviours', [
  8341. Keying,
  8342. Highlighting,
  8343. Composing,
  8344. Replacing
  8345. ]),
  8346. defaulted$1('eventOrder', {})
  8347. ],
  8348. apis: {
  8349. collapseMenu: function (apis, tmenu) {
  8350. apis.collapseMenu(tmenu);
  8351. },
  8352. highlightPrimary: function (apis, tmenu) {
  8353. apis.highlightPrimary(tmenu);
  8354. },
  8355. repositionMenus: function (apis, tmenu) {
  8356. apis.repositionMenus(tmenu);
  8357. }
  8358. },
  8359. factory: make$2,
  8360. extraApis: {
  8361. tieredData: tieredData,
  8362. singleData: singleData,
  8363. collapseItem: collapseItem$1
  8364. }
  8365. });
  8366. var makeMenu = function (detail, menuSandbox, anchor, menuSpec, getBounds) {
  8367. var lazySink = function () {
  8368. return detail.lazySink(menuSandbox);
  8369. };
  8370. var layouts = menuSpec.type === 'horizontal' ? {
  8371. layouts: {
  8372. onLtr: function () {
  8373. return belowOrAbove();
  8374. },
  8375. onRtl: function () {
  8376. return belowOrAboveRtl();
  8377. }
  8378. }
  8379. } : {};
  8380. var isFirstTierSubmenu = function (triggeringPaths) {
  8381. return triggeringPaths.length === 2;
  8382. };
  8383. var getSubmenuLayouts = function (triggeringPaths) {
  8384. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8385. };
  8386. return tieredMenu.sketch({
  8387. dom: { tag: 'div' },
  8388. data: menuSpec.data,
  8389. markers: menuSpec.menu.markers,
  8390. highlightImmediately: menuSpec.menu.highlightImmediately,
  8391. onEscape: function () {
  8392. Sandboxing.close(menuSandbox);
  8393. detail.onEscape.map(function (handler) {
  8394. return handler(menuSandbox);
  8395. });
  8396. return Optional.some(true);
  8397. },
  8398. onExecute: function () {
  8399. return Optional.some(true);
  8400. },
  8401. onOpenMenu: function (tmenu, menu) {
  8402. Positioning.positionWithinBounds(lazySink().getOrDie(), anchor, menu, getBounds());
  8403. },
  8404. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8405. var sink = lazySink().getOrDie();
  8406. Positioning.position(sink, __assign({
  8407. anchor: 'submenu',
  8408. item: item
  8409. }, getSubmenuLayouts(triggeringPaths)), submenu);
  8410. },
  8411. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8412. var sink = lazySink().getOrDie();
  8413. Positioning.positionWithinBounds(sink, anchor, primaryMenu, getBounds());
  8414. each(submenuTriggers, function (st) {
  8415. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8416. Positioning.position(sink, __assign({
  8417. anchor: 'submenu',
  8418. item: st.triggeringItem
  8419. }, submenuLayouts), st.triggeredMenu);
  8420. });
  8421. }
  8422. });
  8423. };
  8424. var factory = function (detail, spec) {
  8425. var isPartOfRelated = function (sandbox, queryElem) {
  8426. var related = detail.getRelated(sandbox);
  8427. return related.exists(function (rel) {
  8428. return isPartOf(rel, queryElem);
  8429. });
  8430. };
  8431. var setContent = function (sandbox, thing) {
  8432. Sandboxing.setContent(sandbox, thing);
  8433. };
  8434. var showAt = function (sandbox, anchor, thing) {
  8435. showWithin(sandbox, anchor, thing, Optional.none());
  8436. };
  8437. var showWithin = function (sandbox, anchor, thing, boxElement) {
  8438. showWithinBounds(sandbox, anchor, thing, function () {
  8439. return boxElement.map(function (elem) {
  8440. return box(elem);
  8441. });
  8442. });
  8443. };
  8444. var showWithinBounds = function (sandbox, anchor, thing, getBounds) {
  8445. var sink = detail.lazySink(sandbox).getOrDie();
  8446. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8447. return Positioning.positionWithinBounds(sink, anchor, sandbox, getBounds());
  8448. });
  8449. Representing.setValue(sandbox, Optional.some({
  8450. mode: 'position',
  8451. anchor: anchor,
  8452. getBounds: getBounds
  8453. }));
  8454. };
  8455. var showMenuAt = function (sandbox, anchor, menuSpec) {
  8456. showMenuWithinBounds(sandbox, anchor, menuSpec, function () {
  8457. return Optional.none();
  8458. });
  8459. };
  8460. var showMenuWithinBounds = function (sandbox, anchor, menuSpec, getBounds) {
  8461. var menu = makeMenu(detail, sandbox, anchor, menuSpec, getBounds);
  8462. Sandboxing.open(sandbox, menu);
  8463. Representing.setValue(sandbox, Optional.some({
  8464. mode: 'menu',
  8465. menu: menu
  8466. }));
  8467. };
  8468. var hide = function (sandbox) {
  8469. if (Sandboxing.isOpen(sandbox)) {
  8470. Representing.setValue(sandbox, Optional.none());
  8471. Sandboxing.close(sandbox);
  8472. }
  8473. };
  8474. var getContent = function (sandbox) {
  8475. return Sandboxing.getState(sandbox);
  8476. };
  8477. var reposition = function (sandbox) {
  8478. if (Sandboxing.isOpen(sandbox)) {
  8479. Representing.getValue(sandbox).each(function (state) {
  8480. switch (state.mode) {
  8481. case 'menu':
  8482. Sandboxing.getState(sandbox).each(function (tmenu) {
  8483. tieredMenu.repositionMenus(tmenu);
  8484. });
  8485. break;
  8486. case 'position':
  8487. var sink = detail.lazySink(sandbox).getOrDie();
  8488. Positioning.positionWithinBounds(sink, state.anchor, sandbox, state.getBounds());
  8489. break;
  8490. }
  8491. });
  8492. }
  8493. };
  8494. var apis = {
  8495. setContent: setContent,
  8496. showAt: showAt,
  8497. showWithin: showWithin,
  8498. showWithinBounds: showWithinBounds,
  8499. showMenuAt: showMenuAt,
  8500. showMenuWithinBounds: showMenuWithinBounds,
  8501. hide: hide,
  8502. getContent: getContent,
  8503. reposition: reposition,
  8504. isOpen: Sandboxing.isOpen
  8505. };
  8506. return {
  8507. uid: detail.uid,
  8508. dom: detail.dom,
  8509. behaviours: augment(detail.inlineBehaviours, [
  8510. Sandboxing.config({
  8511. isPartOf: function (sandbox, data, queryElem) {
  8512. return isPartOf(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8513. },
  8514. getAttachPoint: function (sandbox) {
  8515. return detail.lazySink(sandbox).getOrDie();
  8516. },
  8517. onOpen: function (sandbox) {
  8518. detail.onShow(sandbox);
  8519. },
  8520. onClose: function (sandbox) {
  8521. detail.onHide(sandbox);
  8522. }
  8523. }),
  8524. Representing.config({
  8525. store: {
  8526. mode: 'memory',
  8527. initialValue: Optional.none()
  8528. }
  8529. }),
  8530. Receiving.config({
  8531. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) {
  8532. return { fireEventInstead: { event: fe.event } };
  8533. }).getOr({})))), receivingChannel$1(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) {
  8534. return { fireEventInstead: { event: fe.event } };
  8535. }).getOr({})), { doReposition: reposition })))
  8536. })
  8537. ]),
  8538. eventOrder: detail.eventOrder,
  8539. apis: apis
  8540. };
  8541. };
  8542. var InlineView = single$2({
  8543. name: 'InlineView',
  8544. configFields: [
  8545. strict$1('lazySink'),
  8546. onHandler('onShow'),
  8547. onHandler('onHide'),
  8548. optionFunction('onEscape'),
  8549. field$1('inlineBehaviours', [
  8550. Sandboxing,
  8551. Representing,
  8552. Receiving
  8553. ]),
  8554. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  8555. optionObjOf('fireRepositionEventInstead', [defaulted$1('event', repositionRequested())]),
  8556. defaulted$1('getRelated', Optional.none),
  8557. defaulted$1('isExtraPart', never),
  8558. defaulted$1('eventOrder', Optional.none)
  8559. ],
  8560. factory: factory,
  8561. apis: {
  8562. showAt: function (apis, component, anchor, thing) {
  8563. apis.showAt(component, anchor, thing);
  8564. },
  8565. showWithin: function (apis, component, anchor, thing, boxElement) {
  8566. apis.showWithin(component, anchor, thing, boxElement);
  8567. },
  8568. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8569. apis.showWithinBounds(component, anchor, thing, bounds);
  8570. },
  8571. showMenuAt: function (apis, component, anchor, menuSpec) {
  8572. apis.showMenuAt(component, anchor, menuSpec);
  8573. },
  8574. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8575. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8576. },
  8577. hide: function (apis, component) {
  8578. apis.hide(component);
  8579. },
  8580. isOpen: function (apis, component) {
  8581. return apis.isOpen(component);
  8582. },
  8583. getContent: function (apis, component) {
  8584. return apis.getContent(component);
  8585. },
  8586. setContent: function (apis, component, thing) {
  8587. apis.setContent(component, thing);
  8588. },
  8589. reposition: function (apis, component) {
  8590. apis.reposition(component);
  8591. }
  8592. }
  8593. });
  8594. var westEdgeX$1 = function (anchor) {
  8595. return anchor.x;
  8596. };
  8597. var middleX$1 = function (anchor, element) {
  8598. return anchor.x + anchor.width / 2 - element.width / 2;
  8599. };
  8600. var eastEdgeX$1 = function (anchor, element) {
  8601. return anchor.x + anchor.width - element.width;
  8602. };
  8603. var northY$2 = function (anchor) {
  8604. return anchor.y;
  8605. };
  8606. var southY$2 = function (anchor, element) {
  8607. return anchor.y + anchor.height - element.height;
  8608. };
  8609. var southeast$3 = function (anchor, element, bubbles) {
  8610. return nu$7(eastEdgeX$1(anchor, element), southY$2(anchor, element), bubbles.innerSoutheast(), northwest(), boundsRestriction(anchor, {
  8611. right: 0,
  8612. bottom: 3
  8613. }), 'layout-inner-se');
  8614. };
  8615. var southwest$3 = function (anchor, element, bubbles) {
  8616. return nu$7(westEdgeX$1(anchor), southY$2(anchor, element), bubbles.innerSouthwest(), northeast(), boundsRestriction(anchor, {
  8617. left: 1,
  8618. bottom: 3
  8619. }), 'layout-inner-sw');
  8620. };
  8621. var northeast$3 = function (anchor, element, bubbles) {
  8622. return nu$7(eastEdgeX$1(anchor, element), northY$2(anchor), bubbles.innerNortheast(), southwest(), boundsRestriction(anchor, {
  8623. right: 0,
  8624. top: 2
  8625. }), 'layout-inner-ne');
  8626. };
  8627. var northwest$3 = function (anchor, element, bubbles) {
  8628. return nu$7(westEdgeX$1(anchor), northY$2(anchor), bubbles.innerNorthwest(), southeast(), boundsRestriction(anchor, {
  8629. left: 1,
  8630. top: 2
  8631. }), 'layout-inner-nw');
  8632. };
  8633. var north$3 = function (anchor, element, bubbles) {
  8634. return nu$7(middleX$1(anchor, element), northY$2(anchor), bubbles.innerNorth(), south(), boundsRestriction(anchor, { top: 2 }), 'layout-inner-n');
  8635. };
  8636. var south$3 = function (anchor, element, bubbles) {
  8637. return nu$7(middleX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouth(), north(), boundsRestriction(anchor, { bottom: 3 }), 'layout-inner-s');
  8638. };
  8639. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  8640. var factory$1 = function (detail) {
  8641. var events = events$7(detail.action);
  8642. var tag = detail.dom.tag;
  8643. var lookupAttr = function (attr) {
  8644. return get(detail.dom, 'attributes').bind(function (attrs) {
  8645. return get(attrs, attr);
  8646. });
  8647. };
  8648. var getModAttributes = function () {
  8649. if (tag === 'button') {
  8650. var type = lookupAttr('type').getOr('button');
  8651. var roleAttrs = lookupAttr('role').map(function (role) {
  8652. return { role: role };
  8653. }).getOr({});
  8654. return __assign({ type: type }, roleAttrs);
  8655. } else {
  8656. var role = lookupAttr('role').getOr('button');
  8657. return { role: role };
  8658. }
  8659. };
  8660. return {
  8661. uid: detail.uid,
  8662. dom: detail.dom,
  8663. components: detail.components,
  8664. events: events,
  8665. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  8666. Focusing.config({}),
  8667. Keying.config({
  8668. mode: 'execution',
  8669. useSpace: true,
  8670. useEnter: true
  8671. })
  8672. ]),
  8673. domModification: { attributes: getModAttributes() },
  8674. eventOrder: detail.eventOrder
  8675. };
  8676. };
  8677. var Button = single$2({
  8678. name: 'Button',
  8679. factory: factory$1,
  8680. configFields: [
  8681. defaulted$1('uid', undefined),
  8682. strict$1('dom'),
  8683. defaulted$1('components', []),
  8684. SketchBehaviours.field('buttonBehaviours', [
  8685. Focusing,
  8686. Keying
  8687. ]),
  8688. option('action'),
  8689. option('role'),
  8690. defaulted$1('eventOrder', {})
  8691. ]
  8692. });
  8693. var record = function (spec) {
  8694. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  8695. var get = function (anyInSystem) {
  8696. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  8697. };
  8698. var getOpt = function (anyInSystem) {
  8699. return anyInSystem.getSystem().getByUid(uid).toOptional();
  8700. };
  8701. var asSpec = function () {
  8702. return __assign(__assign({}, spec), { uid: uid });
  8703. };
  8704. return {
  8705. get: get,
  8706. getOpt: getOpt,
  8707. asSpec: asSpec
  8708. };
  8709. };
  8710. var defaultIcon = function (icons) {
  8711. return Optional.from(icons()['temporary-placeholder']).getOr('!not found!');
  8712. };
  8713. var get$d = function (name, icons) {
  8714. return Optional.from(icons()[name.toLowerCase()]).getOrThunk(function () {
  8715. return defaultIcon(icons);
  8716. });
  8717. };
  8718. var getOr = function (name, icons, fallback) {
  8719. return Optional.from(icons()[name.toLowerCase()]).or(fallback).getOrThunk(function () {
  8720. return defaultIcon(icons);
  8721. });
  8722. };
  8723. var getFirst$1 = function (names, icons) {
  8724. return findMap(names, function (name) {
  8725. return Optional.from(icons()[name.toLowerCase()]);
  8726. }).getOrThunk(function () {
  8727. return defaultIcon(icons);
  8728. });
  8729. };
  8730. var notificationIconMap = {
  8731. success: 'checkmark',
  8732. error: 'warning',
  8733. err: 'error',
  8734. warning: 'warning',
  8735. warn: 'warning',
  8736. info: 'info'
  8737. };
  8738. var factory$2 = function (detail) {
  8739. var memBannerText = record({
  8740. dom: {
  8741. tag: 'p',
  8742. innerHtml: detail.translationProvider(detail.text)
  8743. },
  8744. behaviours: derive$1([Replacing.config({})])
  8745. });
  8746. var renderPercentBar = function (percent) {
  8747. return {
  8748. dom: {
  8749. tag: 'div',
  8750. classes: ['tox-bar'],
  8751. attributes: { style: 'width: ' + percent + '%' }
  8752. }
  8753. };
  8754. };
  8755. var renderPercentText = function (percent) {
  8756. return {
  8757. dom: {
  8758. tag: 'div',
  8759. classes: ['tox-text'],
  8760. innerHtml: percent + '%'
  8761. }
  8762. };
  8763. };
  8764. var memBannerProgress = record({
  8765. dom: {
  8766. tag: 'div',
  8767. classes: detail.progress ? [
  8768. 'tox-progress-bar',
  8769. 'tox-progress-indicator'
  8770. ] : ['tox-progress-bar']
  8771. },
  8772. components: [
  8773. {
  8774. dom: {
  8775. tag: 'div',
  8776. classes: ['tox-bar-container']
  8777. },
  8778. components: [renderPercentBar(0)]
  8779. },
  8780. renderPercentText(0)
  8781. ],
  8782. behaviours: derive$1([Replacing.config({})])
  8783. });
  8784. var updateProgress = function (comp, percent) {
  8785. if (comp.getSystem().isConnected()) {
  8786. memBannerProgress.getOpt(comp).each(function (progress) {
  8787. Replacing.set(progress, [
  8788. {
  8789. dom: {
  8790. tag: 'div',
  8791. classes: ['tox-bar-container']
  8792. },
  8793. components: [renderPercentBar(percent)]
  8794. },
  8795. renderPercentText(percent)
  8796. ]);
  8797. });
  8798. }
  8799. };
  8800. var updateText = function (comp, text$1) {
  8801. if (comp.getSystem().isConnected()) {
  8802. var banner = memBannerText.get(comp);
  8803. Replacing.set(banner, [text(text$1)]);
  8804. }
  8805. };
  8806. var apis = {
  8807. updateProgress: updateProgress,
  8808. updateText: updateText
  8809. };
  8810. var iconChoices = flatten([
  8811. detail.icon.toArray(),
  8812. detail.level.toArray(),
  8813. detail.level.bind(function (level) {
  8814. return Optional.from(notificationIconMap[level]);
  8815. }).toArray()
  8816. ]);
  8817. var memButton = record(Button.sketch({
  8818. dom: {
  8819. tag: 'button',
  8820. classes: [
  8821. 'tox-notification__dismiss',
  8822. 'tox-button',
  8823. 'tox-button--naked',
  8824. 'tox-button--icon'
  8825. ]
  8826. },
  8827. components: [{
  8828. dom: {
  8829. tag: 'div',
  8830. classes: ['tox-icon'],
  8831. innerHtml: get$d('close', detail.iconProvider),
  8832. attributes: { 'aria-label': detail.translationProvider('Close') }
  8833. }
  8834. }],
  8835. action: function (comp) {
  8836. detail.onAction(comp);
  8837. }
  8838. }));
  8839. var components = [
  8840. {
  8841. dom: {
  8842. tag: 'div',
  8843. classes: ['tox-notification__icon'],
  8844. innerHtml: getFirst$1(iconChoices, detail.iconProvider)
  8845. }
  8846. },
  8847. {
  8848. dom: {
  8849. tag: 'div',
  8850. classes: ['tox-notification__body']
  8851. },
  8852. components: [memBannerText.asSpec()],
  8853. behaviours: derive$1([Replacing.config({})])
  8854. }
  8855. ];
  8856. return {
  8857. uid: detail.uid,
  8858. dom: {
  8859. tag: 'div',
  8860. attributes: { role: 'alert' },
  8861. classes: detail.level.map(function (level) {
  8862. return [
  8863. 'tox-notification',
  8864. 'tox-notification--in',
  8865. 'tox-notification--' + level
  8866. ];
  8867. }).getOr([
  8868. 'tox-notification',
  8869. 'tox-notification--in'
  8870. ])
  8871. },
  8872. behaviours: derive$1([
  8873. Focusing.config({}),
  8874. config('notification-events', [run(focusin(), function (comp) {
  8875. memButton.getOpt(comp).each(Focusing.focus);
  8876. })])
  8877. ]),
  8878. components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
  8879. apis: apis
  8880. };
  8881. };
  8882. var Notification = single$2({
  8883. name: 'Notification',
  8884. factory: factory$2,
  8885. configFields: [
  8886. option('level'),
  8887. strict$1('progress'),
  8888. strict$1('icon'),
  8889. strict$1('onAction'),
  8890. strict$1('text'),
  8891. strict$1('iconProvider'),
  8892. strict$1('translationProvider'),
  8893. defaultedBoolean('closeButton', true)
  8894. ],
  8895. apis: {
  8896. updateProgress: function (apis, comp, percent) {
  8897. apis.updateProgress(comp, percent);
  8898. },
  8899. updateText: function (apis, comp, text) {
  8900. apis.updateText(comp, text);
  8901. }
  8902. }
  8903. });
  8904. function NotificationManagerImpl (editor, extras, uiMothership) {
  8905. var backstage = extras.backstage;
  8906. var getLayoutDirection = function (rel) {
  8907. switch (rel) {
  8908. case 'bc-bc':
  8909. return south$3;
  8910. case 'tc-tc':
  8911. return north$3;
  8912. case 'tc-bc':
  8913. return north$1;
  8914. case 'bc-tc':
  8915. default:
  8916. return south$1;
  8917. }
  8918. };
  8919. var prePositionNotifications = function (notifications) {
  8920. each(notifications, function (notification) {
  8921. return notification.moveTo(0, 0);
  8922. });
  8923. };
  8924. var positionNotifications = function (notifications) {
  8925. if (notifications.length > 0) {
  8926. head(notifications).each(function (firstItem) {
  8927. return firstItem.moveRel(null, 'banner');
  8928. });
  8929. each(notifications, function (notification, index) {
  8930. if (index > 0) {
  8931. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  8932. }
  8933. });
  8934. }
  8935. };
  8936. var reposition = function (notifications) {
  8937. prePositionNotifications(notifications);
  8938. positionNotifications(notifications);
  8939. };
  8940. var open = function (settings, closeCallback) {
  8941. var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  8942. var close = function () {
  8943. closeCallback();
  8944. InlineView.hide(notificationWrapper);
  8945. };
  8946. var notification = build$1(Notification.sketch({
  8947. text: settings.text,
  8948. level: contains([
  8949. 'success',
  8950. 'error',
  8951. 'warning',
  8952. 'warn',
  8953. 'info'
  8954. ], settings.type) ? settings.type : undefined,
  8955. progress: settings.progressBar === true,
  8956. icon: Optional.from(settings.icon),
  8957. closeButton: !hideCloseButton,
  8958. onAction: close,
  8959. iconProvider: backstage.shared.providers.icons,
  8960. translationProvider: backstage.shared.providers.translate
  8961. }));
  8962. var notificationWrapper = build$1(InlineView.sketch(__assign({
  8963. dom: {
  8964. tag: 'div',
  8965. classes: ['tox-notifications-container']
  8966. },
  8967. lazySink: extras.backstage.shared.getSink,
  8968. fireDismissalEventInstead: {}
  8969. }, backstage.shared.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
  8970. uiMothership.add(notificationWrapper);
  8971. if (settings.timeout > 0) {
  8972. global$2.setTimeout(function () {
  8973. close();
  8974. }, settings.timeout);
  8975. }
  8976. return {
  8977. close: close,
  8978. moveTo: function (x, y) {
  8979. InlineView.showAt(notificationWrapper, {
  8980. anchor: 'makeshift',
  8981. x: x,
  8982. y: y
  8983. }, premade$1(notification));
  8984. },
  8985. moveRel: function (element, rel) {
  8986. if (rel !== 'banner') {
  8987. var layoutDirection_1 = getLayoutDirection(rel);
  8988. var nodeAnchor = {
  8989. anchor: 'node',
  8990. root: body(),
  8991. node: Optional.some(SugarElement.fromDom(element)),
  8992. layouts: {
  8993. onRtl: function () {
  8994. return [layoutDirection_1];
  8995. },
  8996. onLtr: function () {
  8997. return [layoutDirection_1];
  8998. }
  8999. }
  9000. };
  9001. InlineView.showAt(notificationWrapper, nodeAnchor, premade$1(notification));
  9002. } else {
  9003. InlineView.showAt(notificationWrapper, extras.backstage.shared.anchors.banner(), premade$1(notification));
  9004. }
  9005. },
  9006. text: function (nuText) {
  9007. Notification.updateText(notification, nuText);
  9008. },
  9009. settings: settings,
  9010. getEl: function () {
  9011. return notification.element.dom;
  9012. },
  9013. progressBar: {
  9014. value: function (percent) {
  9015. Notification.updateProgress(notification, percent);
  9016. }
  9017. }
  9018. };
  9019. };
  9020. var close = function (notification) {
  9021. notification.close();
  9022. };
  9023. var getArgs = function (notification) {
  9024. return notification.settings;
  9025. };
  9026. return {
  9027. open: open,
  9028. close: close,
  9029. reposition: reposition,
  9030. getArgs: getArgs
  9031. };
  9032. }
  9033. var first = function (fn, rate) {
  9034. var timer = null;
  9035. var cancel = function () {
  9036. if (timer !== null) {
  9037. clearTimeout(timer);
  9038. timer = null;
  9039. }
  9040. };
  9041. var throttle = function () {
  9042. var args = [];
  9043. for (var _i = 0; _i < arguments.length; _i++) {
  9044. args[_i] = arguments[_i];
  9045. }
  9046. if (timer === null) {
  9047. timer = setTimeout(function () {
  9048. fn.apply(null, args);
  9049. timer = null;
  9050. }, rate);
  9051. }
  9052. };
  9053. return {
  9054. cancel: cancel,
  9055. throttle: throttle
  9056. };
  9057. };
  9058. var last$2 = function (fn, rate) {
  9059. var timer = null;
  9060. var cancel = function () {
  9061. if (timer !== null) {
  9062. clearTimeout(timer);
  9063. timer = null;
  9064. }
  9065. };
  9066. var throttle = function () {
  9067. var args = [];
  9068. for (var _i = 0; _i < arguments.length; _i++) {
  9069. args[_i] = arguments[_i];
  9070. }
  9071. if (timer !== null) {
  9072. clearTimeout(timer);
  9073. }
  9074. timer = setTimeout(function () {
  9075. fn.apply(null, args);
  9076. timer = null;
  9077. }, rate);
  9078. };
  9079. return {
  9080. cancel: cancel,
  9081. throttle: throttle
  9082. };
  9083. };
  9084. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  9085. var isBoundary = function (dom, node) {
  9086. return dom.isBlock(node) || contains([
  9087. 'BR',
  9088. 'IMG',
  9089. 'HR',
  9090. 'INPUT'
  9091. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9092. };
  9093. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9094. var search = global$3(dom, function (node) {
  9095. return isBoundary(dom, node);
  9096. });
  9097. return Optional.from(search.backwards(node, offset, process, rootNode));
  9098. };
  9099. var autocompleteSelector = '[data-mce-autocompleter]';
  9100. var create$4 = function (editor, range) {
  9101. return detect$4(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9102. var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9103. append(wrapper, SugarElement.fromDom(range.extractContents()));
  9104. range.insertNode(wrapper.dom);
  9105. parent(wrapper).each(function (elm) {
  9106. return elm.dom.normalize();
  9107. });
  9108. last$1(wrapper).map(function (last) {
  9109. editor.selection.setCursorLocation(last.dom, getEnd(last));
  9110. });
  9111. return wrapper;
  9112. });
  9113. };
  9114. var detect$4 = function (elm) {
  9115. return closest$3(elm, autocompleteSelector);
  9116. };
  9117. var isValidTextRange = function (rng) {
  9118. return rng.collapsed && rng.startContainer.nodeType === 3;
  9119. };
  9120. var getText = function (rng) {
  9121. return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9122. };
  9123. var isWhitespace = function (chr) {
  9124. return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  9125. };
  9126. var stripTriggerChar = function (text, triggerCh) {
  9127. return text.substring(triggerCh.length);
  9128. };
  9129. var findChar = function (text, index, ch) {
  9130. var i;
  9131. for (i = index - 1; i >= 0; i--) {
  9132. var char = text.charAt(i);
  9133. if (isWhitespace(char)) {
  9134. return Optional.none();
  9135. }
  9136. if (char === ch) {
  9137. break;
  9138. }
  9139. }
  9140. return Optional.some(i);
  9141. };
  9142. var findStart = function (dom, initRange, ch, minChars) {
  9143. if (minChars === void 0) {
  9144. minChars = 0;
  9145. }
  9146. if (!isValidTextRange(initRange)) {
  9147. return Optional.none();
  9148. }
  9149. var findTriggerChIndex = function (element, offset, text) {
  9150. return findChar(text, offset, ch).getOr(offset);
  9151. };
  9152. var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  9153. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  9154. var range = initRange.cloneRange();
  9155. range.setStart(spot.container, spot.offset);
  9156. range.setEnd(initRange.endContainer, initRange.endOffset);
  9157. if (range.collapsed) {
  9158. return Optional.none();
  9159. }
  9160. var text = getText(range);
  9161. var triggerCharIndex = text.lastIndexOf(ch);
  9162. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  9163. return Optional.none();
  9164. } else {
  9165. return Optional.some({
  9166. text: stripTriggerChar(text, ch),
  9167. range: range,
  9168. triggerChar: ch
  9169. });
  9170. }
  9171. });
  9172. };
  9173. var getContext = function (dom, initRange, ch, minChars) {
  9174. if (minChars === void 0) {
  9175. minChars = 0;
  9176. }
  9177. return detect$4(SugarElement.fromDom(initRange.startContainer)).fold(function () {
  9178. return findStart(dom, initRange, ch, minChars);
  9179. }, function (elm) {
  9180. var range = dom.createRng();
  9181. range.selectNode(elm.dom);
  9182. var text = getText(range);
  9183. return Optional.some({
  9184. range: range,
  9185. text: stripTriggerChar(text, ch),
  9186. triggerChar: ch
  9187. });
  9188. });
  9189. };
  9190. var setup = function (api, editor) {
  9191. editor.on('keypress compositionend', api.onKeypress.throttle);
  9192. editor.on('remove', api.onKeypress.cancel);
  9193. var redirectKeyToItem = function (item, e) {
  9194. emitWith(item, keydown(), { raw: e });
  9195. };
  9196. editor.on('keydown', function (e) {
  9197. var getItem = function () {
  9198. return api.getView().bind(Highlighting.getHighlighted);
  9199. };
  9200. if (e.which === 8) {
  9201. api.onKeypress.throttle(e);
  9202. }
  9203. if (api.isActive()) {
  9204. if (e.which === 27) {
  9205. api.cancelIfNecessary();
  9206. }
  9207. if (api.isMenuOpen()) {
  9208. if (e.which === 13) {
  9209. getItem().each(emitExecute);
  9210. e.preventDefault();
  9211. } else if (e.which === 40) {
  9212. getItem().fold(function () {
  9213. api.getView().each(Highlighting.highlightFirst);
  9214. }, function (item) {
  9215. redirectKeyToItem(item, e);
  9216. });
  9217. e.preventDefault();
  9218. e.stopImmediatePropagation();
  9219. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9220. getItem().each(function (item) {
  9221. redirectKeyToItem(item, e);
  9222. e.preventDefault();
  9223. e.stopImmediatePropagation();
  9224. });
  9225. }
  9226. } else {
  9227. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9228. api.cancelIfNecessary();
  9229. }
  9230. }
  9231. }
  9232. });
  9233. editor.on('NodeChange', function (e) {
  9234. if (api.isActive() && !api.isProcessingAction() && detect$4(SugarElement.fromDom(e.element)).isNone()) {
  9235. api.cancelIfNecessary();
  9236. }
  9237. });
  9238. };
  9239. var AutocompleterEditorEvents = { setup: setup };
  9240. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9241. var point$2 = function (container, offset) {
  9242. return {
  9243. container: container,
  9244. offset: offset
  9245. };
  9246. };
  9247. var isText$1 = function (node) {
  9248. return node.nodeType === TEXT;
  9249. };
  9250. var isElement$1 = function (node) {
  9251. return node.nodeType === ELEMENT;
  9252. };
  9253. var toLast = function (node) {
  9254. if (isText$1(node)) {
  9255. return point$2(node, node.data.length);
  9256. } else {
  9257. var children = node.childNodes;
  9258. return children.length > 0 ? toLast(children[children.length - 1]) : point$2(node, children.length);
  9259. }
  9260. };
  9261. var toLeaf = function (node, offset) {
  9262. var children = node.childNodes;
  9263. if (children.length > 0 && offset < children.length) {
  9264. return toLeaf(children[offset], 0);
  9265. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9266. return toLast(children[children.length - 1]);
  9267. } else {
  9268. return point$2(node, offset);
  9269. }
  9270. };
  9271. var isPreviousCharContent = function (dom, leaf) {
  9272. return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  9273. return offset === 0 ? -1 : offset;
  9274. }, dom.getRoot()).filter(function (spot) {
  9275. var char = spot.container.data.charAt(spot.offset - 1);
  9276. return !isWhitespace(char);
  9277. }).isSome();
  9278. };
  9279. var isStartOfWord = function (dom) {
  9280. return function (rng) {
  9281. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9282. return !isPreviousCharContent(dom, leaf);
  9283. };
  9284. };
  9285. var getTriggerContext = function (dom, initRange, database) {
  9286. return findMap(database.triggerChars, function (ch) {
  9287. return getContext(dom, initRange, ch);
  9288. });
  9289. };
  9290. var lookup = function (editor, getDatabase) {
  9291. var database = getDatabase();
  9292. var rng = editor.selection.getRng();
  9293. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9294. return lookupWithContext(editor, getDatabase, context);
  9295. });
  9296. };
  9297. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9298. if (fetchOptions === void 0) {
  9299. fetchOptions = {};
  9300. }
  9301. var database = getDatabase();
  9302. var rng = editor.selection.getRng();
  9303. var startText = rng.startContainer.nodeValue;
  9304. var autocompleters = filter(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9305. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9306. return isStartOfWord(editor.dom);
  9307. })(context.range, startText, context.text);
  9308. });
  9309. if (autocompleters.length === 0) {
  9310. return Optional.none();
  9311. }
  9312. var lookupData = global$4.all(map(autocompleters, function (ac) {
  9313. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9314. return fetchResult.then(function (results) {
  9315. return {
  9316. matchText: context.text,
  9317. items: results,
  9318. columns: ac.columns,
  9319. onAction: ac.onAction
  9320. };
  9321. });
  9322. }));
  9323. return Optional.some({
  9324. lookupData: lookupData,
  9325. context: context
  9326. });
  9327. };
  9328. var separatorMenuItemSchema = objOf([
  9329. strictString('type'),
  9330. optionString('text')
  9331. ]);
  9332. var createSeparatorMenuItem = function (spec) {
  9333. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9334. };
  9335. var autocompleterItemSchema = objOf([
  9336. defaulted$1('type', 'autocompleteitem'),
  9337. defaulted$1('active', false),
  9338. defaulted$1('disabled', false),
  9339. defaulted$1('meta', {}),
  9340. strictString('value'),
  9341. optionString('text'),
  9342. optionString('icon')
  9343. ]);
  9344. var autocompleterSchema = objOf([
  9345. strictString('type'),
  9346. strictString('ch'),
  9347. defaultedNumber('minChars', 1),
  9348. defaulted$1('columns', 1),
  9349. defaultedNumber('maxResults', 10),
  9350. optionFunction('matches'),
  9351. strictFunction('fetch'),
  9352. strictFunction('onAction')
  9353. ]);
  9354. var createSeparatorItem = function (spec) {
  9355. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9356. };
  9357. var createAutocompleterItem = function (spec) {
  9358. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9359. };
  9360. var createAutocompleter = function (spec) {
  9361. return asRaw('Autocompleter', autocompleterSchema, spec);
  9362. };
  9363. var baseToolbarButtonFields = [
  9364. defaultedBoolean('disabled', false),
  9365. optionString('tooltip'),
  9366. optionString('icon'),
  9367. optionString('text'),
  9368. defaultedFunction('onSetup', function () {
  9369. return noop;
  9370. })
  9371. ];
  9372. var toolbarButtonSchema = objOf([
  9373. strictString('type'),
  9374. strictFunction('onAction')
  9375. ].concat(baseToolbarButtonFields));
  9376. var createToolbarButton = function (spec) {
  9377. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  9378. };
  9379. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  9380. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  9381. strictString('type'),
  9382. strictFunction('onAction')
  9383. ]));
  9384. var createToggleButton = function (spec) {
  9385. return asRaw('ToggleButton', toggleButtonSchema, spec);
  9386. };
  9387. var contextBarFields = [
  9388. defaultedFunction('predicate', function () {
  9389. return false;
  9390. }),
  9391. defaultedStringEnum('scope', 'node', [
  9392. 'node',
  9393. 'editor'
  9394. ]),
  9395. defaultedStringEnum('position', 'selection', [
  9396. 'node',
  9397. 'selection',
  9398. 'line'
  9399. ])
  9400. ];
  9401. var contextButtonFields = baseToolbarButtonFields.concat([
  9402. defaulted$1('type', 'contextformbutton'),
  9403. defaulted$1('primary', false),
  9404. strictFunction('onAction'),
  9405. state$1('original', identity)
  9406. ]);
  9407. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  9408. defaulted$1('type', 'contextformbutton'),
  9409. defaulted$1('primary', false),
  9410. strictFunction('onAction'),
  9411. state$1('original', identity)
  9412. ]);
  9413. var launchButtonFields = baseToolbarButtonFields.concat([defaulted$1('type', 'contextformbutton')]);
  9414. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted$1('type', 'contextformtogglebutton')]);
  9415. var toggleOrNormal = choose$1('type', {
  9416. contextformbutton: contextButtonFields,
  9417. contextformtogglebutton: contextToggleButtonFields
  9418. });
  9419. var contextFormSchema = objOf([
  9420. defaulted$1('type', 'contextform'),
  9421. defaultedFunction('initValue', function () {
  9422. return '';
  9423. }),
  9424. optionString('label'),
  9425. strictArrayOf('commands', toggleOrNormal),
  9426. optionOf('launch', choose$1('type', {
  9427. contextformbutton: launchButtonFields,
  9428. contextformtogglebutton: launchToggleButtonFields
  9429. }))
  9430. ].concat(contextBarFields));
  9431. var createContextForm = function (spec) {
  9432. return asRaw('ContextForm', contextFormSchema, spec);
  9433. };
  9434. var contextToolbarSchema = objOf([
  9435. defaulted$1('type', 'contexttoolbar'),
  9436. strictString('items')
  9437. ].concat(contextBarFields));
  9438. var createContextToolbar = function (spec) {
  9439. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  9440. };
  9441. var stringArray = function (a) {
  9442. var all = {};
  9443. each(a, function (key) {
  9444. all[key] = {};
  9445. });
  9446. return keys(all);
  9447. };
  9448. var register = function (editor) {
  9449. var popups = editor.ui.registry.getAll().popups;
  9450. var dataset = map$2(popups, function (popup) {
  9451. return createAutocompleter(popup).fold(function (err) {
  9452. throw new Error(formatError(err));
  9453. }, function (x) {
  9454. return x;
  9455. });
  9456. });
  9457. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9458. return v.ch;
  9459. }));
  9460. var datasetValues = values(dataset);
  9461. var lookupByChar = function (ch) {
  9462. return filter(datasetValues, function (dv) {
  9463. return dv.ch === ch;
  9464. });
  9465. };
  9466. return {
  9467. dataset: dataset,
  9468. triggerChars: triggerChars,
  9469. lookupByChar: lookupByChar
  9470. };
  9471. };
  9472. var ItemResponse;
  9473. (function (ItemResponse) {
  9474. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  9475. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  9476. }(ItemResponse || (ItemResponse = {})));
  9477. var ItemResponse$1 = ItemResponse;
  9478. var navClass = 'tox-menu-nav__js';
  9479. var selectableClass = 'tox-collection__item';
  9480. var colorClass = 'tox-swatch';
  9481. var presetClasses = {
  9482. normal: navClass,
  9483. color: colorClass
  9484. };
  9485. var tickedClass = 'tox-collection__item--enabled';
  9486. var groupHeadingClass = 'tox-collection__group-heading';
  9487. var iconClass = 'tox-collection__item-icon';
  9488. var textClass = 'tox-collection__item-label';
  9489. var accessoryClass = 'tox-collection__item-accessory';
  9490. var caretClass = 'tox-collection__item-caret';
  9491. var checkmarkClass = 'tox-collection__item-checkmark';
  9492. var activeClass = 'tox-collection__item--active';
  9493. var iconClassRtl = 'tox-collection__item-icon-rtl';
  9494. var classForPreset = function (presets) {
  9495. return get(presetClasses, presets).getOr(navClass);
  9496. };
  9497. var forMenu = function (presets) {
  9498. if (presets === 'color') {
  9499. return 'tox-swatches';
  9500. } else {
  9501. return 'tox-menu';
  9502. }
  9503. };
  9504. var classes = function (presets) {
  9505. return {
  9506. backgroundMenu: 'tox-background-menu',
  9507. selectedMenu: 'tox-selected-menu',
  9508. selectedItem: 'tox-collection__item--active',
  9509. hasIcons: 'tox-menu--has-icons',
  9510. menu: forMenu(presets),
  9511. tieredMenu: 'tox-tiered-menu'
  9512. };
  9513. };
  9514. var markers$1 = function (presets) {
  9515. var menuClasses = classes(presets);
  9516. return {
  9517. backgroundMenu: menuClasses.backgroundMenu,
  9518. selectedMenu: menuClasses.selectedMenu,
  9519. menu: menuClasses.menu,
  9520. selectedItem: menuClasses.selectedItem,
  9521. item: classForPreset(presets)
  9522. };
  9523. };
  9524. var dom$1 = function (hasIcons, columns, presets) {
  9525. var menuClasses = classes(presets);
  9526. return {
  9527. tag: 'div',
  9528. classes: flatten([
  9529. [
  9530. menuClasses.menu,
  9531. 'tox-menu-' + columns + '-column'
  9532. ],
  9533. hasIcons ? [menuClasses.hasIcons] : []
  9534. ])
  9535. };
  9536. };
  9537. var components$1 = [Menu.parts.items({})];
  9538. var part = function (hasIcons, columns, presets) {
  9539. var menuClasses = classes(presets);
  9540. var d = {
  9541. tag: 'div',
  9542. classes: flatten([[menuClasses.tieredMenu]])
  9543. };
  9544. return {
  9545. dom: d,
  9546. markers: markers$1(presets)
  9547. };
  9548. };
  9549. var chunk$1 = function (rowDom, numColumns) {
  9550. return function (items) {
  9551. var chunks = chunk(items, numColumns);
  9552. return map(chunks, function (c) {
  9553. return {
  9554. dom: rowDom,
  9555. components: c
  9556. };
  9557. });
  9558. };
  9559. };
  9560. var forSwatch = function (columns) {
  9561. return {
  9562. dom: {
  9563. tag: 'div',
  9564. classes: [
  9565. 'tox-menu',
  9566. 'tox-swatches-menu'
  9567. ]
  9568. },
  9569. components: [{
  9570. dom: {
  9571. tag: 'div',
  9572. classes: ['tox-swatches']
  9573. },
  9574. components: [Menu.parts.items({
  9575. preprocess: columns !== 'auto' ? chunk$1({
  9576. tag: 'div',
  9577. classes: ['tox-swatches__row']
  9578. }, columns) : identity
  9579. })]
  9580. }]
  9581. };
  9582. };
  9583. var forToolbar = function (columns) {
  9584. return {
  9585. dom: {
  9586. tag: 'div',
  9587. classes: [
  9588. 'tox-menu',
  9589. 'tox-collection',
  9590. 'tox-collection--toolbar',
  9591. 'tox-collection--toolbar-lg'
  9592. ]
  9593. },
  9594. components: [Menu.parts.items({
  9595. preprocess: chunk$1({
  9596. tag: 'div',
  9597. classes: ['tox-collection__group']
  9598. }, columns)
  9599. })]
  9600. };
  9601. };
  9602. var preprocessCollection = function (items, isSeparator) {
  9603. var allSplits = [];
  9604. var currentSplit = [];
  9605. each(items, function (item, i) {
  9606. if (isSeparator(item, i)) {
  9607. if (currentSplit.length > 0) {
  9608. allSplits.push(currentSplit);
  9609. }
  9610. currentSplit = [];
  9611. if (has(item.dom, 'innerHtml')) {
  9612. currentSplit.push(item);
  9613. }
  9614. } else {
  9615. currentSplit.push(item);
  9616. }
  9617. });
  9618. if (currentSplit.length > 0) {
  9619. allSplits.push(currentSplit);
  9620. }
  9621. return map(allSplits, function (s) {
  9622. return {
  9623. dom: {
  9624. tag: 'div',
  9625. classes: ['tox-collection__group']
  9626. },
  9627. components: s
  9628. };
  9629. });
  9630. };
  9631. var forCollection = function (columns, initItems, _hasIcons) {
  9632. return {
  9633. dom: {
  9634. tag: 'div',
  9635. classes: [
  9636. 'tox-menu',
  9637. 'tox-collection'
  9638. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  9639. },
  9640. components: [Menu.parts.items({
  9641. preprocess: function (items) {
  9642. if (columns !== 'auto' && columns > 1) {
  9643. return chunk$1({
  9644. tag: 'div',
  9645. classes: ['tox-collection__group']
  9646. }, columns)(items);
  9647. } else {
  9648. return preprocessCollection(items, function (_item, i) {
  9649. return initItems[i].type === 'separator';
  9650. });
  9651. }
  9652. }
  9653. })]
  9654. };
  9655. };
  9656. var forHorizontalCollection = function (initItems, _hasIcons) {
  9657. return {
  9658. dom: {
  9659. tag: 'div',
  9660. classes: [
  9661. 'tox-collection',
  9662. 'tox-collection--horizontal'
  9663. ]
  9664. },
  9665. components: [Menu.parts.items({
  9666. preprocess: function (items) {
  9667. return preprocessCollection(items, function (_item, i) {
  9668. return initItems[i].type === 'separator';
  9669. });
  9670. }
  9671. })]
  9672. };
  9673. };
  9674. var menuHasIcons = function (xs) {
  9675. return exists(xs, function (item) {
  9676. return 'icon' in item && item.icon !== undefined;
  9677. });
  9678. };
  9679. var handleError = function (error) {
  9680. console.error(formatError(error));
  9681. console.log(error);
  9682. return Optional.none();
  9683. };
  9684. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  9685. var structure = forHorizontalCollection(items);
  9686. return {
  9687. value: value,
  9688. dom: structure.dom,
  9689. components: structure.components,
  9690. items: items
  9691. };
  9692. };
  9693. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  9694. if (presets === 'color') {
  9695. var structure = forSwatch(columns);
  9696. return {
  9697. value: value,
  9698. dom: structure.dom,
  9699. components: structure.components,
  9700. items: items
  9701. };
  9702. }
  9703. if (presets === 'normal' && columns === 'auto') {
  9704. var structure = forCollection(columns, items);
  9705. return {
  9706. value: value,
  9707. dom: structure.dom,
  9708. components: structure.components,
  9709. items: items
  9710. };
  9711. }
  9712. if (presets === 'normal' && columns === 1) {
  9713. var structure = forCollection(1, items);
  9714. return {
  9715. value: value,
  9716. dom: structure.dom,
  9717. components: structure.components,
  9718. items: items
  9719. };
  9720. }
  9721. if (presets === 'normal') {
  9722. var structure = forCollection(columns, items);
  9723. return {
  9724. value: value,
  9725. dom: structure.dom,
  9726. components: structure.components,
  9727. items: items
  9728. };
  9729. }
  9730. if (presets === 'listpreview' && columns !== 'auto') {
  9731. var structure = forToolbar(columns);
  9732. return {
  9733. value: value,
  9734. dom: structure.dom,
  9735. components: structure.components,
  9736. items: items
  9737. };
  9738. }
  9739. return {
  9740. value: value,
  9741. dom: dom$1(hasIcons, columns, presets),
  9742. components: components$1,
  9743. items: items
  9744. };
  9745. };
  9746. var commonMenuItemFields = [
  9747. defaultedBoolean('disabled', false),
  9748. optionString('text'),
  9749. optionString('shortcut'),
  9750. field('value', 'value', defaultedThunk(function () {
  9751. return generate$1('menuitem-value');
  9752. }), anyValue$1()),
  9753. defaulted$1('meta', {})
  9754. ];
  9755. var choiceMenuItemSchema = objOf([
  9756. strictString('type'),
  9757. defaultedBoolean('active', false),
  9758. optionString('icon')
  9759. ].concat(commonMenuItemFields));
  9760. var createChoiceMenuItem = function (spec) {
  9761. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  9762. };
  9763. var fancyTypes = [
  9764. 'inserttable',
  9765. 'colorswatch'
  9766. ];
  9767. var fancyMenuItemSchema = objOf([
  9768. strictString('type'),
  9769. strictStringEnum('fancytype', fancyTypes),
  9770. defaultedFunction('onAction', noop)
  9771. ]);
  9772. var createFancyMenuItem = function (spec) {
  9773. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  9774. };
  9775. var menuItemSchema = objOf([
  9776. strictString('type'),
  9777. defaultedFunction('onSetup', function () {
  9778. return noop;
  9779. }),
  9780. defaultedFunction('onAction', noop),
  9781. optionString('icon')
  9782. ].concat(commonMenuItemFields));
  9783. var createMenuItem = function (spec) {
  9784. return asRaw('menuitem', menuItemSchema, spec);
  9785. };
  9786. var nestedMenuItemSchema = objOf([
  9787. strictString('type'),
  9788. strictFunction('getSubmenuItems'),
  9789. defaultedFunction('onSetup', function () {
  9790. return noop;
  9791. }),
  9792. optionString('icon')
  9793. ].concat(commonMenuItemFields));
  9794. var createNestedMenuItem = function (spec) {
  9795. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  9796. };
  9797. var toggleMenuItemSchema = objOf([
  9798. strictString('type'),
  9799. optionString('icon'),
  9800. defaultedBoolean('active', false),
  9801. defaultedFunction('onSetup', function () {
  9802. return noop;
  9803. }),
  9804. strictFunction('onAction')
  9805. ].concat(commonMenuItemFields));
  9806. var createToggleMenuItem = function (spec) {
  9807. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  9808. };
  9809. var detectSize = function (comp, margin, selectorClass) {
  9810. var descendants$1 = descendants(comp.element, '.' + selectorClass);
  9811. if (descendants$1.length > 0) {
  9812. var columnLength = findIndex(descendants$1, function (c) {
  9813. var thisTop = c.dom.getBoundingClientRect().top;
  9814. var cTop = descendants$1[0].dom.getBoundingClientRect().top;
  9815. return Math.abs(thisTop - cTop) > margin;
  9816. }).getOr(descendants$1.length);
  9817. return Optional.some({
  9818. numColumns: columnLength,
  9819. numRows: Math.ceil(descendants$1.length / columnLength)
  9820. });
  9821. } else {
  9822. return Optional.none();
  9823. }
  9824. };
  9825. var namedEvents = function (name, handlers) {
  9826. return derive$1([config(name, handlers)]);
  9827. };
  9828. var unnamedEvents = function (handlers) {
  9829. return namedEvents(generate$1('unnamed-events'), handlers);
  9830. };
  9831. var SimpleBehaviours = {
  9832. namedEvents: namedEvents,
  9833. unnamedEvents: unnamedEvents
  9834. };
  9835. var TooltippingSchema = [
  9836. strict$1('lazySink'),
  9837. strict$1('tooltipDom'),
  9838. defaulted$1('exclusive', true),
  9839. defaulted$1('tooltipComponents', []),
  9840. defaulted$1('delay', 300),
  9841. defaultedStringEnum('mode', 'normal', [
  9842. 'normal',
  9843. 'follow-highlight'
  9844. ]),
  9845. defaulted$1('anchor', function (comp) {
  9846. return {
  9847. anchor: 'hotspot',
  9848. hotspot: comp,
  9849. layouts: {
  9850. onLtr: constant([
  9851. south$1,
  9852. north$1,
  9853. southeast$1,
  9854. northeast$1,
  9855. southwest$1,
  9856. northwest$1
  9857. ]),
  9858. onRtl: constant([
  9859. south$1,
  9860. north$1,
  9861. southeast$1,
  9862. northeast$1,
  9863. southwest$1,
  9864. northwest$1
  9865. ])
  9866. }
  9867. };
  9868. }),
  9869. onHandler('onHide'),
  9870. onHandler('onShow')
  9871. ];
  9872. var init$4 = function () {
  9873. var timer = Cell(Optional.none());
  9874. var popup = Cell(Optional.none());
  9875. var getTooltip = function () {
  9876. return popup.get();
  9877. };
  9878. var setTooltip = function (comp) {
  9879. popup.set(Optional.some(comp));
  9880. };
  9881. var clearTooltip = function () {
  9882. popup.set(Optional.none());
  9883. };
  9884. var clearTimer = function () {
  9885. timer.get().each(function (t) {
  9886. clearTimeout(t);
  9887. });
  9888. };
  9889. var resetTimer = function (f, delay) {
  9890. clearTimer();
  9891. timer.set(Optional.some(setTimeout(function () {
  9892. f();
  9893. }, delay)));
  9894. };
  9895. var isShowing = function () {
  9896. return popup.get().isSome();
  9897. };
  9898. var readState = constant('not-implemented');
  9899. return nu$5({
  9900. getTooltip: getTooltip,
  9901. isShowing: isShowing,
  9902. setTooltip: setTooltip,
  9903. clearTooltip: clearTooltip,
  9904. clearTimer: clearTimer,
  9905. resetTimer: resetTimer,
  9906. readState: readState
  9907. });
  9908. };
  9909. var TooltippingState = /*#__PURE__*/Object.freeze({
  9910. __proto__: null,
  9911. init: init$4
  9912. });
  9913. var ExclusivityChannel = generate$1('tooltip.exclusive');
  9914. var ShowTooltipEvent = generate$1('tooltip.show');
  9915. var HideTooltipEvent = generate$1('tooltip.hide');
  9916. var hideAllExclusive = function (component, _tConfig, _tState) {
  9917. component.getSystem().broadcastOn([ExclusivityChannel], {});
  9918. };
  9919. var setComponents = function (component, tConfig, tState, specs) {
  9920. tState.getTooltip().each(function (tooltip) {
  9921. if (tooltip.getSystem().isConnected()) {
  9922. Replacing.set(tooltip, specs);
  9923. }
  9924. });
  9925. };
  9926. var TooltippingApis = /*#__PURE__*/Object.freeze({
  9927. __proto__: null,
  9928. hideAllExclusive: hideAllExclusive,
  9929. setComponents: setComponents
  9930. });
  9931. var events$8 = function (tooltipConfig, state) {
  9932. var hide = function (comp) {
  9933. state.getTooltip().each(function (p) {
  9934. detach(p);
  9935. tooltipConfig.onHide(comp, p);
  9936. state.clearTooltip();
  9937. });
  9938. state.clearTimer();
  9939. };
  9940. var show = function (comp) {
  9941. if (!state.isShowing()) {
  9942. hideAllExclusive(comp);
  9943. var sink = tooltipConfig.lazySink(comp).getOrDie();
  9944. var popup = comp.getSystem().build({
  9945. dom: tooltipConfig.tooltipDom,
  9946. components: tooltipConfig.tooltipComponents,
  9947. events: derive(tooltipConfig.mode === 'normal' ? [
  9948. run(mouseover(), function (_) {
  9949. emit(comp, ShowTooltipEvent);
  9950. }),
  9951. run(mouseout(), function (_) {
  9952. emit(comp, HideTooltipEvent);
  9953. })
  9954. ] : []),
  9955. behaviours: derive$1([Replacing.config({})])
  9956. });
  9957. state.setTooltip(popup);
  9958. attach$1(sink, popup);
  9959. tooltipConfig.onShow(comp, popup);
  9960. Positioning.position(sink, tooltipConfig.anchor(comp), popup);
  9961. }
  9962. };
  9963. return derive(flatten([
  9964. [
  9965. run(ShowTooltipEvent, function (comp) {
  9966. state.resetTimer(function () {
  9967. show(comp);
  9968. }, tooltipConfig.delay);
  9969. }),
  9970. run(HideTooltipEvent, function (comp) {
  9971. state.resetTimer(function () {
  9972. hide(comp);
  9973. }, tooltipConfig.delay);
  9974. }),
  9975. run(receive(), function (comp, message) {
  9976. var receivingData = message;
  9977. if (!receivingData.universal) {
  9978. if (contains(receivingData.channels, ExclusivityChannel)) {
  9979. hide(comp);
  9980. }
  9981. }
  9982. }),
  9983. runOnDetached(function (comp) {
  9984. hide(comp);
  9985. })
  9986. ],
  9987. tooltipConfig.mode === 'normal' ? [
  9988. run(focusin(), function (comp) {
  9989. emit(comp, ShowTooltipEvent);
  9990. }),
  9991. run(postBlur(), function (comp) {
  9992. emit(comp, HideTooltipEvent);
  9993. }),
  9994. run(mouseover(), function (comp) {
  9995. emit(comp, ShowTooltipEvent);
  9996. }),
  9997. run(mouseout(), function (comp) {
  9998. emit(comp, HideTooltipEvent);
  9999. })
  10000. ] : [
  10001. run(highlight(), function (comp, _se) {
  10002. emit(comp, ShowTooltipEvent);
  10003. }),
  10004. run(dehighlight(), function (comp) {
  10005. emit(comp, HideTooltipEvent);
  10006. })
  10007. ]
  10008. ]));
  10009. };
  10010. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  10011. __proto__: null,
  10012. events: events$8
  10013. });
  10014. var Tooltipping = create$1({
  10015. fields: TooltippingSchema,
  10016. name: 'tooltipping',
  10017. active: ActiveTooltipping,
  10018. state: TooltippingState,
  10019. apis: TooltippingApis
  10020. });
  10021. var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  10022. var global$6 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  10023. var nativeDisabled = [
  10024. 'input',
  10025. 'button',
  10026. 'textarea',
  10027. 'select'
  10028. ];
  10029. var onLoad$5 = function (component, disableConfig, disableState) {
  10030. var f = disableConfig.disabled() ? disable : enable;
  10031. f(component, disableConfig);
  10032. };
  10033. var hasNative = function (component, config) {
  10034. return config.useNative === true && contains(nativeDisabled, name(component.element));
  10035. };
  10036. var nativeIsDisabled = function (component) {
  10037. return has$1(component.element, 'disabled');
  10038. };
  10039. var nativeDisable = function (component) {
  10040. set$1(component.element, 'disabled', 'disabled');
  10041. };
  10042. var nativeEnable = function (component) {
  10043. remove$1(component.element, 'disabled');
  10044. };
  10045. var ariaIsDisabled = function (component) {
  10046. return get$2(component.element, 'aria-disabled') === 'true';
  10047. };
  10048. var ariaDisable = function (component) {
  10049. set$1(component.element, 'aria-disabled', 'true');
  10050. };
  10051. var ariaEnable = function (component) {
  10052. set$1(component.element, 'aria-disabled', 'false');
  10053. };
  10054. var disable = function (component, disableConfig, _disableState) {
  10055. disableConfig.disableClass.each(function (disableClass) {
  10056. add$2(component.element, disableClass);
  10057. });
  10058. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  10059. f(component);
  10060. disableConfig.onDisabled(component);
  10061. };
  10062. var enable = function (component, disableConfig, _disableState) {
  10063. disableConfig.disableClass.each(function (disableClass) {
  10064. remove$4(component.element, disableClass);
  10065. });
  10066. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  10067. f(component);
  10068. disableConfig.onEnabled(component);
  10069. };
  10070. var isDisabled = function (component, disableConfig) {
  10071. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  10072. };
  10073. var set$7 = function (component, disableConfig, disableState, disabled) {
  10074. var f = disabled ? disable : enable;
  10075. f(component, disableConfig);
  10076. };
  10077. var DisableApis = /*#__PURE__*/Object.freeze({
  10078. __proto__: null,
  10079. enable: enable,
  10080. disable: disable,
  10081. isDisabled: isDisabled,
  10082. onLoad: onLoad$5,
  10083. set: set$7
  10084. });
  10085. var exhibit$3 = function (base, disableConfig) {
  10086. return nu$6({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  10087. };
  10088. var events$9 = function (disableConfig, disableState) {
  10089. return derive([
  10090. abort(execute(), function (component, _simulatedEvent) {
  10091. return isDisabled(component, disableConfig);
  10092. }),
  10093. loadEvent(disableConfig, disableState, onLoad$5)
  10094. ]);
  10095. };
  10096. var ActiveDisable = /*#__PURE__*/Object.freeze({
  10097. __proto__: null,
  10098. exhibit: exhibit$3,
  10099. events: events$9
  10100. });
  10101. var DisableSchema = [
  10102. defaultedFunction('disabled', never),
  10103. defaulted$1('useNative', true),
  10104. option('disableClass'),
  10105. onHandler('onDisabled'),
  10106. onHandler('onEnabled')
  10107. ];
  10108. var Disabling = create$1({
  10109. fields: DisableSchema,
  10110. name: 'disabling',
  10111. active: ActiveDisable,
  10112. apis: DisableApis
  10113. });
  10114. var global$7 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  10115. var getSkinUrl = function (editor) {
  10116. var skin = editor.getParam('skin');
  10117. var skinUrl = editor.getParam('skin_url');
  10118. if (skin !== false) {
  10119. var skinName = skin ? skin : 'oxide';
  10120. if (skinUrl) {
  10121. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  10122. } else {
  10123. skinUrl = global$7.baseURL + '/skins/ui/' + skinName;
  10124. }
  10125. }
  10126. return skinUrl;
  10127. };
  10128. var isReadOnly = function (editor) {
  10129. return editor.getParam('readonly', false, 'boolean');
  10130. };
  10131. var isSkinDisabled = function (editor) {
  10132. return editor.getParam('skin') === false;
  10133. };
  10134. var getHeightSetting = function (editor) {
  10135. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  10136. };
  10137. var getWidthSetting = function (editor) {
  10138. return editor.getParam('width', global$5.DOM.getStyle(editor.getElement(), 'width'));
  10139. };
  10140. var getMinWidthSetting = function (editor) {
  10141. return Optional.from(editor.getParam('min_width')).filter(isNumber);
  10142. };
  10143. var getMinHeightSetting = function (editor) {
  10144. return Optional.from(editor.getParam('min_height')).filter(isNumber);
  10145. };
  10146. var getMaxWidthSetting = function (editor) {
  10147. return Optional.from(editor.getParam('max_width')).filter(isNumber);
  10148. };
  10149. var getMaxHeightSetting = function (editor) {
  10150. return Optional.from(editor.getParam('max_height')).filter(isNumber);
  10151. };
  10152. var getUserStyleFormats = function (editor) {
  10153. return Optional.from(editor.getParam('style_formats')).filter(isArray);
  10154. };
  10155. var isMergeStyleFormats = function (editor) {
  10156. return editor.getParam('style_formats_merge', false, 'boolean');
  10157. };
  10158. var getLineHeightFormats = function (editor) {
  10159. return editor.getParam('lineheight_formats', '1 1.1 1.2 1.3 1.4 1.5 2', 'string').split(' ');
  10160. };
  10161. var getRemovedMenuItems = function (editor) {
  10162. return editor.getParam('removed_menuitems', '');
  10163. };
  10164. var isMenubarEnabled = function (editor) {
  10165. return editor.getParam('menubar', true, 'boolean') !== false;
  10166. };
  10167. var isToolbarEnabled = function (editor) {
  10168. var toolbar = editor.getParam('toolbar', true);
  10169. var isToolbarTrue = toolbar === true;
  10170. var isToolbarString = isString(toolbar);
  10171. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  10172. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  10173. };
  10174. var getMultipleToolbarsSetting = function (editor) {
  10175. var toolbars = range(9, function (num) {
  10176. return editor.getParam('toolbar' + (num + 1), false, 'string');
  10177. });
  10178. var toolbarArray = filter(toolbars, function (toolbar) {
  10179. return typeof toolbar === 'string';
  10180. });
  10181. return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
  10182. };
  10183. var isMultipleToolbars = function (editor) {
  10184. return getMultipleToolbarsSetting(editor).fold(function () {
  10185. var toolbar = editor.getParam('toolbar', [], 'string[]');
  10186. return toolbar.length > 0;
  10187. }, function () {
  10188. return true;
  10189. });
  10190. };
  10191. var ToolbarMode;
  10192. (function (ToolbarMode) {
  10193. ToolbarMode['default'] = 'wrap';
  10194. ToolbarMode['floating'] = 'floating';
  10195. ToolbarMode['sliding'] = 'sliding';
  10196. ToolbarMode['scrolling'] = 'scrolling';
  10197. }(ToolbarMode || (ToolbarMode = {})));
  10198. var getToolbarMode = function (editor) {
  10199. return editor.getParam('toolbar_mode', '', 'string');
  10200. };
  10201. var ToolbarLocation;
  10202. (function (ToolbarLocation) {
  10203. ToolbarLocation['auto'] = 'auto';
  10204. ToolbarLocation['top'] = 'top';
  10205. ToolbarLocation['bottom'] = 'bottom';
  10206. }(ToolbarLocation || (ToolbarLocation = {})));
  10207. var getToolbarGroups = function (editor) {
  10208. return editor.getParam('toolbar_groups', {}, 'object');
  10209. };
  10210. var getToolbarLocation = function (editor) {
  10211. return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string');
  10212. };
  10213. var isToolbarLocationBottom = function (editor) {
  10214. return getToolbarLocation(editor) === ToolbarLocation.bottom;
  10215. };
  10216. var fixedContainerSelector = function (editor) {
  10217. return editor.getParam('fixed_toolbar_container', '', 'string');
  10218. };
  10219. var isToolbarPersist = function (editor) {
  10220. return editor.getParam('toolbar_persist', false, 'boolean');
  10221. };
  10222. var fixedContainerElement = function (editor) {
  10223. var selector = fixedContainerSelector(editor);
  10224. return selector.length > 0 && editor.inline ? descendant$1(body(), selector) : Optional.none();
  10225. };
  10226. var useFixedContainer = function (editor) {
  10227. return editor.inline && fixedContainerElement(editor).isSome();
  10228. };
  10229. var getUiContainer = function (editor) {
  10230. var fixedContainer = fixedContainerElement(editor);
  10231. return fixedContainer.getOrThunk(function () {
  10232. return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
  10233. });
  10234. };
  10235. var isDistractionFree = function (editor) {
  10236. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  10237. };
  10238. var isStickyToolbar = function (editor) {
  10239. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  10240. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  10241. };
  10242. var isDraggableModal = function (editor) {
  10243. return editor.getParam('draggable_modal', false, 'boolean');
  10244. };
  10245. var getMenus = function (editor) {
  10246. var menu = editor.getParam('menu');
  10247. if (menu) {
  10248. return map$2(menu, function (menu) {
  10249. return __assign(__assign({}, menu), { items: menu.items });
  10250. });
  10251. } else {
  10252. return {};
  10253. }
  10254. };
  10255. var getMenubar = function (editor) {
  10256. return editor.getParam('menubar');
  10257. };
  10258. var getToolbar = function (editor) {
  10259. return editor.getParam('toolbar', true);
  10260. };
  10261. var getFilePickerCallback = function (editor) {
  10262. return editor.getParam('file_picker_callback');
  10263. };
  10264. var getFilePickerTypes = function (editor) {
  10265. return editor.getParam('file_picker_types');
  10266. };
  10267. var getFileBrowserCallbackTypes = function (editor) {
  10268. return editor.getParam('file_browser_callback_types');
  10269. };
  10270. var noTypeaheadUrls = function (editor) {
  10271. return editor.getParam('typeahead_urls') === false;
  10272. };
  10273. var getAnchorTop = function (editor) {
  10274. return editor.getParam('anchor_top', '#top');
  10275. };
  10276. var getAnchorBottom = function (editor) {
  10277. return editor.getParam('anchor_bottom', '#bottom');
  10278. };
  10279. var getFilePickerValidatorHandler = function (editor) {
  10280. var handler = editor.getParam('file_picker_validator_handler', undefined, 'function');
  10281. if (handler === undefined) {
  10282. return editor.getParam('filepicker_validator_handler', undefined, 'function');
  10283. } else {
  10284. return handler;
  10285. }
  10286. };
  10287. var ReadOnlyChannel = 'silver.readonly';
  10288. var ReadOnlyDataSchema = objOf([strictBoolean('readonly')]);
  10289. var broadcastReadonly = function (uiComponents, readonly) {
  10290. var outerContainer = uiComponents.outerContainer;
  10291. var target = outerContainer.element;
  10292. if (readonly) {
  10293. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  10294. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  10295. }
  10296. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10297. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10298. };
  10299. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  10300. editor.on('init', function () {
  10301. if (editor.mode.isReadOnly()) {
  10302. broadcastReadonly(uiComponents, true);
  10303. }
  10304. });
  10305. editor.on('SwitchMode', function () {
  10306. return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
  10307. });
  10308. if (isReadOnly(editor)) {
  10309. editor.setMode('readonly');
  10310. }
  10311. };
  10312. var receivingConfig = function () {
  10313. var _a;
  10314. return Receiving.config({
  10315. channels: (_a = {}, _a[ReadOnlyChannel] = {
  10316. schema: ReadOnlyDataSchema,
  10317. onReceive: function (comp, data) {
  10318. Disabling.set(comp, data.readonly);
  10319. }
  10320. }, _a)
  10321. });
  10322. };
  10323. var item = function (disabled) {
  10324. return Disabling.config({
  10325. disabled: disabled,
  10326. disableClass: 'tox-collection__item--state-disabled'
  10327. });
  10328. };
  10329. var button = function (disabled) {
  10330. return Disabling.config({ disabled: disabled });
  10331. };
  10332. var splitButton = function (disabled) {
  10333. return Disabling.config({
  10334. disabled: disabled,
  10335. disableClass: 'tox-tbtn--disabled'
  10336. });
  10337. };
  10338. var toolbarButton = function (disabled) {
  10339. return Disabling.config({
  10340. disabled: disabled,
  10341. disableClass: 'tox-tbtn--disabled',
  10342. useNative: false
  10343. });
  10344. };
  10345. var DisablingConfigs = {
  10346. item: item,
  10347. button: button,
  10348. splitButton: splitButton,
  10349. toolbarButton: toolbarButton
  10350. };
  10351. var runWithApi = function (info, comp) {
  10352. var api = info.getApi(comp);
  10353. return function (f) {
  10354. f(api);
  10355. };
  10356. };
  10357. var onControlAttached = function (info, editorOffCell) {
  10358. return runOnAttached(function (comp) {
  10359. var run = runWithApi(info, comp);
  10360. run(function (api) {
  10361. var onDestroy = info.onSetup(api);
  10362. if (onDestroy !== null && onDestroy !== undefined) {
  10363. editorOffCell.set(onDestroy);
  10364. }
  10365. });
  10366. });
  10367. };
  10368. var onControlDetached = function (getApi, editorOffCell) {
  10369. return runOnDetached(function (comp) {
  10370. return runWithApi(getApi, comp)(editorOffCell.get());
  10371. });
  10372. };
  10373. var _a;
  10374. var onMenuItemExecute = function (info, itemResponse) {
  10375. return runOnExecute(function (comp, simulatedEvent) {
  10376. runWithApi(info, comp)(info.onAction);
  10377. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10378. emit(comp, sandboxClose());
  10379. simulatedEvent.stop();
  10380. }
  10381. });
  10382. };
  10383. var menuItemEventOrder = (_a = {}, _a[execute()] = [
  10384. 'disabling',
  10385. 'alloy.base.behaviour',
  10386. 'toggling',
  10387. 'item-events'
  10388. ], _a);
  10389. var componentRenderPipeline = function (xs) {
  10390. return bind(xs, function (o) {
  10391. return o.toArray();
  10392. });
  10393. };
  10394. var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) {
  10395. var editorOffCell = Cell(noop);
  10396. return {
  10397. type: 'item',
  10398. dom: structure.dom,
  10399. components: componentRenderPipeline(structure.optComponents),
  10400. data: spec.data,
  10401. eventOrder: menuItemEventOrder,
  10402. hasSubmenu: spec.triggersSubmenu,
  10403. itemBehaviours: derive$1([
  10404. config('item-events', [
  10405. onMenuItemExecute(spec, itemResponse),
  10406. onControlAttached(spec, editorOffCell),
  10407. onControlDetached(spec, editorOffCell)
  10408. ]),
  10409. DisablingConfigs.item(function () {
  10410. return spec.disabled || providersbackstage.isReadOnly();
  10411. }),
  10412. receivingConfig(),
  10413. Replacing.config({})
  10414. ].concat(spec.itemBehaviours))
  10415. };
  10416. };
  10417. var buildData = function (source) {
  10418. return {
  10419. value: source.value,
  10420. meta: __assign({ text: source.text.getOr('') }, source.meta)
  10421. };
  10422. };
  10423. var global$8 = tinymce.util.Tools.resolve('tinymce.Env');
  10424. var convertText = function (source) {
  10425. var mac = {
  10426. alt: '&#x2325;',
  10427. ctrl: '&#x2303;',
  10428. shift: '&#x21E7;',
  10429. meta: '&#x2318;',
  10430. access: '&#x2303;&#x2325;'
  10431. };
  10432. var other = {
  10433. meta: 'Ctrl',
  10434. access: 'Shift+Alt'
  10435. };
  10436. var replace = global$8.mac ? mac : other;
  10437. var shortcut = source.split('+');
  10438. var updated = map(shortcut, function (segment) {
  10439. var search = segment.toLowerCase().trim();
  10440. return has(replace, search) ? replace[search] : segment;
  10441. });
  10442. return global$8.mac ? updated.join('') : updated.join('+');
  10443. };
  10444. var renderIcon = function (iconHtml) {
  10445. return {
  10446. dom: {
  10447. tag: 'div',
  10448. classes: [iconClass],
  10449. innerHtml: iconHtml
  10450. }
  10451. };
  10452. };
  10453. var renderText = function (text$1) {
  10454. return {
  10455. dom: {
  10456. tag: 'div',
  10457. classes: [textClass]
  10458. },
  10459. components: [text(global$6.translate(text$1))]
  10460. };
  10461. };
  10462. var renderHtml = function (html) {
  10463. return {
  10464. dom: {
  10465. tag: 'div',
  10466. classes: [textClass],
  10467. innerHtml: html
  10468. }
  10469. };
  10470. };
  10471. var renderStyledText = function (style, text$1) {
  10472. return {
  10473. dom: {
  10474. tag: 'div',
  10475. classes: [textClass]
  10476. },
  10477. components: [{
  10478. dom: {
  10479. tag: style.tag,
  10480. styles: style.styles
  10481. },
  10482. components: [text(global$6.translate(text$1))]
  10483. }]
  10484. };
  10485. };
  10486. var renderShortcut = function (shortcut) {
  10487. return {
  10488. dom: {
  10489. tag: 'div',
  10490. classes: [accessoryClass],
  10491. innerHtml: convertText(shortcut)
  10492. }
  10493. };
  10494. };
  10495. var renderCheckmark = function (icons) {
  10496. return {
  10497. dom: {
  10498. tag: 'div',
  10499. classes: [checkmarkClass],
  10500. innerHtml: get$d('checkmark', icons)
  10501. }
  10502. };
  10503. };
  10504. var renderSubmenuCaret = function (icons) {
  10505. return {
  10506. dom: {
  10507. tag: 'div',
  10508. classes: [caretClass],
  10509. innerHtml: get$d('chevron-right', icons)
  10510. }
  10511. };
  10512. };
  10513. var renderDownwardsCaret = function (icons) {
  10514. return {
  10515. dom: {
  10516. tag: 'div',
  10517. classes: [caretClass],
  10518. innerHtml: get$d('chevron-down', icons)
  10519. }
  10520. };
  10521. };
  10522. var renderColorStructure = function (itemText, itemValue, iconSvg, providerBackstage) {
  10523. var colorPickerCommand = 'custom';
  10524. var removeColorCommand = 'remove';
  10525. var getDom = function () {
  10526. var common = colorClass;
  10527. var icon = iconSvg.getOr('');
  10528. var attributes = itemText.map(function (text) {
  10529. return { title: providerBackstage.translate(text) };
  10530. }).getOr({});
  10531. var baseDom = {
  10532. tag: 'div',
  10533. attributes: attributes,
  10534. classes: [common]
  10535. };
  10536. if (itemValue === colorPickerCommand) {
  10537. return __assign(__assign({}, baseDom), {
  10538. tag: 'button',
  10539. classes: __spreadArrays(baseDom.classes, ['tox-swatches__picker-btn']),
  10540. innerHtml: icon
  10541. });
  10542. } else if (itemValue === removeColorCommand) {
  10543. return __assign(__assign({}, baseDom), {
  10544. classes: __spreadArrays(baseDom.classes, ['tox-swatch--remove']),
  10545. innerHtml: icon
  10546. });
  10547. } else {
  10548. return __assign(__assign({}, baseDom), {
  10549. attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  10550. styles: { 'background-color': itemValue }
  10551. });
  10552. }
  10553. };
  10554. return {
  10555. dom: getDom(),
  10556. optComponents: []
  10557. };
  10558. };
  10559. var renderNormalItemStructure = function (info, icon, renderIcons, textRender, rtlClass) {
  10560. var leftIcon = renderIcons ? icon.or(Optional.some('')).map(renderIcon) : Optional.none();
  10561. var checkmark = info.checkMark;
  10562. var domTitle = info.ariaLabel.map(function (label) {
  10563. return { attributes: { title: global$6.translate(label) } };
  10564. }).getOr({});
  10565. var dom = __assign({
  10566. tag: 'div',
  10567. classes: [
  10568. navClass,
  10569. selectableClass
  10570. ].concat(rtlClass ? [iconClassRtl] : [])
  10571. }, domTitle);
  10572. var content = info.htmlContent.fold(function () {
  10573. return info.textContent.map(textRender);
  10574. }, function (html) {
  10575. return Optional.some(renderHtml(html));
  10576. });
  10577. var menuItem = {
  10578. dom: dom,
  10579. optComponents: [
  10580. leftIcon,
  10581. content,
  10582. info.shortcutContent.map(renderShortcut),
  10583. checkmark,
  10584. info.caret
  10585. ]
  10586. };
  10587. return menuItem;
  10588. };
  10589. var rtlIcon = [
  10590. 'list-num-default',
  10591. 'list-num-lower-alpha',
  10592. 'list-num-lower-greek',
  10593. 'list-num-lower-roman',
  10594. 'list-num-upper-alpha',
  10595. 'list-num-upper-roman'
  10596. ];
  10597. var rtlTransform = [
  10598. 'list-bull-circle',
  10599. 'list-bull-default',
  10600. 'list-bull-square'
  10601. ];
  10602. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  10603. if (fallbackIcon === void 0) {
  10604. fallbackIcon = Optional.none();
  10605. }
  10606. var getIconName = function (iconName) {
  10607. return iconName.map(function (name) {
  10608. return global$6.isRtl() && contains(rtlIcon, name) ? name + '-rtl' : name;
  10609. });
  10610. };
  10611. var needRtlClass = global$6.isRtl() && info.iconContent.exists(function (name) {
  10612. return contains(rtlTransform, name);
  10613. });
  10614. var icon = getIconName(info.iconContent).map(function (iconName) {
  10615. return getOr(iconName, providersBackstage.icons, fallbackIcon);
  10616. });
  10617. var textRender = Optional.from(info.meta).fold(function () {
  10618. return renderText;
  10619. }, function (meta) {
  10620. return has(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  10621. });
  10622. if (info.presets === 'color') {
  10623. return renderColorStructure(info.ariaLabel, info.value, icon, providersBackstage);
  10624. } else {
  10625. return renderNormalItemStructure(info, icon, renderIcons, textRender, needRtlClass);
  10626. }
  10627. };
  10628. var tooltipBehaviour = function (meta, sharedBackstage) {
  10629. return get(meta, 'tooltipWorker').map(function (tooltipWorker) {
  10630. return [Tooltipping.config({
  10631. lazySink: sharedBackstage.getSink,
  10632. tooltipDom: {
  10633. tag: 'div',
  10634. classes: ['tox-tooltip-worker-container']
  10635. },
  10636. tooltipComponents: [],
  10637. anchor: function (comp) {
  10638. return {
  10639. anchor: 'submenu',
  10640. item: comp,
  10641. overrides: { maxHeightFunction: expandable }
  10642. };
  10643. },
  10644. mode: 'follow-highlight',
  10645. onShow: function (component, _tooltip) {
  10646. tooltipWorker(function (elm) {
  10647. Tooltipping.setComponents(component, [external({ element: SugarElement.fromDom(elm) })]);
  10648. });
  10649. }
  10650. })];
  10651. }).getOr([]);
  10652. };
  10653. var escapeRegExp = function (text) {
  10654. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10655. };
  10656. var encodeText = function (text) {
  10657. return global$5.DOM.encode(text);
  10658. };
  10659. var replaceText = function (text, matchText) {
  10660. var translated = global$6.translate(text);
  10661. var encoded = encodeText(translated);
  10662. if (matchText.length > 0) {
  10663. var escapedMatchRegex = new RegExp(escapeRegExp(matchText), 'gi');
  10664. return encoded.replace(escapedMatchRegex, function (match) {
  10665. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  10666. });
  10667. } else {
  10668. return encoded;
  10669. }
  10670. };
  10671. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  10672. if (renderIcons === void 0) {
  10673. renderIcons = true;
  10674. }
  10675. var structure = renderItemStructure({
  10676. presets: presets,
  10677. textContent: Optional.none(),
  10678. htmlContent: useText ? spec.text.map(function (text) {
  10679. return replaceText(text, matchText);
  10680. }) : Optional.none(),
  10681. ariaLabel: spec.text,
  10682. iconContent: spec.icon,
  10683. shortcutContent: Optional.none(),
  10684. checkMark: Optional.none(),
  10685. caret: Optional.none(),
  10686. value: spec.value
  10687. }, sharedBackstage.providers, renderIcons, spec.icon);
  10688. return renderCommonItem({
  10689. data: buildData(spec),
  10690. disabled: spec.disabled,
  10691. getApi: function () {
  10692. return {};
  10693. },
  10694. onAction: function (_api) {
  10695. return onItemValueHandler(spec.value, spec.meta);
  10696. },
  10697. onSetup: function () {
  10698. return function () {
  10699. };
  10700. },
  10701. triggersSubmenu: false,
  10702. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  10703. }, structure, itemResponse, sharedBackstage.providers);
  10704. };
  10705. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
  10706. if (renderIcons === void 0) {
  10707. renderIcons = true;
  10708. }
  10709. var getApi = function (component) {
  10710. return {
  10711. setActive: function (state) {
  10712. Toggling.set(component, state);
  10713. },
  10714. isActive: function () {
  10715. return Toggling.isOn(component);
  10716. },
  10717. isDisabled: function () {
  10718. return Disabling.isDisabled(component);
  10719. },
  10720. setDisabled: function (state) {
  10721. return Disabling.set(component, state);
  10722. }
  10723. };
  10724. };
  10725. var structure = renderItemStructure({
  10726. presets: presets,
  10727. textContent: useText ? spec.text : Optional.none(),
  10728. htmlContent: Optional.none(),
  10729. ariaLabel: spec.text,
  10730. iconContent: spec.icon,
  10731. shortcutContent: useText ? spec.shortcut : Optional.none(),
  10732. checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
  10733. caret: Optional.none(),
  10734. value: spec.value
  10735. }, providersBackstage, renderIcons);
  10736. return deepMerge(renderCommonItem({
  10737. data: buildData(spec),
  10738. disabled: spec.disabled,
  10739. getApi: getApi,
  10740. onAction: function (_api) {
  10741. return onItemValueHandler(spec.value);
  10742. },
  10743. onSetup: function (api) {
  10744. api.setActive(isSelected);
  10745. return function () {
  10746. };
  10747. },
  10748. triggersSubmenu: false,
  10749. itemBehaviours: []
  10750. }, structure, itemResponse, providersBackstage), {
  10751. toggling: {
  10752. toggleClass: tickedClass,
  10753. toggleOnExecute: false,
  10754. selected: spec.active
  10755. }
  10756. });
  10757. };
  10758. var parts$2 = generate$4(owner$2(), parts());
  10759. var hexColour = function (value) {
  10760. return { value: value };
  10761. };
  10762. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  10763. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  10764. var isHexString = function (hex) {
  10765. return shorthandRegex.test(hex) || longformRegex.test(hex);
  10766. };
  10767. var getLongForm = function (hex) {
  10768. var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) {
  10769. return r + r + g + g + b + b;
  10770. });
  10771. return { value: hexString };
  10772. };
  10773. var extractValues = function (hex) {
  10774. var longForm = getLongForm(hex);
  10775. var splitForm = longformRegex.exec(longForm.value);
  10776. return splitForm === null ? [
  10777. 'FFFFFF',
  10778. 'FF',
  10779. 'FF',
  10780. 'FF'
  10781. ] : splitForm;
  10782. };
  10783. var toHex = function (component) {
  10784. var hex = component.toString(16);
  10785. return hex.length === 1 ? '0' + hex : hex;
  10786. };
  10787. var fromRgba = function (rgbaColour) {
  10788. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  10789. return hexColour(value);
  10790. };
  10791. var min = Math.min;
  10792. var max = Math.max;
  10793. var round = Math.round;
  10794. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  10795. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  10796. var rgbaColour = function (red, green, blue, alpha) {
  10797. return {
  10798. red: red,
  10799. green: green,
  10800. blue: blue,
  10801. alpha: alpha
  10802. };
  10803. };
  10804. var isRgbaComponent = function (value) {
  10805. var num = parseInt(value, 10);
  10806. return num.toString() === value && num >= 0 && num <= 255;
  10807. };
  10808. var fromHsv = function (hsv) {
  10809. var r;
  10810. var g;
  10811. var b;
  10812. var hue = (hsv.hue || 0) % 360;
  10813. var saturation = hsv.saturation / 100;
  10814. var brightness = hsv.value / 100;
  10815. saturation = max(0, min(saturation, 1));
  10816. brightness = max(0, min(brightness, 1));
  10817. if (saturation === 0) {
  10818. r = g = b = round(255 * brightness);
  10819. return rgbaColour(r, g, b, 1);
  10820. }
  10821. var side = hue / 60;
  10822. var chroma = brightness * saturation;
  10823. var x = chroma * (1 - Math.abs(side % 2 - 1));
  10824. var match = brightness - chroma;
  10825. switch (Math.floor(side)) {
  10826. case 0:
  10827. r = chroma;
  10828. g = x;
  10829. b = 0;
  10830. break;
  10831. case 1:
  10832. r = x;
  10833. g = chroma;
  10834. b = 0;
  10835. break;
  10836. case 2:
  10837. r = 0;
  10838. g = chroma;
  10839. b = x;
  10840. break;
  10841. case 3:
  10842. r = 0;
  10843. g = x;
  10844. b = chroma;
  10845. break;
  10846. case 4:
  10847. r = x;
  10848. g = 0;
  10849. b = chroma;
  10850. break;
  10851. case 5:
  10852. r = chroma;
  10853. g = 0;
  10854. b = x;
  10855. break;
  10856. default:
  10857. r = g = b = 0;
  10858. }
  10859. r = round(255 * (r + match));
  10860. g = round(255 * (g + match));
  10861. b = round(255 * (b + match));
  10862. return rgbaColour(r, g, b, 1);
  10863. };
  10864. var fromHex = function (hexColour) {
  10865. var result = extractValues(hexColour);
  10866. var red = parseInt(result[1], 16);
  10867. var green = parseInt(result[2], 16);
  10868. var blue = parseInt(result[3], 16);
  10869. return rgbaColour(red, green, blue, 1);
  10870. };
  10871. var fromStringValues = function (red, green, blue, alpha) {
  10872. var r = parseInt(red, 10);
  10873. var g = parseInt(green, 10);
  10874. var b = parseInt(blue, 10);
  10875. var a = parseFloat(alpha);
  10876. return rgbaColour(r, g, b, a);
  10877. };
  10878. var fromString = function (rgbaString) {
  10879. if (rgbaString === 'transparent') {
  10880. return Optional.some(rgbaColour(0, 0, 0, 0));
  10881. }
  10882. var rgbMatch = rgbRegex.exec(rgbaString);
  10883. if (rgbMatch !== null) {
  10884. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  10885. }
  10886. var rgbaMatch = rgbaRegex.exec(rgbaString);
  10887. if (rgbaMatch !== null) {
  10888. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  10889. }
  10890. return Optional.none();
  10891. };
  10892. var toString = function (rgba) {
  10893. return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')';
  10894. };
  10895. var red = rgbaColour(255, 0, 0, 1);
  10896. var fireSkinLoaded = function (editor) {
  10897. return editor.fire('SkinLoaded');
  10898. };
  10899. var fireSkinLoadError = function (editor, error) {
  10900. return editor.fire('SkinLoadError', error);
  10901. };
  10902. var fireResizeEditor = function (editor) {
  10903. return editor.fire('ResizeEditor');
  10904. };
  10905. var fireResizeContent = function (editor, e) {
  10906. return editor.fire('ResizeContent', e);
  10907. };
  10908. var fireScrollContent = function (editor, e) {
  10909. return editor.fire('ScrollContent', e);
  10910. };
  10911. var fireTextColorChange = function (editor, data) {
  10912. return editor.fire('TextColorChange', data);
  10913. };
  10914. var global$9 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  10915. var storageName = 'tinymce-custom-colors';
  10916. function ColorCache (max) {
  10917. if (max === void 0) {
  10918. max = 10;
  10919. }
  10920. var storageString = global$9.getItem(storageName);
  10921. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  10922. var prune = function (list) {
  10923. var diff = max - list.length;
  10924. return diff < 0 ? list.slice(0, max) : list;
  10925. };
  10926. var cache = prune(localstorage);
  10927. var add = function (key) {
  10928. indexOf(cache, key).each(remove);
  10929. cache.unshift(key);
  10930. if (cache.length > max) {
  10931. cache.pop();
  10932. }
  10933. global$9.setItem(storageName, JSON.stringify(cache));
  10934. };
  10935. var remove = function (idx) {
  10936. cache.splice(idx, 1);
  10937. };
  10938. var state = function () {
  10939. return cache.slice(0);
  10940. };
  10941. return {
  10942. add: add,
  10943. state: state
  10944. };
  10945. }
  10946. var choiceItem = 'choiceitem';
  10947. var defaultColors = [
  10948. {
  10949. type: choiceItem,
  10950. text: 'Light Green',
  10951. value: '#BFEDD2'
  10952. },
  10953. {
  10954. type: choiceItem,
  10955. text: 'Light Yellow',
  10956. value: '#FBEEB8'
  10957. },
  10958. {
  10959. type: choiceItem,
  10960. text: 'Light Red',
  10961. value: '#F8CAC6'
  10962. },
  10963. {
  10964. type: choiceItem,
  10965. text: 'Light Purple',
  10966. value: '#ECCAFA'
  10967. },
  10968. {
  10969. type: choiceItem,
  10970. text: 'Light Blue',
  10971. value: '#C2E0F4'
  10972. },
  10973. {
  10974. type: choiceItem,
  10975. text: 'Green',
  10976. value: '#2DC26B'
  10977. },
  10978. {
  10979. type: choiceItem,
  10980. text: 'Yellow',
  10981. value: '#F1C40F'
  10982. },
  10983. {
  10984. type: choiceItem,
  10985. text: 'Red',
  10986. value: '#E03E2D'
  10987. },
  10988. {
  10989. type: choiceItem,
  10990. text: 'Purple',
  10991. value: '#B96AD9'
  10992. },
  10993. {
  10994. type: choiceItem,
  10995. text: 'Blue',
  10996. value: '#3598DB'
  10997. },
  10998. {
  10999. type: choiceItem,
  11000. text: 'Dark Turquoise',
  11001. value: '#169179'
  11002. },
  11003. {
  11004. type: choiceItem,
  11005. text: 'Orange',
  11006. value: '#E67E23'
  11007. },
  11008. {
  11009. type: choiceItem,
  11010. text: 'Dark Red',
  11011. value: '#BA372A'
  11012. },
  11013. {
  11014. type: choiceItem,
  11015. text: 'Dark Purple',
  11016. value: '#843FA1'
  11017. },
  11018. {
  11019. type: choiceItem,
  11020. text: 'Dark Blue',
  11021. value: '#236FA1'
  11022. },
  11023. {
  11024. type: choiceItem,
  11025. text: 'Light Gray',
  11026. value: '#ECF0F1'
  11027. },
  11028. {
  11029. type: choiceItem,
  11030. text: 'Medium Gray',
  11031. value: '#CED4D9'
  11032. },
  11033. {
  11034. type: choiceItem,
  11035. text: 'Gray',
  11036. value: '#95A5A6'
  11037. },
  11038. {
  11039. type: choiceItem,
  11040. text: 'Dark Gray',
  11041. value: '#7E8C8D'
  11042. },
  11043. {
  11044. type: choiceItem,
  11045. text: 'Navy Blue',
  11046. value: '#34495E'
  11047. },
  11048. {
  11049. type: choiceItem,
  11050. text: 'Black',
  11051. value: '#000000'
  11052. },
  11053. {
  11054. type: choiceItem,
  11055. text: 'White',
  11056. value: '#ffffff'
  11057. }
  11058. ];
  11059. var colorCache = ColorCache(10);
  11060. var mapColors = function (colorMap) {
  11061. var colors = [];
  11062. var canvas = document.createElement('canvas');
  11063. canvas.height = 1;
  11064. canvas.width = 1;
  11065. var ctx = canvas.getContext('2d');
  11066. var byteAsHex = function (colorByte, alphaByte) {
  11067. var bg = 255;
  11068. var alpha = alphaByte / 255;
  11069. var colorByteWithWhiteBg = Math.round(colorByte * alpha + bg * (1 - alpha));
  11070. return ('0' + colorByteWithWhiteBg.toString(16)).slice(-2).toUpperCase();
  11071. };
  11072. var asHexColor = function (color) {
  11073. if (/^[0-9A-Fa-f]{6}$/.test(color)) {
  11074. return '#' + color.toUpperCase();
  11075. }
  11076. ctx.clearRect(0, 0, canvas.width, canvas.height);
  11077. ctx.fillStyle = '#FFFFFF';
  11078. ctx.fillStyle = color;
  11079. ctx.fillRect(0, 0, 1, 1);
  11080. var rgba = ctx.getImageData(0, 0, 1, 1).data;
  11081. var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3];
  11082. return '#' + byteAsHex(r, a) + byteAsHex(g, a) + byteAsHex(b, a);
  11083. };
  11084. for (var i = 0; i < colorMap.length; i += 2) {
  11085. colors.push({
  11086. text: colorMap[i + 1],
  11087. value: asHexColor(colorMap[i]),
  11088. type: 'choiceitem'
  11089. });
  11090. }
  11091. return colors;
  11092. };
  11093. var getColorCols = function (editor, defaultCols) {
  11094. return editor.getParam('color_cols', defaultCols, 'number');
  11095. };
  11096. var hasCustomColors = function (editor) {
  11097. return editor.getParam('custom_colors') !== false;
  11098. };
  11099. var getColorMap = function (editor) {
  11100. return editor.getParam('color_map');
  11101. };
  11102. var getColors = function (editor) {
  11103. var unmapped = getColorMap(editor);
  11104. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  11105. };
  11106. var getCurrentColors = function () {
  11107. return map(colorCache.state(), function (color) {
  11108. return {
  11109. type: choiceItem,
  11110. text: color,
  11111. value: color
  11112. };
  11113. });
  11114. };
  11115. var addColor = function (color) {
  11116. colorCache.add(color);
  11117. };
  11118. var getCurrentColor = function (editor, format) {
  11119. var color;
  11120. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  11121. var value;
  11122. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  11123. color = color ? color : value;
  11124. }
  11125. });
  11126. return color;
  11127. };
  11128. var applyFormat = function (editor, format, value) {
  11129. editor.undoManager.transact(function () {
  11130. editor.focus();
  11131. editor.formatter.apply(format, { value: value });
  11132. editor.nodeChanged();
  11133. });
  11134. };
  11135. var removeFormat = function (editor, format) {
  11136. editor.undoManager.transact(function () {
  11137. editor.focus();
  11138. editor.formatter.remove(format, { value: null }, null, true);
  11139. editor.nodeChanged();
  11140. });
  11141. };
  11142. var registerCommands = function (editor) {
  11143. editor.addCommand('mceApplyTextcolor', function (format, value) {
  11144. applyFormat(editor, format, value);
  11145. });
  11146. editor.addCommand('mceRemoveTextcolor', function (format) {
  11147. removeFormat(editor, format);
  11148. });
  11149. };
  11150. var calcCols = function (colors) {
  11151. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  11152. };
  11153. var getColorCols$1 = function (editor) {
  11154. var colors = getColors(editor);
  11155. var defaultCols = calcCols(colors.length);
  11156. return getColorCols(editor, defaultCols);
  11157. };
  11158. var getAdditionalColors = function (hasCustom) {
  11159. var type = 'choiceitem';
  11160. var remove = {
  11161. type: type,
  11162. text: 'Remove color',
  11163. icon: 'color-swatch-remove-color',
  11164. value: 'remove'
  11165. };
  11166. var custom = {
  11167. type: type,
  11168. text: 'Custom color',
  11169. icon: 'color-picker',
  11170. value: 'custom'
  11171. };
  11172. return hasCustom ? [
  11173. remove,
  11174. custom
  11175. ] : [remove];
  11176. };
  11177. var applyColor = function (editor, format, value, onChoice) {
  11178. if (value === 'custom') {
  11179. var dialog = colorPickerDialog(editor);
  11180. dialog(function (colorOpt) {
  11181. colorOpt.each(function (color) {
  11182. addColor(color);
  11183. editor.execCommand('mceApplyTextcolor', format, color);
  11184. onChoice(color);
  11185. });
  11186. }, '#000000');
  11187. } else if (value === 'remove') {
  11188. onChoice('');
  11189. editor.execCommand('mceRemoveTextcolor', format);
  11190. } else {
  11191. onChoice(value);
  11192. editor.execCommand('mceApplyTextcolor', format, value);
  11193. }
  11194. };
  11195. var getColors$1 = function (colors, hasCustom) {
  11196. return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  11197. };
  11198. var getFetch = function (colors, hasCustom) {
  11199. return function (callback) {
  11200. callback(getColors$1(colors, hasCustom));
  11201. };
  11202. };
  11203. var setIconColor = function (splitButtonApi, name, newColor) {
  11204. var setIconFillAndStroke = function (pathId, color) {
  11205. splitButtonApi.setIconFill(pathId, color);
  11206. splitButtonApi.setIconStroke(pathId, color);
  11207. };
  11208. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  11209. setIconFillAndStroke(id, newColor);
  11210. };
  11211. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  11212. editor.ui.registry.addSplitButton(name, {
  11213. tooltip: tooltip,
  11214. presets: 'color',
  11215. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11216. select: function (value) {
  11217. var optCurrentRgb = Optional.from(getCurrentColor(editor, format));
  11218. return optCurrentRgb.bind(function (currentRgb) {
  11219. return fromString(currentRgb).map(function (rgba) {
  11220. var currentHex = fromRgba(rgba).value;
  11221. return contains$1(value.toLowerCase(), currentHex);
  11222. });
  11223. }).getOr(false);
  11224. },
  11225. columns: getColorCols$1(editor),
  11226. fetch: getFetch(getColors(editor), hasCustomColors(editor)),
  11227. onAction: function (_splitButtonApi) {
  11228. if (lastColor.get() !== null) {
  11229. applyColor(editor, format, lastColor.get(), function () {
  11230. });
  11231. }
  11232. },
  11233. onItemAction: function (_splitButtonApi, value) {
  11234. applyColor(editor, format, value, function (newColor) {
  11235. lastColor.set(newColor);
  11236. fireTextColorChange(editor, {
  11237. name: name,
  11238. color: newColor
  11239. });
  11240. });
  11241. },
  11242. onSetup: function (splitButtonApi) {
  11243. if (lastColor.get() !== null) {
  11244. setIconColor(splitButtonApi, name, lastColor.get());
  11245. }
  11246. var handler = function (e) {
  11247. if (e.name === name) {
  11248. setIconColor(splitButtonApi, e.name, e.color);
  11249. }
  11250. };
  11251. editor.on('TextColorChange', handler);
  11252. return function () {
  11253. editor.off('TextColorChange', handler);
  11254. };
  11255. }
  11256. });
  11257. };
  11258. var registerTextColorMenuItem = function (editor, name, format, text) {
  11259. editor.ui.registry.addNestedMenuItem(name, {
  11260. text: text,
  11261. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11262. getSubmenuItems: function () {
  11263. return [{
  11264. type: 'fancymenuitem',
  11265. fancytype: 'colorswatch',
  11266. onAction: function (data) {
  11267. applyColor(editor, format, data.value, noop);
  11268. }
  11269. }];
  11270. }
  11271. });
  11272. };
  11273. var colorPickerDialog = function (editor) {
  11274. return function (callback, value) {
  11275. var getOnSubmit = function (callback) {
  11276. return function (api) {
  11277. var data = api.getData();
  11278. callback(Optional.from(data.colorpicker));
  11279. api.close();
  11280. };
  11281. };
  11282. var onAction = function (api, details) {
  11283. if (details.name === 'hex-valid') {
  11284. if (details.value) {
  11285. api.enable('ok');
  11286. } else {
  11287. api.disable('ok');
  11288. }
  11289. }
  11290. };
  11291. var initialData = { colorpicker: value };
  11292. var submit = getOnSubmit(callback);
  11293. editor.windowManager.open({
  11294. title: 'Color Picker',
  11295. size: 'normal',
  11296. body: {
  11297. type: 'panel',
  11298. items: [{
  11299. type: 'colorpicker',
  11300. name: 'colorpicker',
  11301. label: 'Color'
  11302. }]
  11303. },
  11304. buttons: [
  11305. {
  11306. type: 'cancel',
  11307. name: 'cancel',
  11308. text: 'Cancel'
  11309. },
  11310. {
  11311. type: 'submit',
  11312. name: 'save',
  11313. text: 'Save',
  11314. primary: true
  11315. }
  11316. ],
  11317. initialData: initialData,
  11318. onAction: onAction,
  11319. onSubmit: submit,
  11320. onClose: function () {
  11321. },
  11322. onCancel: function () {
  11323. callback(Optional.none());
  11324. }
  11325. });
  11326. };
  11327. };
  11328. var register$1 = function (editor) {
  11329. registerCommands(editor);
  11330. var lastForeColor = Cell(null);
  11331. var lastBackColor = Cell(null);
  11332. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  11333. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  11334. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  11335. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  11336. };
  11337. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11338. var hasIcons = menuHasIcons(items);
  11339. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11340. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11341. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11342. };
  11343. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11344. return cat(map(items, function (item) {
  11345. if (item.type === 'choiceitem') {
  11346. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11347. return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items)));
  11348. });
  11349. } else {
  11350. return Optional.none();
  11351. }
  11352. }));
  11353. };
  11354. var deriveMenuMovement = function (columns, presets) {
  11355. var menuMarkers = markers$1(presets);
  11356. if (columns === 1) {
  11357. return {
  11358. mode: 'menu',
  11359. moveOnTab: true
  11360. };
  11361. } else if (columns === 'auto') {
  11362. return {
  11363. mode: 'grid',
  11364. selector: '.' + menuMarkers.item,
  11365. initSize: {
  11366. numColumns: 1,
  11367. numRows: 1
  11368. }
  11369. };
  11370. } else {
  11371. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11372. return {
  11373. mode: 'matrix',
  11374. rowSelector: '.' + rowClass
  11375. };
  11376. }
  11377. };
  11378. var deriveCollectionMovement = function (columns, presets) {
  11379. if (columns === 1) {
  11380. return {
  11381. mode: 'menu',
  11382. moveOnTab: false,
  11383. selector: '.tox-collection__item'
  11384. };
  11385. } else if (columns === 'auto') {
  11386. return {
  11387. mode: 'flatgrid',
  11388. selector: '.' + 'tox-collection__item',
  11389. initSize: {
  11390. numColumns: 1,
  11391. numRows: 1
  11392. }
  11393. };
  11394. } else {
  11395. return {
  11396. mode: 'matrix',
  11397. selectors: {
  11398. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11399. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11400. }
  11401. };
  11402. }
  11403. };
  11404. function renderColorSwatchItem(spec, backstage) {
  11405. var items = getColors$1(backstage.colorinput.getColors(), backstage.colorinput.hasCustomColors());
  11406. var columns = backstage.colorinput.getColorCols();
  11407. var presets = 'color';
  11408. var menuSpec = createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  11409. spec.onAction({ value: value });
  11410. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  11411. return false;
  11412. }, backstage.shared.providers);
  11413. var widgetSpec = __assign(__assign({}, menuSpec), {
  11414. markers: markers$1(presets),
  11415. movement: deriveMenuMovement(columns, presets)
  11416. });
  11417. return {
  11418. type: 'widget',
  11419. data: { value: generate$1('widget-id') },
  11420. dom: {
  11421. tag: 'div',
  11422. classes: ['tox-fancymenuitem']
  11423. },
  11424. autofocus: true,
  11425. components: [parts$2.widget(Menu.sketch(widgetSpec))]
  11426. };
  11427. }
  11428. var cellOverEvent = generate$1('cell-over');
  11429. var cellExecuteEvent = generate$1('cell-execute');
  11430. var makeCell = function (row, col, labelId) {
  11431. var _a;
  11432. var emitCellOver = function (c) {
  11433. return emitWith(c, cellOverEvent, {
  11434. row: row,
  11435. col: col
  11436. });
  11437. };
  11438. var emitExecute = function (c) {
  11439. return emitWith(c, cellExecuteEvent, {
  11440. row: row,
  11441. col: col
  11442. });
  11443. };
  11444. var onClick = function (c, se) {
  11445. se.stop();
  11446. emitExecute(c);
  11447. };
  11448. return build$1({
  11449. dom: {
  11450. tag: 'div',
  11451. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  11452. },
  11453. behaviours: derive$1([
  11454. config('insert-table-picker-cell', [
  11455. run(mouseover(), Focusing.focus),
  11456. run(execute(), emitExecute),
  11457. run(click(), onClick),
  11458. run(tap(), onClick)
  11459. ]),
  11460. Toggling.config({
  11461. toggleClass: 'tox-insert-table-picker__selected',
  11462. toggleOnExecute: false
  11463. }),
  11464. Focusing.config({ onFocus: emitCellOver })
  11465. ])
  11466. });
  11467. };
  11468. var makeCells = function (labelId, numRows, numCols) {
  11469. var cells = [];
  11470. for (var i = 0; i < numRows; i++) {
  11471. var row = [];
  11472. for (var j = 0; j < numCols; j++) {
  11473. row.push(makeCell(i, j, labelId));
  11474. }
  11475. cells.push(row);
  11476. }
  11477. return cells;
  11478. };
  11479. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  11480. for (var i = 0; i < numRows; i++) {
  11481. for (var j = 0; j < numColumns; j++) {
  11482. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  11483. }
  11484. }
  11485. };
  11486. var makeComponents = function (cells) {
  11487. return bind(cells, function (cellRow) {
  11488. return map(cellRow, premade$1);
  11489. });
  11490. };
  11491. var makeLabelText = function (row, col) {
  11492. return text(col + 1 + 'x' + (row + 1));
  11493. };
  11494. var renderInsertTableMenuItem = function (spec) {
  11495. var numRows = 10;
  11496. var numColumns = 10;
  11497. var sizeLabelId = generate$1('size-label');
  11498. var cells = makeCells(sizeLabelId, numRows, numColumns);
  11499. var memLabel = record({
  11500. dom: {
  11501. tag: 'span',
  11502. classes: ['tox-insert-table-picker__label'],
  11503. attributes: { id: sizeLabelId }
  11504. },
  11505. components: [text('0x0')],
  11506. behaviours: derive$1([Replacing.config({})])
  11507. });
  11508. return {
  11509. type: 'widget',
  11510. data: { value: generate$1('widget-id') },
  11511. dom: {
  11512. tag: 'div',
  11513. classes: ['tox-fancymenuitem']
  11514. },
  11515. autofocus: true,
  11516. components: [parts$2.widget({
  11517. dom: {
  11518. tag: 'div',
  11519. classes: ['tox-insert-table-picker']
  11520. },
  11521. components: makeComponents(cells).concat(memLabel.asSpec()),
  11522. behaviours: derive$1([
  11523. config('insert-table-picker', [
  11524. runWithTarget(cellOverEvent, function (c, t, e) {
  11525. var row = e.event.row;
  11526. var col = e.event.col;
  11527. selectCells(cells, row, col, numRows, numColumns);
  11528. Replacing.set(memLabel.get(c), [makeLabelText(row, col)]);
  11529. }),
  11530. runWithTarget(cellExecuteEvent, function (c, _, e) {
  11531. spec.onAction({
  11532. numRows: e.event.row + 1,
  11533. numColumns: e.event.col + 1
  11534. });
  11535. emit(c, sandboxClose());
  11536. })
  11537. ]),
  11538. Keying.config({
  11539. initSize: {
  11540. numRows: numRows,
  11541. numColumns: numColumns
  11542. },
  11543. mode: 'flatgrid',
  11544. selector: '[role="button"]'
  11545. })
  11546. ])
  11547. })]
  11548. };
  11549. };
  11550. var fancyMenuItems = {
  11551. inserttable: renderInsertTableMenuItem,
  11552. colorswatch: renderColorSwatchItem
  11553. };
  11554. var valueOpt = function (obj, key) {
  11555. return Object.prototype.hasOwnProperty.call(obj, key) ? Optional.some(obj[key]) : Optional.none();
  11556. };
  11557. var renderFancyMenuItem = function (spec, backstage) {
  11558. return valueOpt(fancyMenuItems, spec.fancytype).map(function (render) {
  11559. return render(spec, backstage);
  11560. });
  11561. };
  11562. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  11563. if (renderIcons === void 0) {
  11564. renderIcons = true;
  11565. }
  11566. if (downwardsCaret === void 0) {
  11567. downwardsCaret = false;
  11568. }
  11569. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  11570. var getApi = function (component) {
  11571. return {
  11572. isDisabled: function () {
  11573. return Disabling.isDisabled(component);
  11574. },
  11575. setDisabled: function (state) {
  11576. return Disabling.set(component, state);
  11577. }
  11578. };
  11579. };
  11580. var structure = renderItemStructure({
  11581. presets: 'normal',
  11582. iconContent: spec.icon,
  11583. textContent: spec.text,
  11584. htmlContent: Optional.none(),
  11585. ariaLabel: spec.text,
  11586. caret: Optional.some(caret),
  11587. checkMark: Optional.none(),
  11588. shortcutContent: spec.shortcut
  11589. }, providersBackstage, renderIcons);
  11590. return renderCommonItem({
  11591. data: buildData(spec),
  11592. getApi: getApi,
  11593. disabled: spec.disabled,
  11594. onAction: noop,
  11595. onSetup: spec.onSetup,
  11596. triggersSubmenu: true,
  11597. itemBehaviours: []
  11598. }, structure, itemResponse, providersBackstage);
  11599. };
  11600. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11601. if (renderIcons === void 0) {
  11602. renderIcons = true;
  11603. }
  11604. var getApi = function (component) {
  11605. return {
  11606. isDisabled: function () {
  11607. return Disabling.isDisabled(component);
  11608. },
  11609. setDisabled: function (state) {
  11610. return Disabling.set(component, state);
  11611. }
  11612. };
  11613. };
  11614. var structure = renderItemStructure({
  11615. presets: 'normal',
  11616. iconContent: spec.icon,
  11617. textContent: spec.text,
  11618. htmlContent: Optional.none(),
  11619. ariaLabel: spec.text,
  11620. caret: Optional.none(),
  11621. checkMark: Optional.none(),
  11622. shortcutContent: spec.shortcut
  11623. }, providersBackstage, renderIcons);
  11624. return renderCommonItem({
  11625. data: buildData(spec),
  11626. getApi: getApi,
  11627. disabled: spec.disabled,
  11628. onAction: spec.onAction,
  11629. onSetup: spec.onSetup,
  11630. triggersSubmenu: false,
  11631. itemBehaviours: []
  11632. }, structure, itemResponse, providersBackstage);
  11633. };
  11634. var renderSeparatorItem = function (spec) {
  11635. var innerHtml = spec.text.fold(function () {
  11636. return {};
  11637. }, function (text) {
  11638. return { innerHtml: text };
  11639. });
  11640. return {
  11641. type: 'separator',
  11642. dom: __assign({
  11643. tag: 'div',
  11644. classes: [
  11645. selectableClass,
  11646. groupHeadingClass
  11647. ]
  11648. }, innerHtml),
  11649. components: []
  11650. };
  11651. };
  11652. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11653. if (renderIcons === void 0) {
  11654. renderIcons = true;
  11655. }
  11656. var getApi = function (component) {
  11657. return {
  11658. setActive: function (state) {
  11659. Toggling.set(component, state);
  11660. },
  11661. isActive: function () {
  11662. return Toggling.isOn(component);
  11663. },
  11664. isDisabled: function () {
  11665. return Disabling.isDisabled(component);
  11666. },
  11667. setDisabled: function (state) {
  11668. return Disabling.set(component, state);
  11669. }
  11670. };
  11671. };
  11672. var structure = renderItemStructure({
  11673. iconContent: spec.icon,
  11674. textContent: spec.text,
  11675. htmlContent: Optional.none(),
  11676. ariaLabel: spec.text,
  11677. checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
  11678. caret: Optional.none(),
  11679. shortcutContent: spec.shortcut,
  11680. presets: 'normal',
  11681. meta: spec.meta
  11682. }, providersBackstage, renderIcons);
  11683. return deepMerge(renderCommonItem({
  11684. data: buildData(spec),
  11685. disabled: spec.disabled,
  11686. getApi: getApi,
  11687. onAction: spec.onAction,
  11688. onSetup: spec.onSetup,
  11689. triggersSubmenu: false,
  11690. itemBehaviours: []
  11691. }, structure, itemResponse, providersBackstage), {
  11692. toggling: {
  11693. toggleClass: tickedClass,
  11694. toggleOnExecute: false,
  11695. selected: spec.active
  11696. }
  11697. });
  11698. };
  11699. var autocomplete = renderAutocompleteItem;
  11700. var separator = renderSeparatorItem;
  11701. var normal = renderNormalItem;
  11702. var nested = renderNestedItem;
  11703. var toggle$1 = renderToggleMenuItem;
  11704. var fancy = renderFancyMenuItem;
  11705. var FocusMode;
  11706. (function (FocusMode) {
  11707. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  11708. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  11709. }(FocusMode || (FocusMode = {})));
  11710. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  11711. var providersBackstage = backstage.shared.providers;
  11712. var parseForHorizontalMenu = function (menuitem) {
  11713. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  11714. shortcut: Optional.none(),
  11715. icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
  11716. });
  11717. };
  11718. switch (item.type) {
  11719. case 'menuitem':
  11720. return createMenuItem(item).fold(handleError, function (d) {
  11721. return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11722. });
  11723. case 'nestedmenuitem':
  11724. return createNestedMenuItem(item).fold(handleError, function (d) {
  11725. return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  11726. });
  11727. case 'togglemenuitem':
  11728. return createToggleMenuItem(item).fold(handleError, function (d) {
  11729. return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11730. });
  11731. case 'separator':
  11732. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  11733. return Optional.some(separator(d));
  11734. });
  11735. case 'fancymenuitem':
  11736. return createFancyMenuItem(item).fold(handleError, function (d) {
  11737. return fancy(parseForHorizontalMenu(d), backstage);
  11738. });
  11739. default: {
  11740. console.error('Unknown item in general menu', item);
  11741. return Optional.none();
  11742. }
  11743. }
  11744. };
  11745. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage) {
  11746. var renderText = columns === 1;
  11747. var renderIcons = !renderText || menuHasIcons(items);
  11748. return cat(map(items, function (item) {
  11749. if (item.type === 'separator') {
  11750. return createSeparatorItem(item).fold(handleError, function (d) {
  11751. return Optional.some(separator(d));
  11752. });
  11753. } else {
  11754. return createAutocompleterItem(item).fold(handleError, function (d) {
  11755. return Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  11756. });
  11757. }
  11758. }));
  11759. };
  11760. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  11761. var hasIcons = menuHasIcons(items);
  11762. var alloyItems = cat(map(items, function (item) {
  11763. var itemHasIcon = function (i) {
  11764. return isHorizontalMenu ? !i.hasOwnProperty('text') : hasIcons;
  11765. };
  11766. var createItem = function (i) {
  11767. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  11768. };
  11769. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  11770. return createItem(__assign(__assign({}, item), { disabled: true }));
  11771. } else {
  11772. return createItem(item);
  11773. }
  11774. }));
  11775. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  11776. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  11777. };
  11778. var createTieredDataFrom = function (partialMenu) {
  11779. return tieredMenu.singleData(partialMenu.value, partialMenu);
  11780. };
  11781. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  11782. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom();
  11783. var movement = deriveMenuMovement(columns, presets);
  11784. var menuMarkers = markers$1(presets);
  11785. return {
  11786. dom: partialMenu.dom,
  11787. components: partialMenu.components,
  11788. items: partialMenu.items,
  11789. value: partialMenu.value,
  11790. markers: {
  11791. selectedItem: menuMarkers.selectedItem,
  11792. item: menuMarkers.item
  11793. },
  11794. movement: movement,
  11795. fakeFocus: focusMode === FocusMode.ContentFocus,
  11796. focusManager: focusManager,
  11797. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  11798. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  11799. var numColumns = _a.numColumns, numRows = _a.numRows;
  11800. Keying.setGridSize(comp, numRows, numColumns);
  11801. });
  11802. })])
  11803. };
  11804. };
  11805. var register$2 = function (editor, sharedBackstage) {
  11806. var activeAutocompleter = Cell(Optional.none());
  11807. var processingAction = Cell(false);
  11808. var autocompleter = build$1(InlineView.sketch({
  11809. dom: {
  11810. tag: 'div',
  11811. classes: ['tox-autocompleter']
  11812. },
  11813. components: [],
  11814. fireDismissalEventInstead: {},
  11815. inlineBehaviours: derive$1([config('dismissAutocompleter', [run(dismissRequested(), function () {
  11816. return cancelIfNecessary();
  11817. })])]),
  11818. lazySink: sharedBackstage.getSink
  11819. }));
  11820. var isMenuOpen = function () {
  11821. return InlineView.isOpen(autocompleter);
  11822. };
  11823. var isActive = function () {
  11824. return activeAutocompleter.get().isSome();
  11825. };
  11826. var hideIfNecessary = function () {
  11827. if (isActive()) {
  11828. InlineView.hide(autocompleter);
  11829. }
  11830. };
  11831. var cancelIfNecessary = function () {
  11832. if (isActive()) {
  11833. var lastElement = activeAutocompleter.get().map(function (ac) {
  11834. return ac.element;
  11835. });
  11836. detect$4(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
  11837. hideIfNecessary();
  11838. activeAutocompleter.set(Optional.none());
  11839. processingAction.set(false);
  11840. }
  11841. };
  11842. var getAutocompleters = cached(function () {
  11843. return register(editor);
  11844. });
  11845. var getCombinedItems = function (triggerChar, matches) {
  11846. var columns = findMap(matches, function (m) {
  11847. return Optional.from(m.columns);
  11848. }).getOr(1);
  11849. return bind(matches, function (match) {
  11850. var choices = match.items;
  11851. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  11852. var nr = editor.selection.getRng();
  11853. getContext(editor.dom, nr, triggerChar).fold(function () {
  11854. return console.error('Lost context. Cursor probably moved');
  11855. }, function (_a) {
  11856. var range = _a.range;
  11857. var autocompleterApi = {
  11858. hide: function () {
  11859. cancelIfNecessary();
  11860. },
  11861. reload: function (fetchOptions) {
  11862. hideIfNecessary();
  11863. load(fetchOptions);
  11864. }
  11865. };
  11866. processingAction.set(true);
  11867. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  11868. processingAction.set(false);
  11869. });
  11870. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage);
  11871. });
  11872. };
  11873. var commenceIfNecessary = function (context) {
  11874. if (!isActive()) {
  11875. var wrapper = create$4(editor, context.range);
  11876. activeAutocompleter.set(Optional.some({
  11877. triggerChar: context.triggerChar,
  11878. element: wrapper,
  11879. matchLength: context.text.length
  11880. }));
  11881. processingAction.set(false);
  11882. }
  11883. };
  11884. var display = function (ac, context, lookupData, items) {
  11885. ac.matchLength = context.text.length;
  11886. var columns = findMap(lookupData, function (ld) {
  11887. return Optional.from(ld.columns);
  11888. }).getOr(1);
  11889. InlineView.showAt(autocompleter, {
  11890. anchor: 'node',
  11891. root: SugarElement.fromDom(editor.getBody()),
  11892. node: Optional.from(ac.element)
  11893. }, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')));
  11894. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  11895. };
  11896. var doLookup = function (fetchOptions) {
  11897. return activeAutocompleter.get().map(function (ac) {
  11898. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  11899. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  11900. });
  11901. }).getOrThunk(function () {
  11902. return lookup(editor, getAutocompleters);
  11903. });
  11904. };
  11905. var load = function (fetchOptions) {
  11906. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  11907. commenceIfNecessary(lookupInfo.context);
  11908. lookupInfo.lookupData.then(function (lookupData) {
  11909. activeAutocompleter.get().map(function (ac) {
  11910. var context = lookupInfo.context;
  11911. if (ac.triggerChar === context.triggerChar) {
  11912. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  11913. if (combinedItems.length > 0) {
  11914. display(ac, context, lookupData, combinedItems);
  11915. } else if (context.text.length - ac.matchLength >= 10) {
  11916. cancelIfNecessary();
  11917. } else {
  11918. hideIfNecessary();
  11919. }
  11920. }
  11921. });
  11922. });
  11923. });
  11924. };
  11925. var onKeypress = last$2(function (e) {
  11926. if (e.which === 27) {
  11927. return;
  11928. }
  11929. load();
  11930. }, 50);
  11931. var autocompleterUiApi = {
  11932. onKeypress: onKeypress,
  11933. cancelIfNecessary: cancelIfNecessary,
  11934. isMenuOpen: isMenuOpen,
  11935. isActive: isActive,
  11936. isProcessingAction: processingAction.get,
  11937. getView: function () {
  11938. return InlineView.getContent(autocompleter);
  11939. }
  11940. };
  11941. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  11942. };
  11943. var Autocompleter = { register: register$2 };
  11944. var filter$2 = always;
  11945. var bind$3 = function (element, event, handler) {
  11946. return bind$2(element, event, filter$2, handler);
  11947. };
  11948. var capture$1 = function (element, event, handler) {
  11949. return capture(element, event, filter$2, handler);
  11950. };
  11951. var fromRawEvent$1 = fromRawEvent;
  11952. var closest$4 = function (scope, selector, isRoot) {
  11953. return closest$3(scope, selector, isRoot).isSome();
  11954. };
  11955. function DelayedFunction (fun, delay) {
  11956. var ref = null;
  11957. var schedule = function () {
  11958. var args = [];
  11959. for (var _i = 0; _i < arguments.length; _i++) {
  11960. args[_i] = arguments[_i];
  11961. }
  11962. ref = setTimeout(function () {
  11963. fun.apply(null, args);
  11964. ref = null;
  11965. }, delay);
  11966. };
  11967. var cancel = function () {
  11968. if (ref !== null) {
  11969. clearTimeout(ref);
  11970. ref = null;
  11971. }
  11972. };
  11973. return {
  11974. cancel: cancel,
  11975. schedule: schedule
  11976. };
  11977. }
  11978. var SIGNIFICANT_MOVE = 5;
  11979. var LONGPRESS_DELAY = 400;
  11980. var getTouch = function (event) {
  11981. var raw = event.raw;
  11982. if (raw.touches === undefined || raw.touches.length !== 1) {
  11983. return Optional.none();
  11984. }
  11985. return Optional.some(raw.touches[0]);
  11986. };
  11987. var isFarEnough = function (touch, data) {
  11988. var distX = Math.abs(touch.clientX - data.x);
  11989. var distY = Math.abs(touch.clientY - data.y);
  11990. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  11991. };
  11992. var monitor = function (settings) {
  11993. var startData = Cell(Optional.none());
  11994. var longpressFired = Cell(false);
  11995. var longpress$1 = DelayedFunction(function (event) {
  11996. settings.triggerEvent(longpress(), event);
  11997. longpressFired.set(true);
  11998. }, LONGPRESS_DELAY);
  11999. var handleTouchstart = function (event) {
  12000. getTouch(event).each(function (touch) {
  12001. longpress$1.cancel();
  12002. var data = {
  12003. x: touch.clientX,
  12004. y: touch.clientY,
  12005. target: event.target
  12006. };
  12007. longpress$1.schedule(event);
  12008. longpressFired.set(false);
  12009. startData.set(Optional.some(data));
  12010. });
  12011. return Optional.none();
  12012. };
  12013. var handleTouchmove = function (event) {
  12014. longpress$1.cancel();
  12015. getTouch(event).each(function (touch) {
  12016. startData.get().each(function (data) {
  12017. if (isFarEnough(touch, data)) {
  12018. startData.set(Optional.none());
  12019. }
  12020. });
  12021. });
  12022. return Optional.none();
  12023. };
  12024. var handleTouchend = function (event) {
  12025. longpress$1.cancel();
  12026. var isSame = function (data) {
  12027. return eq$1(data.target, event.target);
  12028. };
  12029. return startData.get().filter(isSame).map(function (_data) {
  12030. if (longpressFired.get()) {
  12031. event.prevent();
  12032. return false;
  12033. } else {
  12034. return settings.triggerEvent(tap(), event);
  12035. }
  12036. });
  12037. };
  12038. var handlers = wrapAll$1([
  12039. {
  12040. key: touchstart(),
  12041. value: handleTouchstart
  12042. },
  12043. {
  12044. key: touchmove(),
  12045. value: handleTouchmove
  12046. },
  12047. {
  12048. key: touchend(),
  12049. value: handleTouchend
  12050. }
  12051. ]);
  12052. var fireIfReady = function (event, type) {
  12053. return get(handlers, type).bind(function (handler) {
  12054. return handler(event);
  12055. });
  12056. };
  12057. return { fireIfReady: fireIfReady };
  12058. };
  12059. var isDangerous = function (event) {
  12060. var keyEv = event.raw;
  12061. return keyEv.which === BACKSPACE[0] && !contains([
  12062. 'input',
  12063. 'textarea'
  12064. ], name(event.target)) && !closest$4(event.target, '[contenteditable="true"]');
  12065. };
  12066. var isFirefox = function () {
  12067. return detect$3().browser.isFirefox();
  12068. };
  12069. var settingsSchema = objOfOnly([
  12070. strictFunction('triggerEvent'),
  12071. defaulted$1('stopBackspace', true)
  12072. ]);
  12073. var bindFocus = function (container, handler) {
  12074. if (isFirefox()) {
  12075. return capture$1(container, 'focus', handler);
  12076. } else {
  12077. return bind$3(container, 'focusin', handler);
  12078. }
  12079. };
  12080. var bindBlur = function (container, handler) {
  12081. if (isFirefox()) {
  12082. return capture$1(container, 'blur', handler);
  12083. } else {
  12084. return bind$3(container, 'focusout', handler);
  12085. }
  12086. };
  12087. var setup$1 = function (container, rawSettings) {
  12088. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  12089. var pointerEvents = [
  12090. 'touchstart',
  12091. 'touchmove',
  12092. 'touchend',
  12093. 'touchcancel',
  12094. 'gesturestart',
  12095. 'mousedown',
  12096. 'mouseup',
  12097. 'mouseover',
  12098. 'mousemove',
  12099. 'mouseout',
  12100. 'click'
  12101. ];
  12102. var tapEvent = monitor(settings);
  12103. var simpleEvents = map(pointerEvents.concat([
  12104. 'selectstart',
  12105. 'input',
  12106. 'contextmenu',
  12107. 'change',
  12108. 'transitionend',
  12109. 'drag',
  12110. 'dragstart',
  12111. 'dragend',
  12112. 'dragenter',
  12113. 'dragleave',
  12114. 'dragover',
  12115. 'drop',
  12116. 'keyup'
  12117. ]), function (type) {
  12118. return bind$3(container, type, function (event) {
  12119. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  12120. if (tapStopped) {
  12121. event.kill();
  12122. }
  12123. });
  12124. var stopped = settings.triggerEvent(type, event);
  12125. if (stopped) {
  12126. event.kill();
  12127. }
  12128. });
  12129. });
  12130. var pasteTimeout = Cell(Optional.none());
  12131. var onPaste = bind$3(container, 'paste', function (event) {
  12132. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  12133. if (tapStopped) {
  12134. event.kill();
  12135. }
  12136. });
  12137. var stopped = settings.triggerEvent('paste', event);
  12138. if (stopped) {
  12139. event.kill();
  12140. }
  12141. pasteTimeout.set(Optional.some(setTimeout(function () {
  12142. settings.triggerEvent(postPaste(), event);
  12143. }, 0)));
  12144. });
  12145. var onKeydown = bind$3(container, 'keydown', function (event) {
  12146. var stopped = settings.triggerEvent('keydown', event);
  12147. if (stopped) {
  12148. event.kill();
  12149. } else if (settings.stopBackspace === true && isDangerous(event)) {
  12150. event.prevent();
  12151. }
  12152. });
  12153. var onFocusIn = bindFocus(container, function (event) {
  12154. var stopped = settings.triggerEvent('focusin', event);
  12155. if (stopped) {
  12156. event.kill();
  12157. }
  12158. });
  12159. var focusoutTimeout = Cell(Optional.none());
  12160. var onFocusOut = bindBlur(container, function (event) {
  12161. var stopped = settings.triggerEvent('focusout', event);
  12162. if (stopped) {
  12163. event.kill();
  12164. }
  12165. focusoutTimeout.set(Optional.some(setTimeout(function () {
  12166. settings.triggerEvent(postBlur(), event);
  12167. }, 0)));
  12168. });
  12169. var unbind = function () {
  12170. each(simpleEvents, function (e) {
  12171. e.unbind();
  12172. });
  12173. onKeydown.unbind();
  12174. onFocusIn.unbind();
  12175. onFocusOut.unbind();
  12176. onPaste.unbind();
  12177. pasteTimeout.get().each(clearTimeout);
  12178. focusoutTimeout.get().each(clearTimeout);
  12179. };
  12180. return { unbind: unbind };
  12181. };
  12182. var derive$2 = function (rawEvent, rawTarget) {
  12183. var source = get(rawEvent, 'target').getOr(rawTarget);
  12184. return Cell(source);
  12185. };
  12186. var fromSource = function (event, source) {
  12187. var stopper = Cell(false);
  12188. var cutter = Cell(false);
  12189. var stop = function () {
  12190. stopper.set(true);
  12191. };
  12192. var cut = function () {
  12193. cutter.set(true);
  12194. };
  12195. return {
  12196. stop: stop,
  12197. cut: cut,
  12198. isStopped: stopper.get,
  12199. isCut: cutter.get,
  12200. event: event,
  12201. setSource: source.set,
  12202. getSource: source.get
  12203. };
  12204. };
  12205. var fromExternal = function (event) {
  12206. var stopper = Cell(false);
  12207. var stop = function () {
  12208. stopper.set(true);
  12209. };
  12210. return {
  12211. stop: stop,
  12212. cut: noop,
  12213. isStopped: stopper.get,
  12214. isCut: never,
  12215. event: event,
  12216. setSource: die('Cannot set source of a broadcasted event'),
  12217. getSource: die('Cannot get source of a broadcasted event')
  12218. };
  12219. };
  12220. var adt$b = Adt.generate([
  12221. { stopped: [] },
  12222. { resume: ['element'] },
  12223. { complete: [] }
  12224. ]);
  12225. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  12226. var handler = lookup(eventType, target);
  12227. var simulatedEvent = fromSource(rawEvent, source);
  12228. return handler.fold(function () {
  12229. logger.logEventNoHandlers(eventType, target);
  12230. return adt$b.complete();
  12231. }, function (handlerInfo) {
  12232. var descHandler = handlerInfo.descHandler;
  12233. var eventHandler = getCurried(descHandler);
  12234. eventHandler(simulatedEvent);
  12235. if (simulatedEvent.isStopped()) {
  12236. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  12237. return adt$b.stopped();
  12238. } else if (simulatedEvent.isCut()) {
  12239. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  12240. return adt$b.complete();
  12241. } else {
  12242. return parent(handlerInfo.element).fold(function () {
  12243. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  12244. return adt$b.complete();
  12245. }, function (parent) {
  12246. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  12247. return adt$b.resume(parent);
  12248. });
  12249. }
  12250. });
  12251. };
  12252. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12253. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  12254. return true;
  12255. }, function (parent) {
  12256. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12257. }, function () {
  12258. return false;
  12259. });
  12260. };
  12261. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12262. var source = derive$2(rawEvent, target);
  12263. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12264. };
  12265. var broadcast = function (listeners, rawEvent, _logger) {
  12266. var simulatedEvent = fromExternal(rawEvent);
  12267. each(listeners, function (listener) {
  12268. var descHandler = listener.descHandler;
  12269. var handler = getCurried(descHandler);
  12270. handler(simulatedEvent);
  12271. });
  12272. return simulatedEvent.isStopped();
  12273. };
  12274. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12275. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  12276. };
  12277. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12278. var source = derive$2(rawEvent, rawTarget);
  12279. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12280. };
  12281. var eventHandler = function (element, descHandler) {
  12282. return {
  12283. element: element,
  12284. descHandler: descHandler
  12285. };
  12286. };
  12287. var broadcastHandler = function (id, handler) {
  12288. return {
  12289. id: id,
  12290. descHandler: handler
  12291. };
  12292. };
  12293. function EventRegistry () {
  12294. var registry = {};
  12295. var registerId = function (extraArgs, id, events) {
  12296. each$1(events, function (v, k) {
  12297. var handlers = registry[k] !== undefined ? registry[k] : {};
  12298. handlers[id] = curryArgs(v, extraArgs);
  12299. registry[k] = handlers;
  12300. });
  12301. };
  12302. var findHandler = function (handlers, elem) {
  12303. return read$1(elem).fold(function () {
  12304. return Optional.none();
  12305. }, function (id) {
  12306. return handlers.bind(function (h) {
  12307. return get(h, id);
  12308. }).map(function (descHandler) {
  12309. return eventHandler(elem, descHandler);
  12310. });
  12311. });
  12312. };
  12313. var filterByType = function (type) {
  12314. return get(registry, type).map(function (handlers) {
  12315. return mapToArray(handlers, function (f, id) {
  12316. return broadcastHandler(id, f);
  12317. });
  12318. }).getOr([]);
  12319. };
  12320. var find = function (isAboveRoot, type, target) {
  12321. var handlers = get(registry, type);
  12322. return closest(target, function (elem) {
  12323. return findHandler(handlers, elem);
  12324. }, isAboveRoot);
  12325. };
  12326. var unregisterId = function (id) {
  12327. each$1(registry, function (handlersById, _eventName) {
  12328. if (handlersById.hasOwnProperty(id)) {
  12329. delete handlersById[id];
  12330. }
  12331. });
  12332. };
  12333. return {
  12334. registerId: registerId,
  12335. unregisterId: unregisterId,
  12336. filterByType: filterByType,
  12337. find: find
  12338. };
  12339. }
  12340. function Registry () {
  12341. var events = EventRegistry();
  12342. var components = {};
  12343. var readOrTag = function (component) {
  12344. var elem = component.element;
  12345. return read$1(elem).fold(function () {
  12346. return write('uid-', component.element);
  12347. }, function (uid) {
  12348. return uid;
  12349. });
  12350. };
  12351. var failOnDuplicate = function (component, tagId) {
  12352. var conflict = components[tagId];
  12353. if (conflict === component) {
  12354. unregister(component);
  12355. } else {
  12356. 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');
  12357. }
  12358. };
  12359. var register = function (component) {
  12360. var tagId = readOrTag(component);
  12361. if (hasNonNullableKey(components, tagId)) {
  12362. failOnDuplicate(component, tagId);
  12363. }
  12364. var extraArgs = [component];
  12365. events.registerId(extraArgs, tagId, component.events);
  12366. components[tagId] = component;
  12367. };
  12368. var unregister = function (component) {
  12369. read$1(component.element).each(function (tagId) {
  12370. delete components[tagId];
  12371. events.unregisterId(tagId);
  12372. });
  12373. };
  12374. var filter = function (type) {
  12375. return events.filterByType(type);
  12376. };
  12377. var find = function (isAboveRoot, type, target) {
  12378. return events.find(isAboveRoot, type, target);
  12379. };
  12380. var getById = function (id) {
  12381. return get(components, id);
  12382. };
  12383. return {
  12384. find: find,
  12385. filter: filter,
  12386. register: register,
  12387. unregister: unregister,
  12388. getById: getById
  12389. };
  12390. }
  12391. var factory$3 = function (detail) {
  12392. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12393. return {
  12394. uid: detail.uid,
  12395. dom: __assign({
  12396. tag: 'div',
  12397. attributes: __assign({ role: 'presentation' }, attributes)
  12398. }, domWithoutAttributes),
  12399. components: detail.components,
  12400. behaviours: get$c(detail.containerBehaviours),
  12401. events: detail.events,
  12402. domModification: detail.domModification,
  12403. eventOrder: detail.eventOrder
  12404. };
  12405. };
  12406. var Container = single$2({
  12407. name: 'Container',
  12408. factory: factory$3,
  12409. configFields: [
  12410. defaulted$1('components', []),
  12411. field$1('containerBehaviours', []),
  12412. defaulted$1('events', {}),
  12413. defaulted$1('domModification', {}),
  12414. defaulted$1('eventOrder', {})
  12415. ]
  12416. });
  12417. var takeover = function (root) {
  12418. var isAboveRoot = function (el) {
  12419. return parent(root.element).fold(function () {
  12420. return true;
  12421. }, function (parent) {
  12422. return eq$1(el, parent);
  12423. });
  12424. };
  12425. var registry = Registry();
  12426. var lookup = function (eventName, target) {
  12427. return registry.find(isAboveRoot, eventName, target);
  12428. };
  12429. var domEvents = setup$1(root.element, {
  12430. triggerEvent: function (eventName, event) {
  12431. return monitorEvent(eventName, event.target, function (logger) {
  12432. return triggerUntilStopped(lookup, eventName, event, logger);
  12433. });
  12434. }
  12435. });
  12436. var systemApi = {
  12437. debugInfo: constant('real'),
  12438. triggerEvent: function (eventName, target, data) {
  12439. monitorEvent(eventName, target, function (logger) {
  12440. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  12441. });
  12442. },
  12443. triggerFocus: function (target, originator) {
  12444. read$1(target).fold(function () {
  12445. focus$1(target);
  12446. }, function (_alloyId) {
  12447. monitorEvent(focus(), target, function (logger) {
  12448. triggerHandler(lookup, focus(), {
  12449. originator: originator,
  12450. kill: noop,
  12451. prevent: noop,
  12452. target: target
  12453. }, target, logger);
  12454. return false;
  12455. });
  12456. });
  12457. },
  12458. triggerEscape: function (comp, simulatedEvent) {
  12459. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  12460. },
  12461. getByUid: function (uid) {
  12462. return getByUid(uid);
  12463. },
  12464. getByDom: function (elem) {
  12465. return getByDom(elem);
  12466. },
  12467. build: build$1,
  12468. addToGui: function (c) {
  12469. add(c);
  12470. },
  12471. removeFromGui: function (c) {
  12472. remove$1(c);
  12473. },
  12474. addToWorld: function (c) {
  12475. addToWorld(c);
  12476. },
  12477. removeFromWorld: function (c) {
  12478. removeFromWorld(c);
  12479. },
  12480. broadcast: function (message) {
  12481. broadcast$1(message);
  12482. },
  12483. broadcastOn: function (channels, message) {
  12484. broadcastOn(channels, message);
  12485. },
  12486. broadcastEvent: function (eventName, event) {
  12487. broadcastEvent(eventName, event);
  12488. },
  12489. isConnected: always
  12490. };
  12491. var addToWorld = function (component) {
  12492. component.connect(systemApi);
  12493. if (!isText(component.element)) {
  12494. registry.register(component);
  12495. each(component.components(), addToWorld);
  12496. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  12497. }
  12498. };
  12499. var removeFromWorld = function (component) {
  12500. if (!isText(component.element)) {
  12501. each(component.components(), removeFromWorld);
  12502. registry.unregister(component);
  12503. }
  12504. component.disconnect();
  12505. };
  12506. var add = function (component) {
  12507. attach$1(root, component);
  12508. };
  12509. var remove$1 = function (component) {
  12510. detach(component);
  12511. };
  12512. var destroy = function () {
  12513. domEvents.unbind();
  12514. remove(root.element);
  12515. };
  12516. var broadcastData = function (data) {
  12517. var receivers = registry.filter(receive());
  12518. each(receivers, function (receiver) {
  12519. var descHandler = receiver.descHandler;
  12520. var handler = getCurried(descHandler);
  12521. handler(data);
  12522. });
  12523. };
  12524. var broadcast$1 = function (message) {
  12525. broadcastData({
  12526. universal: true,
  12527. data: message
  12528. });
  12529. };
  12530. var broadcastOn = function (channels, message) {
  12531. broadcastData({
  12532. universal: false,
  12533. channels: channels,
  12534. data: message
  12535. });
  12536. };
  12537. var broadcastEvent = function (eventName, event) {
  12538. var listeners = registry.filter(eventName);
  12539. return broadcast(listeners, event);
  12540. };
  12541. var getByUid = function (uid) {
  12542. return registry.getById(uid).fold(function () {
  12543. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  12544. }, Result.value);
  12545. };
  12546. var getByDom = function (elem) {
  12547. var uid = read$1(elem).getOr('not found');
  12548. return getByUid(uid);
  12549. };
  12550. addToWorld(root);
  12551. return {
  12552. root: root,
  12553. element: root.element,
  12554. destroy: destroy,
  12555. add: add,
  12556. remove: remove$1,
  12557. getByUid: getByUid,
  12558. getByDom: getByDom,
  12559. addToWorld: addToWorld,
  12560. removeFromWorld: removeFromWorld,
  12561. broadcast: broadcast$1,
  12562. broadcastOn: broadcastOn,
  12563. broadcastEvent: broadcastEvent
  12564. };
  12565. };
  12566. var renderBar = function (spec, backstage) {
  12567. return {
  12568. dom: {
  12569. tag: 'div',
  12570. classes: [
  12571. 'tox-bar',
  12572. 'tox-form__controls-h-stack'
  12573. ]
  12574. },
  12575. components: map(spec.items, backstage.interpreter)
  12576. };
  12577. };
  12578. var schema$e = constant([
  12579. defaulted$1('prefix', 'form-field'),
  12580. field$1('fieldBehaviours', [
  12581. Composing,
  12582. Representing
  12583. ])
  12584. ]);
  12585. var parts$3 = constant([
  12586. optional({
  12587. schema: [strict$1('dom')],
  12588. name: 'label'
  12589. }),
  12590. optional({
  12591. factory: {
  12592. sketch: function (spec) {
  12593. return {
  12594. uid: spec.uid,
  12595. dom: {
  12596. tag: 'span',
  12597. styles: { display: 'none' },
  12598. attributes: { 'aria-hidden': 'true' },
  12599. innerHtml: spec.text
  12600. }
  12601. };
  12602. }
  12603. },
  12604. schema: [strict$1('text')],
  12605. name: 'aria-descriptor'
  12606. }),
  12607. required({
  12608. factory: {
  12609. sketch: function (spec) {
  12610. var excludeFactory = exclude$1(spec, ['factory']);
  12611. return spec.factory.sketch(excludeFactory);
  12612. }
  12613. },
  12614. schema: [strict$1('factory')],
  12615. name: 'field'
  12616. })
  12617. ]);
  12618. var factory$4 = function (detail, components, _spec, _externals) {
  12619. var behaviours = augment(detail.fieldBehaviours, [
  12620. Composing.config({
  12621. find: function (container) {
  12622. return getPart(container, detail, 'field');
  12623. }
  12624. }),
  12625. Representing.config({
  12626. store: {
  12627. mode: 'manual',
  12628. getValue: function (field) {
  12629. return Composing.getCurrent(field).bind(Representing.getValue);
  12630. },
  12631. setValue: function (field, value) {
  12632. Composing.getCurrent(field).each(function (current) {
  12633. Representing.setValue(current, value);
  12634. });
  12635. }
  12636. }
  12637. })
  12638. ]);
  12639. var events = derive([runOnAttached(function (component, _simulatedEvent) {
  12640. var ps = getParts(component, detail, [
  12641. 'label',
  12642. 'field',
  12643. 'aria-descriptor'
  12644. ]);
  12645. ps.field().each(function (field) {
  12646. var id = generate$1(detail.prefix);
  12647. ps.label().each(function (label) {
  12648. set$1(label.element, 'for', id);
  12649. set$1(field.element, 'id', id);
  12650. });
  12651. ps['aria-descriptor']().each(function (descriptor) {
  12652. var descriptorId = generate$1(detail.prefix);
  12653. set$1(descriptor.element, 'id', descriptorId);
  12654. set$1(field.element, 'aria-describedby', descriptorId);
  12655. });
  12656. });
  12657. })]);
  12658. var apis = {
  12659. getField: function (container) {
  12660. return getPart(container, detail, 'field');
  12661. },
  12662. getLabel: function (container) {
  12663. return getPart(container, detail, 'label');
  12664. }
  12665. };
  12666. return {
  12667. uid: detail.uid,
  12668. dom: detail.dom,
  12669. components: components,
  12670. behaviours: behaviours,
  12671. events: events,
  12672. apis: apis
  12673. };
  12674. };
  12675. var FormField = composite$1({
  12676. name: 'FormField',
  12677. configFields: schema$e(),
  12678. partFields: parts$3(),
  12679. factory: factory$4,
  12680. apis: {
  12681. getField: function (apis, comp) {
  12682. return apis.getField(comp);
  12683. },
  12684. getLabel: function (apis, comp) {
  12685. return apis.getLabel(comp);
  12686. }
  12687. }
  12688. });
  12689. var exhibit$4 = function (base, tabConfig) {
  12690. return nu$6({
  12691. attributes: wrapAll$1([{
  12692. key: tabConfig.tabAttr,
  12693. value: 'true'
  12694. }])
  12695. });
  12696. };
  12697. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  12698. __proto__: null,
  12699. exhibit: exhibit$4
  12700. });
  12701. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  12702. var Tabstopping = create$1({
  12703. fields: TabstopSchema,
  12704. name: 'tabstopping',
  12705. active: ActiveTabstopping
  12706. });
  12707. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  12708. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  12709. return FormField.sketch(spec);
  12710. };
  12711. var renderFormField = function (pLabel, pField) {
  12712. return renderFormFieldWith(pLabel, pField, [], []);
  12713. };
  12714. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  12715. return {
  12716. dom: renderFormFieldDomWith(extraClasses),
  12717. components: pLabel.toArray().concat([pField]),
  12718. fieldBehaviours: derive$1(extraBehaviours)
  12719. };
  12720. };
  12721. var renderFormFieldDom = function () {
  12722. return renderFormFieldDomWith([]);
  12723. };
  12724. var renderFormFieldDomWith = function (extraClasses) {
  12725. return {
  12726. tag: 'div',
  12727. classes: ['tox-form__group'].concat(extraClasses)
  12728. };
  12729. };
  12730. var renderLabel = function (label, providersBackstage) {
  12731. return FormField.parts.label({
  12732. dom: {
  12733. tag: 'label',
  12734. classes: ['tox-label'],
  12735. innerHtml: providersBackstage.translate(label)
  12736. }
  12737. });
  12738. };
  12739. var formChangeEvent = generate$1('form-component-change');
  12740. var formCloseEvent = generate$1('form-close');
  12741. var formCancelEvent = generate$1('form-cancel');
  12742. var formActionEvent = generate$1('form-action');
  12743. var formSubmitEvent = generate$1('form-submit');
  12744. var formBlockEvent = generate$1('form-block');
  12745. var formUnblockEvent = generate$1('form-unblock');
  12746. var formTabChangeEvent = generate$1('form-tabchange');
  12747. var formResizeEvent = generate$1('form-resize');
  12748. var renderCollection = function (spec, providersBackstage) {
  12749. var _a;
  12750. var pLabel = spec.label.map(function (label) {
  12751. return renderLabel(label, providersBackstage);
  12752. });
  12753. var runOnItem = function (f) {
  12754. return function (comp, se) {
  12755. closest$3(se.event.target, '[data-collection-item-value]').each(function (target) {
  12756. f(comp, se, target, get$2(target, 'data-collection-item-value'));
  12757. });
  12758. };
  12759. };
  12760. var escapeAttribute = function (ch) {
  12761. if (ch === '"') {
  12762. return '&quot;';
  12763. }
  12764. return ch;
  12765. };
  12766. var setContents = function (comp, items) {
  12767. var htmlLines = map(items, function (item) {
  12768. var itemText = global$6.translate(item.text);
  12769. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  12770. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  12771. var mapItemName = {
  12772. '_': ' ',
  12773. ' - ': ' ',
  12774. '-': ' '
  12775. };
  12776. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  12777. return mapItemName[match];
  12778. });
  12779. var readonlyClass = providersBackstage.isReadOnly() ? ' tox-collection__item--state-disabled' : '';
  12780. return '<div class="tox-collection__item' + readonlyClass + '" tabindex="-1" data-collection-item-value="' + escapeAttribute(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  12781. });
  12782. var chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk(htmlLines, spec.columns) : [htmlLines];
  12783. var html = map(chunks, function (ch) {
  12784. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  12785. });
  12786. set(comp.element, html.join(''));
  12787. };
  12788. var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  12789. se.stop();
  12790. if (!providersBackstage.isReadOnly()) {
  12791. emitWith(comp, formActionEvent, {
  12792. name: spec.name,
  12793. value: itemValue
  12794. });
  12795. }
  12796. });
  12797. var collectionEvents = [
  12798. run(mouseover(), runOnItem(function (comp, se, tgt) {
  12799. focus$1(tgt);
  12800. })),
  12801. run(click(), onClick),
  12802. run(tap(), onClick),
  12803. run(focusin(), runOnItem(function (comp, se, tgt) {
  12804. descendant$1(comp.element, '.' + activeClass).each(function (currentActive) {
  12805. remove$4(currentActive, activeClass);
  12806. });
  12807. add$2(tgt, activeClass);
  12808. })),
  12809. run(focusout(), runOnItem(function (comp) {
  12810. descendant$1(comp.element, '.' + activeClass).each(function (currentActive) {
  12811. remove$4(currentActive, activeClass);
  12812. });
  12813. })),
  12814. runOnExecute(runOnItem(function (comp, se, tgt, itemValue) {
  12815. emitWith(comp, formActionEvent, {
  12816. name: spec.name,
  12817. value: itemValue
  12818. });
  12819. }))
  12820. ];
  12821. var iterCollectionItems = function (comp, applyAttributes) {
  12822. return map(descendants(comp.element, '.tox-collection__item'), applyAttributes);
  12823. };
  12824. var pField = FormField.parts.field({
  12825. dom: {
  12826. tag: 'div',
  12827. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  12828. },
  12829. components: [],
  12830. factory: { sketch: identity },
  12831. behaviours: derive$1([
  12832. Disabling.config({
  12833. disabled: providersBackstage.isReadOnly,
  12834. onDisabled: function (comp) {
  12835. iterCollectionItems(comp, function (childElm) {
  12836. add$2(childElm, 'tox-collection__item--state-disabled');
  12837. set$1(childElm, 'aria-disabled', true);
  12838. });
  12839. },
  12840. onEnabled: function (comp) {
  12841. iterCollectionItems(comp, function (childElm) {
  12842. remove$4(childElm, 'tox-collection__item--state-disabled');
  12843. remove$1(childElm, 'aria-disabled');
  12844. });
  12845. }
  12846. }),
  12847. receivingConfig(),
  12848. Replacing.config({}),
  12849. Representing.config({
  12850. store: {
  12851. mode: 'memory',
  12852. initialValue: []
  12853. },
  12854. onSetValue: function (comp, items) {
  12855. setContents(comp, items);
  12856. if (spec.columns === 'auto') {
  12857. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  12858. var numRows = _a.numRows, numColumns = _a.numColumns;
  12859. Keying.setGridSize(comp, numRows, numColumns);
  12860. });
  12861. }
  12862. emit(comp, formResizeEvent);
  12863. }
  12864. }),
  12865. Tabstopping.config({}),
  12866. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  12867. config('collection-events', collectionEvents)
  12868. ]),
  12869. eventOrder: (_a = {}, _a[execute()] = [
  12870. 'disabling',
  12871. 'alloy.base.behaviour',
  12872. 'collection-events'
  12873. ], _a)
  12874. });
  12875. var extraClasses = ['tox-form__group--collection'];
  12876. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  12877. };
  12878. var schema$f = constant([
  12879. option('data'),
  12880. defaulted$1('inputAttributes', {}),
  12881. defaulted$1('inputStyles', {}),
  12882. defaulted$1('tag', 'input'),
  12883. defaulted$1('inputClasses', []),
  12884. onHandler('onSetValue'),
  12885. defaulted$1('styles', {}),
  12886. defaulted$1('eventOrder', {}),
  12887. field$1('inputBehaviours', [
  12888. Representing,
  12889. Focusing
  12890. ]),
  12891. defaulted$1('selectOnFocus', true)
  12892. ]);
  12893. var focusBehaviours = function (detail) {
  12894. return derive$1([Focusing.config({
  12895. onFocus: !detail.selectOnFocus ? noop : function (component) {
  12896. var input = component.element;
  12897. var value = get$5(input);
  12898. input.dom.setSelectionRange(0, value.length);
  12899. }
  12900. })]);
  12901. };
  12902. var behaviours = function (detail) {
  12903. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  12904. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  12905. return { initialValue: data };
  12906. }).getOr({})), {
  12907. getValue: function (input) {
  12908. return get$5(input.element);
  12909. },
  12910. setValue: function (input, data) {
  12911. var current = get$5(input.element);
  12912. if (current !== data) {
  12913. set$3(input.element, data);
  12914. }
  12915. }
  12916. }),
  12917. onSetValue: detail.onSetValue
  12918. })]));
  12919. };
  12920. var dom$2 = function (detail) {
  12921. return {
  12922. tag: detail.tag,
  12923. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  12924. styles: detail.inputStyles,
  12925. classes: detail.inputClasses
  12926. };
  12927. };
  12928. var factory$5 = function (detail, _spec) {
  12929. return {
  12930. uid: detail.uid,
  12931. dom: dom$2(detail),
  12932. components: [],
  12933. behaviours: behaviours(detail),
  12934. eventOrder: detail.eventOrder
  12935. };
  12936. };
  12937. var Input = single$2({
  12938. name: 'Input',
  12939. configFields: schema$f(),
  12940. factory: factory$5
  12941. });
  12942. var exports$1 = {}, module = { exports: exports$1 };
  12943. (function (define, exports, module, require) {
  12944. (function (f) {
  12945. if (typeof exports === 'object' && typeof module !== 'undefined') {
  12946. module.exports = f();
  12947. } else if (typeof define === 'function' && define.amd) {
  12948. define([], f);
  12949. } else {
  12950. var g;
  12951. if (typeof window !== 'undefined') {
  12952. g = window;
  12953. } else if (typeof global !== 'undefined') {
  12954. g = global;
  12955. } else if (typeof self !== 'undefined') {
  12956. g = self;
  12957. } else {
  12958. g = this;
  12959. }
  12960. g.EphoxContactWrapper = f();
  12961. }
  12962. }(function () {
  12963. return function () {
  12964. function r(e, n, t) {
  12965. function o(i, f) {
  12966. if (!n[i]) {
  12967. if (!e[i]) {
  12968. var c = 'function' == typeof require && require;
  12969. if (!f && c)
  12970. return c(i, !0);
  12971. if (u)
  12972. return u(i, !0);
  12973. var a = new Error('Cannot find module \'' + i + '\'');
  12974. throw a.code = 'MODULE_NOT_FOUND', a;
  12975. }
  12976. var p = n[i] = { exports: {} };
  12977. e[i][0].call(p.exports, function (r) {
  12978. var n = e[i][1][r];
  12979. return o(n || r);
  12980. }, p, p.exports, r, e, n, t);
  12981. }
  12982. return n[i].exports;
  12983. }
  12984. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  12985. o(t[i]);
  12986. return o;
  12987. }
  12988. return r;
  12989. }()({
  12990. 1: [
  12991. function (require, module, exports) {
  12992. var process = module.exports = {};
  12993. var cachedSetTimeout;
  12994. var cachedClearTimeout;
  12995. function defaultSetTimout() {
  12996. throw new Error('setTimeout has not been defined');
  12997. }
  12998. function defaultClearTimeout() {
  12999. throw new Error('clearTimeout has not been defined');
  13000. }
  13001. (function () {
  13002. try {
  13003. if (typeof setTimeout === 'function') {
  13004. cachedSetTimeout = setTimeout;
  13005. } else {
  13006. cachedSetTimeout = defaultSetTimout;
  13007. }
  13008. } catch (e) {
  13009. cachedSetTimeout = defaultSetTimout;
  13010. }
  13011. try {
  13012. if (typeof clearTimeout === 'function') {
  13013. cachedClearTimeout = clearTimeout;
  13014. } else {
  13015. cachedClearTimeout = defaultClearTimeout;
  13016. }
  13017. } catch (e) {
  13018. cachedClearTimeout = defaultClearTimeout;
  13019. }
  13020. }());
  13021. function runTimeout(fun) {
  13022. if (cachedSetTimeout === setTimeout) {
  13023. return setTimeout(fun, 0);
  13024. }
  13025. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  13026. cachedSetTimeout = setTimeout;
  13027. return setTimeout(fun, 0);
  13028. }
  13029. try {
  13030. return cachedSetTimeout(fun, 0);
  13031. } catch (e) {
  13032. try {
  13033. return cachedSetTimeout.call(null, fun, 0);
  13034. } catch (e) {
  13035. return cachedSetTimeout.call(this, fun, 0);
  13036. }
  13037. }
  13038. }
  13039. function runClearTimeout(marker) {
  13040. if (cachedClearTimeout === clearTimeout) {
  13041. return clearTimeout(marker);
  13042. }
  13043. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  13044. cachedClearTimeout = clearTimeout;
  13045. return clearTimeout(marker);
  13046. }
  13047. try {
  13048. return cachedClearTimeout(marker);
  13049. } catch (e) {
  13050. try {
  13051. return cachedClearTimeout.call(null, marker);
  13052. } catch (e) {
  13053. return cachedClearTimeout.call(this, marker);
  13054. }
  13055. }
  13056. }
  13057. var queue = [];
  13058. var draining = false;
  13059. var currentQueue;
  13060. var queueIndex = -1;
  13061. function cleanUpNextTick() {
  13062. if (!draining || !currentQueue) {
  13063. return;
  13064. }
  13065. draining = false;
  13066. if (currentQueue.length) {
  13067. queue = currentQueue.concat(queue);
  13068. } else {
  13069. queueIndex = -1;
  13070. }
  13071. if (queue.length) {
  13072. drainQueue();
  13073. }
  13074. }
  13075. function drainQueue() {
  13076. if (draining) {
  13077. return;
  13078. }
  13079. var timeout = runTimeout(cleanUpNextTick);
  13080. draining = true;
  13081. var len = queue.length;
  13082. while (len) {
  13083. currentQueue = queue;
  13084. queue = [];
  13085. while (++queueIndex < len) {
  13086. if (currentQueue) {
  13087. currentQueue[queueIndex].run();
  13088. }
  13089. }
  13090. queueIndex = -1;
  13091. len = queue.length;
  13092. }
  13093. currentQueue = null;
  13094. draining = false;
  13095. runClearTimeout(timeout);
  13096. }
  13097. process.nextTick = function (fun) {
  13098. var args = new Array(arguments.length - 1);
  13099. if (arguments.length > 1) {
  13100. for (var i = 1; i < arguments.length; i++) {
  13101. args[i - 1] = arguments[i];
  13102. }
  13103. }
  13104. queue.push(new Item(fun, args));
  13105. if (queue.length === 1 && !draining) {
  13106. runTimeout(drainQueue);
  13107. }
  13108. };
  13109. function Item(fun, array) {
  13110. this.fun = fun;
  13111. this.array = array;
  13112. }
  13113. Item.prototype.run = function () {
  13114. this.fun.apply(null, this.array);
  13115. };
  13116. process.title = 'browser';
  13117. process.browser = true;
  13118. process.env = {};
  13119. process.argv = [];
  13120. process.version = '';
  13121. process.versions = {};
  13122. function noop() {
  13123. }
  13124. process.on = noop;
  13125. process.addListener = noop;
  13126. process.once = noop;
  13127. process.off = noop;
  13128. process.removeListener = noop;
  13129. process.removeAllListeners = noop;
  13130. process.emit = noop;
  13131. process.prependListener = noop;
  13132. process.prependOnceListener = noop;
  13133. process.listeners = function (name) {
  13134. return [];
  13135. };
  13136. process.binding = function (name) {
  13137. throw new Error('process.binding is not supported');
  13138. };
  13139. process.cwd = function () {
  13140. return '/';
  13141. };
  13142. process.chdir = function (dir) {
  13143. throw new Error('process.chdir is not supported');
  13144. };
  13145. process.umask = function () {
  13146. return 0;
  13147. };
  13148. },
  13149. {}
  13150. ],
  13151. 2: [
  13152. function (require, module, exports) {
  13153. (function (setImmediate) {
  13154. (function (root) {
  13155. var setTimeoutFunc = setTimeout;
  13156. function noop() {
  13157. }
  13158. function bind(fn, thisArg) {
  13159. return function () {
  13160. fn.apply(thisArg, arguments);
  13161. };
  13162. }
  13163. function Promise(fn) {
  13164. if (typeof this !== 'object')
  13165. throw new TypeError('Promises must be constructed via new');
  13166. if (typeof fn !== 'function')
  13167. throw new TypeError('not a function');
  13168. this._state = 0;
  13169. this._handled = false;
  13170. this._value = undefined;
  13171. this._deferreds = [];
  13172. doResolve(fn, this);
  13173. }
  13174. function handle(self, deferred) {
  13175. while (self._state === 3) {
  13176. self = self._value;
  13177. }
  13178. if (self._state === 0) {
  13179. self._deferreds.push(deferred);
  13180. return;
  13181. }
  13182. self._handled = true;
  13183. Promise._immediateFn(function () {
  13184. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  13185. if (cb === null) {
  13186. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  13187. return;
  13188. }
  13189. var ret;
  13190. try {
  13191. ret = cb(self._value);
  13192. } catch (e) {
  13193. reject(deferred.promise, e);
  13194. return;
  13195. }
  13196. resolve(deferred.promise, ret);
  13197. });
  13198. }
  13199. function resolve(self, newValue) {
  13200. try {
  13201. if (newValue === self)
  13202. throw new TypeError('A promise cannot be resolved with itself.');
  13203. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  13204. var then = newValue.then;
  13205. if (newValue instanceof Promise) {
  13206. self._state = 3;
  13207. self._value = newValue;
  13208. finale(self);
  13209. return;
  13210. } else if (typeof then === 'function') {
  13211. doResolve(bind(then, newValue), self);
  13212. return;
  13213. }
  13214. }
  13215. self._state = 1;
  13216. self._value = newValue;
  13217. finale(self);
  13218. } catch (e) {
  13219. reject(self, e);
  13220. }
  13221. }
  13222. function reject(self, newValue) {
  13223. self._state = 2;
  13224. self._value = newValue;
  13225. finale(self);
  13226. }
  13227. function finale(self) {
  13228. if (self._state === 2 && self._deferreds.length === 0) {
  13229. Promise._immediateFn(function () {
  13230. if (!self._handled) {
  13231. Promise._unhandledRejectionFn(self._value);
  13232. }
  13233. });
  13234. }
  13235. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  13236. handle(self, self._deferreds[i]);
  13237. }
  13238. self._deferreds = null;
  13239. }
  13240. function Handler(onFulfilled, onRejected, promise) {
  13241. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  13242. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  13243. this.promise = promise;
  13244. }
  13245. function doResolve(fn, self) {
  13246. var done = false;
  13247. try {
  13248. fn(function (value) {
  13249. if (done)
  13250. return;
  13251. done = true;
  13252. resolve(self, value);
  13253. }, function (reason) {
  13254. if (done)
  13255. return;
  13256. done = true;
  13257. reject(self, reason);
  13258. });
  13259. } catch (ex) {
  13260. if (done)
  13261. return;
  13262. done = true;
  13263. reject(self, ex);
  13264. }
  13265. }
  13266. Promise.prototype['catch'] = function (onRejected) {
  13267. return this.then(null, onRejected);
  13268. };
  13269. Promise.prototype.then = function (onFulfilled, onRejected) {
  13270. var prom = new this.constructor(noop);
  13271. handle(this, new Handler(onFulfilled, onRejected, prom));
  13272. return prom;
  13273. };
  13274. Promise.all = function (arr) {
  13275. var args = Array.prototype.slice.call(arr);
  13276. return new Promise(function (resolve, reject) {
  13277. if (args.length === 0)
  13278. return resolve([]);
  13279. var remaining = args.length;
  13280. function res(i, val) {
  13281. try {
  13282. if (val && (typeof val === 'object' || typeof val === 'function')) {
  13283. var then = val.then;
  13284. if (typeof then === 'function') {
  13285. then.call(val, function (val) {
  13286. res(i, val);
  13287. }, reject);
  13288. return;
  13289. }
  13290. }
  13291. args[i] = val;
  13292. if (--remaining === 0) {
  13293. resolve(args);
  13294. }
  13295. } catch (ex) {
  13296. reject(ex);
  13297. }
  13298. }
  13299. for (var i = 0; i < args.length; i++) {
  13300. res(i, args[i]);
  13301. }
  13302. });
  13303. };
  13304. Promise.resolve = function (value) {
  13305. if (value && typeof value === 'object' && value.constructor === Promise) {
  13306. return value;
  13307. }
  13308. return new Promise(function (resolve) {
  13309. resolve(value);
  13310. });
  13311. };
  13312. Promise.reject = function (value) {
  13313. return new Promise(function (resolve, reject) {
  13314. reject(value);
  13315. });
  13316. };
  13317. Promise.race = function (values) {
  13318. return new Promise(function (resolve, reject) {
  13319. for (var i = 0, len = values.length; i < len; i++) {
  13320. values[i].then(resolve, reject);
  13321. }
  13322. });
  13323. };
  13324. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  13325. setImmediate(fn);
  13326. } : function (fn) {
  13327. setTimeoutFunc(fn, 0);
  13328. };
  13329. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  13330. if (typeof console !== 'undefined' && console) {
  13331. console.warn('Possible Unhandled Promise Rejection:', err);
  13332. }
  13333. };
  13334. Promise._setImmediateFn = function _setImmediateFn(fn) {
  13335. Promise._immediateFn = fn;
  13336. };
  13337. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  13338. Promise._unhandledRejectionFn = fn;
  13339. };
  13340. if (typeof module !== 'undefined' && module.exports) {
  13341. module.exports = Promise;
  13342. } else if (!root.Promise) {
  13343. root.Promise = Promise;
  13344. }
  13345. }(this));
  13346. }.call(this, require('timers').setImmediate));
  13347. },
  13348. { 'timers': 3 }
  13349. ],
  13350. 3: [
  13351. function (require, module, exports) {
  13352. (function (setImmediate, clearImmediate) {
  13353. var nextTick = require('process/browser.js').nextTick;
  13354. var apply = Function.prototype.apply;
  13355. var slice = Array.prototype.slice;
  13356. var immediateIds = {};
  13357. var nextImmediateId = 0;
  13358. exports.setTimeout = function () {
  13359. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  13360. };
  13361. exports.setInterval = function () {
  13362. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  13363. };
  13364. exports.clearTimeout = exports.clearInterval = function (timeout) {
  13365. timeout.close();
  13366. };
  13367. function Timeout(id, clearFn) {
  13368. this._id = id;
  13369. this._clearFn = clearFn;
  13370. }
  13371. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  13372. };
  13373. Timeout.prototype.close = function () {
  13374. this._clearFn.call(window, this._id);
  13375. };
  13376. exports.enroll = function (item, msecs) {
  13377. clearTimeout(item._idleTimeoutId);
  13378. item._idleTimeout = msecs;
  13379. };
  13380. exports.unenroll = function (item) {
  13381. clearTimeout(item._idleTimeoutId);
  13382. item._idleTimeout = -1;
  13383. };
  13384. exports._unrefActive = exports.active = function (item) {
  13385. clearTimeout(item._idleTimeoutId);
  13386. var msecs = item._idleTimeout;
  13387. if (msecs >= 0) {
  13388. item._idleTimeoutId = setTimeout(function onTimeout() {
  13389. if (item._onTimeout)
  13390. item._onTimeout();
  13391. }, msecs);
  13392. }
  13393. };
  13394. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  13395. var id = nextImmediateId++;
  13396. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13397. immediateIds[id] = true;
  13398. nextTick(function onNextTick() {
  13399. if (immediateIds[id]) {
  13400. if (args) {
  13401. fn.apply(null, args);
  13402. } else {
  13403. fn.call(null);
  13404. }
  13405. exports.clearImmediate(id);
  13406. }
  13407. });
  13408. return id;
  13409. };
  13410. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  13411. delete immediateIds[id];
  13412. };
  13413. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  13414. },
  13415. {
  13416. 'process/browser.js': 1,
  13417. 'timers': 3
  13418. }
  13419. ],
  13420. 4: [
  13421. function (require, module, exports) {
  13422. var promisePolyfill = require('promise-polyfill');
  13423. var Global = function () {
  13424. if (typeof window !== 'undefined') {
  13425. return window;
  13426. } else {
  13427. return Function('return this;')();
  13428. }
  13429. }();
  13430. module.exports = { boltExport: Global.Promise || promisePolyfill };
  13431. },
  13432. { 'promise-polyfill': 2 }
  13433. ]
  13434. }, {}, [4])(4);
  13435. }));
  13436. }(undefined, exports$1, module, undefined));
  13437. var Promise = module.exports.boltExport;
  13438. var nu$a = function (baseFn) {
  13439. var data = Optional.none();
  13440. var callbacks = [];
  13441. var map = function (f) {
  13442. return nu$a(function (nCallback) {
  13443. get(function (data) {
  13444. nCallback(f(data));
  13445. });
  13446. });
  13447. };
  13448. var get = function (nCallback) {
  13449. if (isReady()) {
  13450. call(nCallback);
  13451. } else {
  13452. callbacks.push(nCallback);
  13453. }
  13454. };
  13455. var set = function (x) {
  13456. if (!isReady()) {
  13457. data = Optional.some(x);
  13458. run(callbacks);
  13459. callbacks = [];
  13460. }
  13461. };
  13462. var isReady = function () {
  13463. return data.isSome();
  13464. };
  13465. var run = function (cbs) {
  13466. each(cbs, call);
  13467. };
  13468. var call = function (cb) {
  13469. data.each(function (x) {
  13470. setTimeout(function () {
  13471. cb(x);
  13472. }, 0);
  13473. });
  13474. };
  13475. baseFn(set);
  13476. return {
  13477. get: get,
  13478. map: map,
  13479. isReady: isReady
  13480. };
  13481. };
  13482. var pure = function (a) {
  13483. return nu$a(function (callback) {
  13484. callback(a);
  13485. });
  13486. };
  13487. var LazyValue = {
  13488. nu: nu$a,
  13489. pure: pure
  13490. };
  13491. var errorReporter = function (err) {
  13492. setTimeout(function () {
  13493. throw err;
  13494. }, 0);
  13495. };
  13496. var make$3 = function (run) {
  13497. var get = function (callback) {
  13498. run().then(callback, errorReporter);
  13499. };
  13500. var map = function (fab) {
  13501. return make$3(function () {
  13502. return run().then(fab);
  13503. });
  13504. };
  13505. var bind = function (aFutureB) {
  13506. return make$3(function () {
  13507. return run().then(function (v) {
  13508. return aFutureB(v).toPromise();
  13509. });
  13510. });
  13511. };
  13512. var anonBind = function (futureB) {
  13513. return make$3(function () {
  13514. return run().then(function () {
  13515. return futureB.toPromise();
  13516. });
  13517. });
  13518. };
  13519. var toLazy = function () {
  13520. return LazyValue.nu(get);
  13521. };
  13522. var toCached = function () {
  13523. var cache = null;
  13524. return make$3(function () {
  13525. if (cache === null) {
  13526. cache = run();
  13527. }
  13528. return cache;
  13529. });
  13530. };
  13531. var toPromise = run;
  13532. return {
  13533. map: map,
  13534. bind: bind,
  13535. anonBind: anonBind,
  13536. toLazy: toLazy,
  13537. toCached: toCached,
  13538. toPromise: toPromise,
  13539. get: get
  13540. };
  13541. };
  13542. var nu$b = function (baseFn) {
  13543. return make$3(function () {
  13544. return new Promise(baseFn);
  13545. });
  13546. };
  13547. var pure$1 = function (a) {
  13548. return make$3(function () {
  13549. return Promise.resolve(a);
  13550. });
  13551. };
  13552. var Future = {
  13553. nu: nu$b,
  13554. pure: pure$1
  13555. };
  13556. var ariaElements = [
  13557. 'input',
  13558. 'textarea'
  13559. ];
  13560. var isAriaElement = function (elem) {
  13561. var name$1 = name(elem);
  13562. return contains(ariaElements, name$1);
  13563. };
  13564. var markValid = function (component, invalidConfig) {
  13565. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13566. remove$4(elem, invalidConfig.invalidClass);
  13567. invalidConfig.notify.each(function (notifyInfo) {
  13568. if (isAriaElement(component.element)) {
  13569. set$1(component.element, 'aria-invalid', false);
  13570. }
  13571. notifyInfo.getContainer(component).each(function (container) {
  13572. set(container, notifyInfo.validHtml);
  13573. });
  13574. notifyInfo.onValid(component);
  13575. });
  13576. };
  13577. var markInvalid = function (component, invalidConfig, invalidState, text) {
  13578. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13579. add$2(elem, invalidConfig.invalidClass);
  13580. invalidConfig.notify.each(function (notifyInfo) {
  13581. if (isAriaElement(component.element)) {
  13582. set$1(component.element, 'aria-invalid', true);
  13583. }
  13584. notifyInfo.getContainer(component).each(function (container) {
  13585. set(container, text);
  13586. });
  13587. notifyInfo.onInvalid(component, text);
  13588. });
  13589. };
  13590. var query = function (component, invalidConfig, _invalidState) {
  13591. return invalidConfig.validator.fold(function () {
  13592. return Future.pure(Result.value(true));
  13593. }, function (validatorInfo) {
  13594. return validatorInfo.validate(component);
  13595. });
  13596. };
  13597. var run$1 = function (component, invalidConfig, invalidState) {
  13598. invalidConfig.notify.each(function (notifyInfo) {
  13599. notifyInfo.onValidate(component);
  13600. });
  13601. return query(component, invalidConfig).map(function (valid) {
  13602. if (component.getSystem().isConnected()) {
  13603. return valid.fold(function (err) {
  13604. markInvalid(component, invalidConfig, invalidState, err);
  13605. return Result.error(err);
  13606. }, function (v) {
  13607. markValid(component, invalidConfig);
  13608. return Result.value(v);
  13609. });
  13610. } else {
  13611. return Result.error('No longer in system');
  13612. }
  13613. });
  13614. };
  13615. var isInvalid = function (component, invalidConfig) {
  13616. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13617. return has$2(elem, invalidConfig.invalidClass);
  13618. };
  13619. var InvalidateApis = /*#__PURE__*/Object.freeze({
  13620. __proto__: null,
  13621. markValid: markValid,
  13622. markInvalid: markInvalid,
  13623. query: query,
  13624. run: run$1,
  13625. isInvalid: isInvalid
  13626. });
  13627. var events$a = function (invalidConfig, invalidState) {
  13628. return invalidConfig.validator.map(function (validatorInfo) {
  13629. return derive([run(validatorInfo.onEvent, function (component) {
  13630. run$1(component, invalidConfig, invalidState).get(identity);
  13631. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  13632. run$1(component, invalidConfig, invalidState).get(noop);
  13633. })] : []));
  13634. }).getOr({});
  13635. };
  13636. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  13637. __proto__: null,
  13638. events: events$a
  13639. });
  13640. var InvalidateSchema = [
  13641. strict$1('invalidClass'),
  13642. defaulted$1('getRoot', Optional.none),
  13643. optionObjOf('notify', [
  13644. defaulted$1('aria', 'alert'),
  13645. defaulted$1('getContainer', Optional.none),
  13646. defaulted$1('validHtml', ''),
  13647. onHandler('onValid'),
  13648. onHandler('onInvalid'),
  13649. onHandler('onValidate')
  13650. ]),
  13651. optionObjOf('validator', [
  13652. strict$1('validate'),
  13653. defaulted$1('onEvent', 'input'),
  13654. defaulted$1('validateOnLoad', true)
  13655. ])
  13656. ];
  13657. var Invalidating = create$1({
  13658. fields: InvalidateSchema,
  13659. name: 'invalidating',
  13660. active: ActiveInvalidate,
  13661. apis: InvalidateApis,
  13662. extra: {
  13663. validation: function (validator) {
  13664. return function (component) {
  13665. var v = Representing.getValue(component);
  13666. return Future.pure(validator(v));
  13667. };
  13668. }
  13669. }
  13670. });
  13671. var getCoupled = function (component, coupleConfig, coupleState, name) {
  13672. return coupleState.getOrCreate(component, coupleConfig, name);
  13673. };
  13674. var CouplingApis = /*#__PURE__*/Object.freeze({
  13675. __proto__: null,
  13676. getCoupled: getCoupled
  13677. });
  13678. var CouplingSchema = [strictOf('others', setOf$1(Result.value, anyValue$1()))];
  13679. var init$5 = function () {
  13680. var coupled = {};
  13681. var getOrCreate = function (component, coupleConfig, name) {
  13682. var available = keys(coupleConfig.others);
  13683. if (!available) {
  13684. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  13685. } else {
  13686. return get(coupled, name).getOrThunk(function () {
  13687. var builder = get(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  13688. var spec = builder(component);
  13689. var built = component.getSystem().build(spec);
  13690. coupled[name] = built;
  13691. return built;
  13692. });
  13693. }
  13694. };
  13695. var readState = constant({});
  13696. return nu$5({
  13697. readState: readState,
  13698. getOrCreate: getOrCreate
  13699. });
  13700. };
  13701. var CouplingState = /*#__PURE__*/Object.freeze({
  13702. __proto__: null,
  13703. init: init$5
  13704. });
  13705. var Coupling = create$1({
  13706. fields: CouplingSchema,
  13707. name: 'coupling',
  13708. apis: CouplingApis,
  13709. state: CouplingState
  13710. });
  13711. var suffix = constant('sink');
  13712. var partType = constant(optional({
  13713. name: suffix(),
  13714. overrides: constant({
  13715. dom: { tag: 'div' },
  13716. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  13717. events: derive([
  13718. cutter(keydown()),
  13719. cutter(mousedown()),
  13720. cutter(click())
  13721. ])
  13722. })
  13723. }));
  13724. var HighlightOnOpen;
  13725. (function (HighlightOnOpen) {
  13726. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  13727. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  13728. }(HighlightOnOpen || (HighlightOnOpen = {})));
  13729. var getAnchor = function (detail, component) {
  13730. var hotspot = detail.getHotspot(component).getOr(component);
  13731. var anchor = 'hotspot';
  13732. var overrides = detail.getAnchorOverrides();
  13733. return detail.layouts.fold(function () {
  13734. return {
  13735. anchor: anchor,
  13736. hotspot: hotspot,
  13737. overrides: overrides
  13738. };
  13739. }, function (layouts) {
  13740. return {
  13741. anchor: anchor,
  13742. hotspot: hotspot,
  13743. overrides: overrides,
  13744. layouts: layouts
  13745. };
  13746. });
  13747. };
  13748. var fetch = function (detail, mapFetch, component) {
  13749. var fetcher = detail.fetch;
  13750. return fetcher(component).map(mapFetch);
  13751. };
  13752. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  13753. var futureData = fetch(detail, mapFetch, component);
  13754. var getLazySink = getSink(component, detail);
  13755. return futureData.map(function (tdata) {
  13756. return tdata.bind(function (data) {
  13757. return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  13758. uid: generate$2(''),
  13759. data: data,
  13760. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  13761. onOpenMenu: function (tmenu, menu) {
  13762. var sink = getLazySink().getOrDie();
  13763. Positioning.position(sink, anchor, menu);
  13764. Sandboxing.decloak(sandbox);
  13765. },
  13766. onOpenSubmenu: function (tmenu, item, submenu) {
  13767. var sink = getLazySink().getOrDie();
  13768. Positioning.position(sink, {
  13769. anchor: 'submenu',
  13770. item: item
  13771. }, submenu);
  13772. Sandboxing.decloak(sandbox);
  13773. },
  13774. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  13775. var sink = getLazySink().getOrDie();
  13776. Positioning.position(sink, anchor, primaryMenu);
  13777. each(submenuTriggers, function (st) {
  13778. Positioning.position(sink, {
  13779. anchor: 'submenu',
  13780. item: st.triggeringItem
  13781. }, st.triggeredMenu);
  13782. });
  13783. },
  13784. onEscape: function () {
  13785. Focusing.focus(component);
  13786. Sandboxing.close(sandbox);
  13787. return Optional.some(true);
  13788. }
  13789. })));
  13790. });
  13791. });
  13792. };
  13793. var open$1 = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  13794. var anchor = getAnchor(detail, hotspot);
  13795. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  13796. return processed.map(function (tdata) {
  13797. tdata.fold(function () {
  13798. if (Sandboxing.isOpen(sandbox)) {
  13799. Sandboxing.close(sandbox);
  13800. }
  13801. }, function (data) {
  13802. Sandboxing.cloak(sandbox);
  13803. Sandboxing.open(sandbox, data);
  13804. onOpenSync(sandbox);
  13805. });
  13806. return sandbox;
  13807. });
  13808. };
  13809. var close$1 = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  13810. Sandboxing.close(sandbox);
  13811. return Future.pure(sandbox);
  13812. };
  13813. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  13814. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  13815. var showing = Sandboxing.isOpen(sandbox);
  13816. var action = showing ? close$1 : open$1;
  13817. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  13818. };
  13819. var matchWidth = function (hotspot, container, useMinWidth) {
  13820. var menu = Composing.getCurrent(container).getOr(container);
  13821. var buttonWidth = get$7(hotspot.element);
  13822. if (useMinWidth) {
  13823. set$2(menu.element, 'min-width', buttonWidth + 'px');
  13824. } else {
  13825. set$4(menu.element, buttonWidth);
  13826. }
  13827. };
  13828. var getSink = function (anyInSystem, sinkDetail) {
  13829. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  13830. return function () {
  13831. return Result.value(internalSink);
  13832. };
  13833. }).getOrThunk(function () {
  13834. return sinkDetail.lazySink.fold(function () {
  13835. return function () {
  13836. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  13837. };
  13838. }, function (lazySinkFn) {
  13839. return function () {
  13840. return lazySinkFn(anyInSystem);
  13841. };
  13842. });
  13843. });
  13844. };
  13845. var doRepositionMenus = function (sandbox) {
  13846. Sandboxing.getState(sandbox).each(function (tmenu) {
  13847. tieredMenu.repositionMenus(tmenu);
  13848. });
  13849. };
  13850. var makeSandbox = function (detail, hotspot, extras) {
  13851. var ariaOwner = manager();
  13852. var onOpen = function (component, menu) {
  13853. var anchor = getAnchor(detail, hotspot);
  13854. ariaOwner.link(hotspot.element);
  13855. if (detail.matchWidth) {
  13856. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  13857. }
  13858. detail.onOpen(anchor, component, menu);
  13859. if (extras !== undefined && extras.onOpen !== undefined) {
  13860. extras.onOpen(component, menu);
  13861. }
  13862. };
  13863. var onClose = function (component, menu) {
  13864. ariaOwner.unlink(hotspot.element);
  13865. if (extras !== undefined && extras.onClose !== undefined) {
  13866. extras.onClose(component, menu);
  13867. }
  13868. };
  13869. var lazySink = getSink(hotspot, detail);
  13870. return {
  13871. dom: {
  13872. tag: 'div',
  13873. classes: detail.sandboxClasses,
  13874. attributes: {
  13875. id: ariaOwner.id,
  13876. role: 'listbox'
  13877. }
  13878. },
  13879. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  13880. Representing.config({
  13881. store: {
  13882. mode: 'memory',
  13883. initialValue: hotspot
  13884. }
  13885. }),
  13886. Sandboxing.config({
  13887. onOpen: onOpen,
  13888. onClose: onClose,
  13889. isPartOf: function (container, data, queryElem) {
  13890. return isPartOf(data, queryElem) || isPartOf(hotspot, queryElem);
  13891. },
  13892. getAttachPoint: function () {
  13893. return lazySink().getOrDie();
  13894. }
  13895. }),
  13896. Composing.config({
  13897. find: function (sandbox) {
  13898. return Sandboxing.getState(sandbox).bind(function (menu) {
  13899. return Composing.getCurrent(menu);
  13900. });
  13901. }
  13902. }),
  13903. Receiving.config({ channels: __assign(__assign({}, receivingChannel({ isExtraPart: never })), receivingChannel$1({ doReposition: doRepositionMenus })) })
  13904. ])
  13905. };
  13906. };
  13907. var repositionMenus = function (comp) {
  13908. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13909. doRepositionMenus(sandbox);
  13910. };
  13911. var sandboxFields = function () {
  13912. return [
  13913. defaulted$1('sandboxClasses', []),
  13914. SketchBehaviours.field('sandboxBehaviours', [
  13915. Composing,
  13916. Receiving,
  13917. Sandboxing,
  13918. Representing
  13919. ])
  13920. ];
  13921. };
  13922. var schema$g = constant([
  13923. strict$1('dom'),
  13924. strict$1('fetch'),
  13925. onHandler('onOpen'),
  13926. onKeyboardHandler('onExecute'),
  13927. defaulted$1('getHotspot', Optional.some),
  13928. defaulted$1('getAnchorOverrides', constant({})),
  13929. schema$1(),
  13930. field$1('dropdownBehaviours', [
  13931. Toggling,
  13932. Coupling,
  13933. Keying,
  13934. Focusing
  13935. ]),
  13936. strict$1('toggleClass'),
  13937. defaulted$1('eventOrder', {}),
  13938. option('lazySink'),
  13939. defaulted$1('matchWidth', false),
  13940. defaulted$1('useMinWidth', false),
  13941. option('role')
  13942. ].concat(sandboxFields()));
  13943. var parts$4 = constant([
  13944. external$1({
  13945. schema: [tieredMenuMarkers()],
  13946. name: 'menu',
  13947. defaults: function (detail) {
  13948. return { onExecute: detail.onExecute };
  13949. }
  13950. }),
  13951. partType()
  13952. ]);
  13953. var factory$6 = function (detail, components, _spec, externals) {
  13954. var _a;
  13955. var lookupAttr = function (attr) {
  13956. return get(detail.dom, 'attributes').bind(function (attrs) {
  13957. return get(attrs, attr);
  13958. });
  13959. };
  13960. var switchToMenu = function (sandbox) {
  13961. Sandboxing.getState(sandbox).each(function (tmenu) {
  13962. tieredMenu.highlightPrimary(tmenu);
  13963. });
  13964. };
  13965. var action = function (component) {
  13966. var onOpenSync = switchToMenu;
  13967. togglePopup(detail, function (x) {
  13968. return x;
  13969. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  13970. };
  13971. var apis = {
  13972. expand: function (comp) {
  13973. if (!Toggling.isOn(comp)) {
  13974. togglePopup(detail, function (x) {
  13975. return x;
  13976. }, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  13977. }
  13978. },
  13979. open: function (comp) {
  13980. if (!Toggling.isOn(comp)) {
  13981. togglePopup(detail, function (x) {
  13982. return x;
  13983. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13984. }
  13985. },
  13986. isOpen: Toggling.isOn,
  13987. close: function (comp) {
  13988. if (Toggling.isOn(comp)) {
  13989. togglePopup(detail, function (x) {
  13990. return x;
  13991. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13992. }
  13993. },
  13994. repositionMenus: function (comp) {
  13995. if (Toggling.isOn(comp)) {
  13996. repositionMenus(comp);
  13997. }
  13998. }
  13999. };
  14000. var triggerExecute = function (comp, _se) {
  14001. emitExecute(comp);
  14002. return Optional.some(true);
  14003. };
  14004. return {
  14005. uid: detail.uid,
  14006. dom: detail.dom,
  14007. components: components,
  14008. behaviours: augment(detail.dropdownBehaviours, [
  14009. Toggling.config({
  14010. toggleClass: detail.toggleClass,
  14011. aria: { mode: 'expanded' }
  14012. }),
  14013. Coupling.config({
  14014. others: {
  14015. sandbox: function (hotspot) {
  14016. return makeSandbox(detail, hotspot, {
  14017. onOpen: function () {
  14018. Toggling.on(hotspot);
  14019. },
  14020. onClose: function () {
  14021. Toggling.off(hotspot);
  14022. }
  14023. });
  14024. }
  14025. }
  14026. }),
  14027. Keying.config({
  14028. mode: 'special',
  14029. onSpace: triggerExecute,
  14030. onEnter: triggerExecute,
  14031. onDown: function (comp, _se) {
  14032. if (Dropdown.isOpen(comp)) {
  14033. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  14034. switchToMenu(sandbox);
  14035. } else {
  14036. Dropdown.open(comp);
  14037. }
  14038. return Optional.some(true);
  14039. },
  14040. onEscape: function (comp, _se) {
  14041. if (Dropdown.isOpen(comp)) {
  14042. Dropdown.close(comp);
  14043. return Optional.some(true);
  14044. } else {
  14045. return Optional.none();
  14046. }
  14047. }
  14048. }),
  14049. Focusing.config({})
  14050. ]),
  14051. events: events$7(Optional.some(action)),
  14052. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
  14053. 'disabling',
  14054. 'toggling',
  14055. 'alloy.base.behaviour'
  14056. ], _a)),
  14057. apis: apis,
  14058. domModification: {
  14059. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  14060. return {};
  14061. }, function (role) {
  14062. return { role: role };
  14063. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  14064. }
  14065. };
  14066. };
  14067. var Dropdown = composite$1({
  14068. name: 'Dropdown',
  14069. configFields: schema$g(),
  14070. partFields: parts$4(),
  14071. factory: factory$6,
  14072. apis: {
  14073. open: function (apis, comp) {
  14074. return apis.open(comp);
  14075. },
  14076. expand: function (apis, comp) {
  14077. return apis.expand(comp);
  14078. },
  14079. close: function (apis, comp) {
  14080. return apis.close(comp);
  14081. },
  14082. isOpen: function (apis, comp) {
  14083. return apis.isOpen(comp);
  14084. },
  14085. repositionMenus: function (apis, comp) {
  14086. return apis.repositionMenus(comp);
  14087. }
  14088. }
  14089. });
  14090. var exhibit$5 = function () {
  14091. return nu$6({
  14092. styles: {
  14093. '-webkit-user-select': 'none',
  14094. 'user-select': 'none',
  14095. '-ms-user-select': 'none',
  14096. '-moz-user-select': '-moz-none'
  14097. },
  14098. attributes: { unselectable: 'on' }
  14099. });
  14100. };
  14101. var events$b = function () {
  14102. return derive([abort(selectstart(), always)]);
  14103. };
  14104. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  14105. __proto__: null,
  14106. events: events$b,
  14107. exhibit: exhibit$5
  14108. });
  14109. var Unselecting = create$1({
  14110. fields: [],
  14111. name: 'unselecting',
  14112. active: ActiveUnselecting
  14113. });
  14114. var renderPanelButton = function (spec, sharedBackstage) {
  14115. return Dropdown.sketch({
  14116. dom: spec.dom,
  14117. components: spec.components,
  14118. toggleClass: 'mce-active',
  14119. dropdownBehaviours: derive$1([
  14120. DisablingConfigs.button(sharedBackstage.providers.isReadOnly),
  14121. receivingConfig(),
  14122. Unselecting.config({}),
  14123. Tabstopping.config({})
  14124. ]),
  14125. layouts: spec.layouts,
  14126. sandboxClasses: ['tox-dialog__popups'],
  14127. lazySink: sharedBackstage.getSink,
  14128. fetch: function (comp) {
  14129. return Future.nu(function (callback) {
  14130. return spec.fetch(callback);
  14131. }).map(function (items) {
  14132. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  14133. spec.onItemAction(comp, value);
  14134. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  14135. return false;
  14136. }, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  14137. });
  14138. },
  14139. parts: { menu: part(false, 1, spec.presets) }
  14140. });
  14141. };
  14142. var colorInputChangeEvent = generate$1('color-input-change');
  14143. var colorSwatchChangeEvent = generate$1('color-swatch-change');
  14144. var colorPickerCancelEvent = generate$1('color-picker-cancel');
  14145. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  14146. var pField = FormField.parts.field({
  14147. factory: Input,
  14148. inputClasses: ['tox-textfield'],
  14149. onSetValue: function (c) {
  14150. return Invalidating.run(c).get(function () {
  14151. });
  14152. },
  14153. inputBehaviours: derive$1([
  14154. Disabling.config({ disabled: sharedBackstage.providers.isReadOnly }),
  14155. receivingConfig(),
  14156. Tabstopping.config({}),
  14157. Invalidating.config({
  14158. invalidClass: 'tox-textbox-field-invalid',
  14159. getRoot: function (comp) {
  14160. return parent(comp.element);
  14161. },
  14162. notify: {
  14163. onValid: function (comp) {
  14164. var val = Representing.getValue(comp);
  14165. emitWith(comp, colorInputChangeEvent, { color: val });
  14166. }
  14167. },
  14168. validator: {
  14169. validateOnLoad: false,
  14170. validate: function (input) {
  14171. var inputValue = Representing.getValue(input);
  14172. if (inputValue.length === 0) {
  14173. return Future.pure(Result.value(true));
  14174. } else {
  14175. var span = SugarElement.fromTag('span');
  14176. set$2(span, 'background-color', inputValue);
  14177. var res = getRaw(span, 'background-color').fold(function () {
  14178. return Result.error('blah');
  14179. }, function (_) {
  14180. return Result.value(inputValue);
  14181. });
  14182. return Future.pure(res);
  14183. }
  14184. }
  14185. }
  14186. })
  14187. ]),
  14188. selectOnFocus: false
  14189. });
  14190. var pLabel = spec.label.map(function (label) {
  14191. return renderLabel(label, sharedBackstage.providers);
  14192. });
  14193. var emitSwatchChange = function (colorBit, value) {
  14194. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  14195. };
  14196. var onItemAction = function (comp, value) {
  14197. memColorButton.getOpt(comp).each(function (colorBit) {
  14198. if (value === 'custom') {
  14199. colorInputBackstage.colorPicker(function (valueOpt) {
  14200. valueOpt.fold(function () {
  14201. return emit(colorBit, colorPickerCancelEvent);
  14202. }, function (value) {
  14203. emitSwatchChange(colorBit, value);
  14204. addColor(value);
  14205. });
  14206. }, '#ffffff');
  14207. } else if (value === 'remove') {
  14208. emitSwatchChange(colorBit, '');
  14209. } else {
  14210. emitSwatchChange(colorBit, value);
  14211. }
  14212. });
  14213. };
  14214. var memColorButton = record(renderPanelButton({
  14215. dom: {
  14216. tag: 'span',
  14217. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  14218. },
  14219. layouts: {
  14220. onRtl: function () {
  14221. return [
  14222. southwest$1,
  14223. southeast$1,
  14224. south$1
  14225. ];
  14226. },
  14227. onLtr: function () {
  14228. return [
  14229. southeast$1,
  14230. southwest$1,
  14231. south$1
  14232. ];
  14233. }
  14234. },
  14235. components: [],
  14236. fetch: getFetch(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  14237. columns: colorInputBackstage.getColorCols(),
  14238. presets: 'color',
  14239. onItemAction: onItemAction
  14240. }, sharedBackstage));
  14241. return FormField.sketch({
  14242. dom: {
  14243. tag: 'div',
  14244. classes: ['tox-form__group']
  14245. },
  14246. components: pLabel.toArray().concat([{
  14247. dom: {
  14248. tag: 'div',
  14249. classes: ['tox-color-input']
  14250. },
  14251. components: [
  14252. pField,
  14253. memColorButton.asSpec()
  14254. ]
  14255. }]),
  14256. fieldBehaviours: derive$1([config('form-field-events', [
  14257. run(colorInputChangeEvent, function (comp, se) {
  14258. memColorButton.getOpt(comp).each(function (colorButton) {
  14259. set$2(colorButton.element, 'background-color', se.event.color);
  14260. });
  14261. emitWith(comp, formChangeEvent, { name: spec.name });
  14262. }),
  14263. run(colorSwatchChangeEvent, function (comp, se) {
  14264. FormField.getField(comp).each(function (field) {
  14265. Representing.setValue(field, se.event.value);
  14266. Composing.getCurrent(comp).each(Focusing.focus);
  14267. });
  14268. }),
  14269. run(colorPickerCancelEvent, function (comp, _se) {
  14270. FormField.getField(comp).each(function (_field) {
  14271. Composing.getCurrent(comp).each(Focusing.focus);
  14272. });
  14273. })
  14274. ])])
  14275. });
  14276. };
  14277. var hsvColour = function (hue, saturation, value) {
  14278. return {
  14279. hue: hue,
  14280. saturation: saturation,
  14281. value: value
  14282. };
  14283. };
  14284. var fromRgb = function (rgbaColour) {
  14285. var h = 0;
  14286. var s = 0;
  14287. var v = 0;
  14288. var r = rgbaColour.red / 255;
  14289. var g = rgbaColour.green / 255;
  14290. var b = rgbaColour.blue / 255;
  14291. var minRGB = Math.min(r, Math.min(g, b));
  14292. var maxRGB = Math.max(r, Math.max(g, b));
  14293. if (minRGB === maxRGB) {
  14294. v = minRGB;
  14295. return hsvColour(0, 0, v * 100);
  14296. }
  14297. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  14298. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  14299. h = 60 * (h - d / (maxRGB - minRGB));
  14300. s = (maxRGB - minRGB) / maxRGB;
  14301. v = maxRGB;
  14302. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  14303. };
  14304. var calcHex = function (value) {
  14305. var hue = (100 - value) / 100 * 360;
  14306. var hsv = hsvColour(hue, 100, 100);
  14307. var rgb = fromHsv(hsv);
  14308. return fromRgba(rgb);
  14309. };
  14310. var fieldsUpdate = generate$1('rgb-hex-update');
  14311. var sliderUpdate = generate$1('slider-update');
  14312. var paletteUpdate = generate$1('palette-update');
  14313. var labelPart = optional({
  14314. schema: [strict$1('dom')],
  14315. name: 'label'
  14316. });
  14317. var edgePart = function (name) {
  14318. return optional({
  14319. name: '' + name + '-edge',
  14320. overrides: function (detail) {
  14321. var action = detail.model.manager.edgeActions[name];
  14322. return action.fold(function () {
  14323. return {};
  14324. }, function (a) {
  14325. return {
  14326. events: derive([
  14327. runActionExtra(touchstart(), function (comp, se, d) {
  14328. return a(comp, d);
  14329. }, [detail]),
  14330. runActionExtra(mousedown(), function (comp, se, d) {
  14331. return a(comp, d);
  14332. }, [detail]),
  14333. runActionExtra(mousemove(), function (comp, se, det) {
  14334. if (det.mouseIsDown.get()) {
  14335. a(comp, det);
  14336. }
  14337. }, [detail])
  14338. ])
  14339. };
  14340. });
  14341. }
  14342. });
  14343. };
  14344. var tlEdgePart = edgePart('top-left');
  14345. var tedgePart = edgePart('top');
  14346. var trEdgePart = edgePart('top-right');
  14347. var redgePart = edgePart('right');
  14348. var brEdgePart = edgePart('bottom-right');
  14349. var bedgePart = edgePart('bottom');
  14350. var blEdgePart = edgePart('bottom-left');
  14351. var ledgePart = edgePart('left');
  14352. var thumbPart = required({
  14353. name: 'thumb',
  14354. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  14355. overrides: function (detail) {
  14356. return {
  14357. events: derive([
  14358. redirectToPart(touchstart(), detail, 'spectrum'),
  14359. redirectToPart(touchmove(), detail, 'spectrum'),
  14360. redirectToPart(touchend(), detail, 'spectrum'),
  14361. redirectToPart(mousedown(), detail, 'spectrum'),
  14362. redirectToPart(mousemove(), detail, 'spectrum'),
  14363. redirectToPart(mouseup(), detail, 'spectrum')
  14364. ])
  14365. };
  14366. }
  14367. });
  14368. var spectrumPart = required({
  14369. schema: [state$1('mouseIsDown', function () {
  14370. return Cell(false);
  14371. })],
  14372. name: 'spectrum',
  14373. overrides: function (detail) {
  14374. var modelDetail = detail.model;
  14375. var model = modelDetail.manager;
  14376. var setValueFrom = function (component, simulatedEvent) {
  14377. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14378. return model.setValueFrom(component, detail, value);
  14379. });
  14380. };
  14381. return {
  14382. behaviours: derive$1([
  14383. Keying.config({
  14384. mode: 'special',
  14385. onLeft: function (spectrum) {
  14386. return model.onLeft(spectrum, detail);
  14387. },
  14388. onRight: function (spectrum) {
  14389. return model.onRight(spectrum, detail);
  14390. },
  14391. onUp: function (spectrum) {
  14392. return model.onUp(spectrum, detail);
  14393. },
  14394. onDown: function (spectrum) {
  14395. return model.onDown(spectrum, detail);
  14396. }
  14397. }),
  14398. Focusing.config({})
  14399. ]),
  14400. events: derive([
  14401. run(touchstart(), setValueFrom),
  14402. run(touchmove(), setValueFrom),
  14403. run(mousedown(), setValueFrom),
  14404. run(mousemove(), function (spectrum, se) {
  14405. if (detail.mouseIsDown.get()) {
  14406. setValueFrom(spectrum, se);
  14407. }
  14408. })
  14409. ])
  14410. };
  14411. }
  14412. });
  14413. var SliderParts = [
  14414. labelPart,
  14415. ledgePart,
  14416. redgePart,
  14417. tedgePart,
  14418. bedgePart,
  14419. tlEdgePart,
  14420. trEdgePart,
  14421. blEdgePart,
  14422. brEdgePart,
  14423. thumbPart,
  14424. spectrumPart
  14425. ];
  14426. var _sliderChangeEvent = 'slider.change.value';
  14427. var sliderChangeEvent = constant(_sliderChangeEvent);
  14428. var isTouchEvent = function (evt) {
  14429. return evt.type.indexOf('touch') !== -1;
  14430. };
  14431. var getEventSource = function (simulatedEvent) {
  14432. var evt = simulatedEvent.event.raw;
  14433. if (isTouchEvent(evt)) {
  14434. var touchEvent = evt;
  14435. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  14436. return SugarPosition(t.clientX, t.clientY);
  14437. }) : Optional.none();
  14438. } else {
  14439. var mouseEvent = evt;
  14440. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  14441. return SugarPosition(me.clientX, me.clientY);
  14442. }) : Optional.none();
  14443. }
  14444. };
  14445. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  14446. var minX = function (detail) {
  14447. return detail.model.minX;
  14448. };
  14449. var minY = function (detail) {
  14450. return detail.model.minY;
  14451. };
  14452. var min1X = function (detail) {
  14453. return detail.model.minX - 1;
  14454. };
  14455. var min1Y = function (detail) {
  14456. return detail.model.minY - 1;
  14457. };
  14458. var maxX = function (detail) {
  14459. return detail.model.maxX;
  14460. };
  14461. var maxY = function (detail) {
  14462. return detail.model.maxY;
  14463. };
  14464. var max1X = function (detail) {
  14465. return detail.model.maxX + 1;
  14466. };
  14467. var max1Y = function (detail) {
  14468. return detail.model.maxY + 1;
  14469. };
  14470. var range$2 = function (detail, max, min) {
  14471. return max(detail) - min(detail);
  14472. };
  14473. var xRange = function (detail) {
  14474. return range$2(detail, maxX, minX);
  14475. };
  14476. var yRange = function (detail) {
  14477. return range$2(detail, maxY, minY);
  14478. };
  14479. var halfX = function (detail) {
  14480. return xRange(detail) / 2;
  14481. };
  14482. var halfY = function (detail) {
  14483. return yRange(detail) / 2;
  14484. };
  14485. var step = function (detail) {
  14486. return detail.stepSize;
  14487. };
  14488. var snap = function (detail) {
  14489. return detail.snapToGrid;
  14490. };
  14491. var snapStart = function (detail) {
  14492. return detail.snapStart;
  14493. };
  14494. var rounded = function (detail) {
  14495. return detail.rounded;
  14496. };
  14497. var hasEdge = function (detail, edgeName) {
  14498. return detail[edgeName + '-edge'] !== undefined;
  14499. };
  14500. var hasLEdge = function (detail) {
  14501. return hasEdge(detail, l);
  14502. };
  14503. var hasREdge = function (detail) {
  14504. return hasEdge(detail, r$1);
  14505. };
  14506. var hasTEdge = function (detail) {
  14507. return hasEdge(detail, t);
  14508. };
  14509. var hasBEdge = function (detail) {
  14510. return hasEdge(detail, b);
  14511. };
  14512. var currentValue = function (detail) {
  14513. return detail.model.value.get();
  14514. };
  14515. var xValue = function (x) {
  14516. return { x: x };
  14517. };
  14518. var yValue = function (y) {
  14519. return { y: y };
  14520. };
  14521. var xyValue = function (x, y) {
  14522. return {
  14523. x: x,
  14524. y: y
  14525. };
  14526. };
  14527. var fireSliderChange = function (component, value) {
  14528. emitWith(component, sliderChangeEvent(), { value: value });
  14529. };
  14530. var setToTLEdgeXY = function (edge, detail) {
  14531. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  14532. };
  14533. var setToTEdge = function (edge, detail) {
  14534. fireSliderChange(edge, yValue(min1Y(detail)));
  14535. };
  14536. var setToTEdgeXY = function (edge, detail) {
  14537. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  14538. };
  14539. var setToTREdgeXY = function (edge, detail) {
  14540. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  14541. };
  14542. var setToREdge = function (edge, detail) {
  14543. fireSliderChange(edge, xValue(max1X(detail)));
  14544. };
  14545. var setToREdgeXY = function (edge, detail) {
  14546. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  14547. };
  14548. var setToBREdgeXY = function (edge, detail) {
  14549. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  14550. };
  14551. var setToBEdge = function (edge, detail) {
  14552. fireSliderChange(edge, yValue(max1Y(detail)));
  14553. };
  14554. var setToBEdgeXY = function (edge, detail) {
  14555. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  14556. };
  14557. var setToBLEdgeXY = function (edge, detail) {
  14558. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  14559. };
  14560. var setToLEdge = function (edge, detail) {
  14561. fireSliderChange(edge, xValue(min1X(detail)));
  14562. };
  14563. var setToLEdgeXY = function (edge, detail) {
  14564. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  14565. };
  14566. var reduceBy = function (value, min, max, step) {
  14567. if (value < min) {
  14568. return value;
  14569. } else if (value > max) {
  14570. return max;
  14571. } else if (value === min) {
  14572. return min - 1;
  14573. } else {
  14574. return Math.max(min, value - step);
  14575. }
  14576. };
  14577. var increaseBy = function (value, min, max, step) {
  14578. if (value > max) {
  14579. return value;
  14580. } else if (value < min) {
  14581. return min;
  14582. } else if (value === max) {
  14583. return max + 1;
  14584. } else {
  14585. return Math.min(max, value + step);
  14586. }
  14587. };
  14588. var capValue = function (value, min, max) {
  14589. return Math.max(min, Math.min(max, value));
  14590. };
  14591. var snapValueOf = function (value, min, max, step, snapStart) {
  14592. return snapStart.fold(function () {
  14593. var initValue = value - min;
  14594. var extraValue = Math.round(initValue / step) * step;
  14595. return capValue(min + extraValue, min - 1, max + 1);
  14596. }, function (start) {
  14597. var remainder = (value - start) % step;
  14598. var adjustment = Math.round(remainder / step);
  14599. var rawSteps = Math.floor((value - start) / step);
  14600. var maxSteps = Math.floor((max - start) / step);
  14601. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  14602. var r = start + numSteps * step;
  14603. return Math.max(start, r);
  14604. });
  14605. };
  14606. var findOffsetOf = function (value, min, max) {
  14607. return Math.min(max, Math.max(value, min)) - min;
  14608. };
  14609. var findValueOf = function (args) {
  14610. 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;
  14611. var capMin = hasMinEdge ? min - 1 : min;
  14612. var capMax = hasMaxEdge ? max + 1 : max;
  14613. if (value < minBound) {
  14614. return capMin;
  14615. } else if (value > maxBound) {
  14616. return capMax;
  14617. } else {
  14618. var offset = findOffsetOf(value, minBound, maxBound);
  14619. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  14620. if (snap && newValue >= min && newValue <= max) {
  14621. return snapValueOf(newValue, min, max, step, snapStart);
  14622. } else if (rounded) {
  14623. return Math.round(newValue);
  14624. } else {
  14625. return newValue;
  14626. }
  14627. }
  14628. };
  14629. var findOffsetOfValue = function (args) {
  14630. 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;
  14631. if (value < min) {
  14632. return hasMinEdge ? 0 : centerMinEdge;
  14633. } else if (value > max) {
  14634. return hasMaxEdge ? maxBound : centerMaxEdge;
  14635. } else {
  14636. return (value - min) / range * maxOffset;
  14637. }
  14638. };
  14639. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  14640. var getBounds$1 = function (component) {
  14641. return component.element.dom.getBoundingClientRect();
  14642. };
  14643. var getBoundsProperty = function (bounds, property) {
  14644. return bounds[property];
  14645. };
  14646. var getMinXBounds = function (component) {
  14647. var bounds = getBounds$1(component);
  14648. return getBoundsProperty(bounds, left);
  14649. };
  14650. var getMaxXBounds = function (component) {
  14651. var bounds = getBounds$1(component);
  14652. return getBoundsProperty(bounds, right);
  14653. };
  14654. var getMinYBounds = function (component) {
  14655. var bounds = getBounds$1(component);
  14656. return getBoundsProperty(bounds, top);
  14657. };
  14658. var getMaxYBounds = function (component) {
  14659. var bounds = getBounds$1(component);
  14660. return getBoundsProperty(bounds, bottom);
  14661. };
  14662. var getXScreenRange = function (component) {
  14663. var bounds = getBounds$1(component);
  14664. return getBoundsProperty(bounds, width);
  14665. };
  14666. var getYScreenRange = function (component) {
  14667. var bounds = getBounds$1(component);
  14668. return getBoundsProperty(bounds, height);
  14669. };
  14670. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  14671. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  14672. };
  14673. var getXCenterOffSetOf = function (component, spectrum) {
  14674. var componentBounds = getBounds$1(component);
  14675. var spectrumBounds = getBounds$1(spectrum);
  14676. var componentMinEdge = getBoundsProperty(componentBounds, left);
  14677. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  14678. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  14679. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14680. };
  14681. var getYCenterOffSetOf = function (component, spectrum) {
  14682. var componentBounds = getBounds$1(component);
  14683. var spectrumBounds = getBounds$1(spectrum);
  14684. var componentMinEdge = getBoundsProperty(componentBounds, top);
  14685. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  14686. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  14687. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14688. };
  14689. var fireSliderChange$1 = function (spectrum, value) {
  14690. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14691. };
  14692. var sliderValue = function (x) {
  14693. return { x: x };
  14694. };
  14695. var findValueOfOffset = function (spectrum, detail, left) {
  14696. var args = {
  14697. min: minX(detail),
  14698. max: maxX(detail),
  14699. range: xRange(detail),
  14700. value: left,
  14701. step: step(detail),
  14702. snap: snap(detail),
  14703. snapStart: snapStart(detail),
  14704. rounded: rounded(detail),
  14705. hasMinEdge: hasLEdge(detail),
  14706. hasMaxEdge: hasREdge(detail),
  14707. minBound: getMinXBounds(spectrum),
  14708. maxBound: getMaxXBounds(spectrum),
  14709. screenRange: getXScreenRange(spectrum)
  14710. };
  14711. return findValueOf(args);
  14712. };
  14713. var setValueFrom = function (spectrum, detail, value) {
  14714. var xValue = findValueOfOffset(spectrum, detail, value);
  14715. var sliderVal = sliderValue(xValue);
  14716. fireSliderChange$1(spectrum, sliderVal);
  14717. return xValue;
  14718. };
  14719. var setToMin = function (spectrum, detail) {
  14720. var min = minX(detail);
  14721. fireSliderChange$1(spectrum, sliderValue(min));
  14722. };
  14723. var setToMax = function (spectrum, detail) {
  14724. var max = maxX(detail);
  14725. fireSliderChange$1(spectrum, sliderValue(max));
  14726. };
  14727. var moveBy = function (direction, spectrum, detail) {
  14728. var f = direction > 0 ? increaseBy : reduceBy;
  14729. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  14730. fireSliderChange$1(spectrum, sliderValue(xValue));
  14731. return Optional.some(xValue);
  14732. };
  14733. var handleMovement = function (direction) {
  14734. return function (spectrum, detail) {
  14735. return moveBy(direction, spectrum, detail).map(function () {
  14736. return true;
  14737. });
  14738. };
  14739. };
  14740. var getValueFromEvent = function (simulatedEvent) {
  14741. var pos = getEventSource(simulatedEvent);
  14742. return pos.map(function (p) {
  14743. return p.left;
  14744. });
  14745. };
  14746. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  14747. var minOffset = 0;
  14748. var maxOffset = getXScreenRange(spectrum);
  14749. var centerMinEdge = minEdge.bind(function (edge) {
  14750. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  14751. }).getOr(minOffset);
  14752. var centerMaxEdge = maxEdge.bind(function (edge) {
  14753. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  14754. }).getOr(maxOffset);
  14755. var args = {
  14756. min: minX(detail),
  14757. max: maxX(detail),
  14758. range: xRange(detail),
  14759. value: value,
  14760. hasMinEdge: hasLEdge(detail),
  14761. hasMaxEdge: hasREdge(detail),
  14762. minBound: getMinXBounds(spectrum),
  14763. minOffset: minOffset,
  14764. maxBound: getMaxXBounds(spectrum),
  14765. maxOffset: maxOffset,
  14766. centerMinEdge: centerMinEdge,
  14767. centerMaxEdge: centerMaxEdge
  14768. };
  14769. return findOffsetOfValue(args);
  14770. };
  14771. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14772. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  14773. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  14774. };
  14775. var setPositionFromValue = function (slider, thumb, detail, edges) {
  14776. var value = currentValue(detail);
  14777. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14778. var thumbRadius = get$7(thumb.element) / 2;
  14779. set$2(thumb.element, 'left', pos - thumbRadius + 'px');
  14780. };
  14781. var onLeft = handleMovement(-1);
  14782. var onRight = handleMovement(1);
  14783. var onUp = Optional.none;
  14784. var onDown = Optional.none;
  14785. var edgeActions = {
  14786. 'top-left': Optional.none(),
  14787. 'top': Optional.none(),
  14788. 'top-right': Optional.none(),
  14789. 'right': Optional.some(setToREdge),
  14790. 'bottom-right': Optional.none(),
  14791. 'bottom': Optional.none(),
  14792. 'bottom-left': Optional.none(),
  14793. 'left': Optional.some(setToLEdge)
  14794. };
  14795. var HorizontalModel = /*#__PURE__*/Object.freeze({
  14796. __proto__: null,
  14797. setValueFrom: setValueFrom,
  14798. setToMin: setToMin,
  14799. setToMax: setToMax,
  14800. findValueOfOffset: findValueOfOffset,
  14801. getValueFromEvent: getValueFromEvent,
  14802. findPositionOfValue: findPositionOfValue,
  14803. setPositionFromValue: setPositionFromValue,
  14804. onLeft: onLeft,
  14805. onRight: onRight,
  14806. onUp: onUp,
  14807. onDown: onDown,
  14808. edgeActions: edgeActions
  14809. });
  14810. var fireSliderChange$2 = function (spectrum, value) {
  14811. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14812. };
  14813. var sliderValue$1 = function (y) {
  14814. return { y: y };
  14815. };
  14816. var findValueOfOffset$1 = function (spectrum, detail, top) {
  14817. var args = {
  14818. min: minY(detail),
  14819. max: maxY(detail),
  14820. range: yRange(detail),
  14821. value: top,
  14822. step: step(detail),
  14823. snap: snap(detail),
  14824. snapStart: snapStart(detail),
  14825. rounded: rounded(detail),
  14826. hasMinEdge: hasTEdge(detail),
  14827. hasMaxEdge: hasBEdge(detail),
  14828. minBound: getMinYBounds(spectrum),
  14829. maxBound: getMaxYBounds(spectrum),
  14830. screenRange: getYScreenRange(spectrum)
  14831. };
  14832. return findValueOf(args);
  14833. };
  14834. var setValueFrom$1 = function (spectrum, detail, value) {
  14835. var yValue = findValueOfOffset$1(spectrum, detail, value);
  14836. var sliderVal = sliderValue$1(yValue);
  14837. fireSliderChange$2(spectrum, sliderVal);
  14838. return yValue;
  14839. };
  14840. var setToMin$1 = function (spectrum, detail) {
  14841. var min = minY(detail);
  14842. fireSliderChange$2(spectrum, sliderValue$1(min));
  14843. };
  14844. var setToMax$1 = function (spectrum, detail) {
  14845. var max = maxY(detail);
  14846. fireSliderChange$2(spectrum, sliderValue$1(max));
  14847. };
  14848. var moveBy$1 = function (direction, spectrum, detail) {
  14849. var f = direction > 0 ? increaseBy : reduceBy;
  14850. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  14851. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  14852. return Optional.some(yValue);
  14853. };
  14854. var handleMovement$1 = function (direction) {
  14855. return function (spectrum, detail) {
  14856. return moveBy$1(direction, spectrum, detail).map(function () {
  14857. return true;
  14858. });
  14859. };
  14860. };
  14861. var getValueFromEvent$1 = function (simulatedEvent) {
  14862. var pos = getEventSource(simulatedEvent);
  14863. return pos.map(function (p) {
  14864. return p.top;
  14865. });
  14866. };
  14867. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  14868. var minOffset = 0;
  14869. var maxOffset = getYScreenRange(spectrum);
  14870. var centerMinEdge = minEdge.bind(function (edge) {
  14871. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  14872. }).getOr(minOffset);
  14873. var centerMaxEdge = maxEdge.bind(function (edge) {
  14874. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  14875. }).getOr(maxOffset);
  14876. var args = {
  14877. min: minY(detail),
  14878. max: maxY(detail),
  14879. range: yRange(detail),
  14880. value: value,
  14881. hasMinEdge: hasTEdge(detail),
  14882. hasMaxEdge: hasBEdge(detail),
  14883. minBound: getMinYBounds(spectrum),
  14884. minOffset: minOffset,
  14885. maxBound: getMaxYBounds(spectrum),
  14886. maxOffset: maxOffset,
  14887. centerMinEdge: centerMinEdge,
  14888. centerMaxEdge: centerMaxEdge
  14889. };
  14890. return findOffsetOfValue(args);
  14891. };
  14892. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14893. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  14894. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  14895. };
  14896. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  14897. var value = currentValue(detail);
  14898. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14899. var thumbRadius = get$6(thumb.element) / 2;
  14900. set$2(thumb.element, 'top', pos - thumbRadius + 'px');
  14901. };
  14902. var onLeft$1 = Optional.none;
  14903. var onRight$1 = Optional.none;
  14904. var onUp$1 = handleMovement$1(-1);
  14905. var onDown$1 = handleMovement$1(1);
  14906. var edgeActions$1 = {
  14907. 'top-left': Optional.none(),
  14908. 'top': Optional.some(setToTEdge),
  14909. 'top-right': Optional.none(),
  14910. 'right': Optional.none(),
  14911. 'bottom-right': Optional.none(),
  14912. 'bottom': Optional.some(setToBEdge),
  14913. 'bottom-left': Optional.none(),
  14914. 'left': Optional.none()
  14915. };
  14916. var VerticalModel = /*#__PURE__*/Object.freeze({
  14917. __proto__: null,
  14918. setValueFrom: setValueFrom$1,
  14919. setToMin: setToMin$1,
  14920. setToMax: setToMax$1,
  14921. findValueOfOffset: findValueOfOffset$1,
  14922. getValueFromEvent: getValueFromEvent$1,
  14923. findPositionOfValue: findPositionOfValue$1,
  14924. setPositionFromValue: setPositionFromValue$1,
  14925. onLeft: onLeft$1,
  14926. onRight: onRight$1,
  14927. onUp: onUp$1,
  14928. onDown: onDown$1,
  14929. edgeActions: edgeActions$1
  14930. });
  14931. var fireSliderChange$3 = function (spectrum, value) {
  14932. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14933. };
  14934. var sliderValue$2 = function (x, y) {
  14935. return {
  14936. x: x,
  14937. y: y
  14938. };
  14939. };
  14940. var setValueFrom$2 = function (spectrum, detail, value) {
  14941. var xValue = findValueOfOffset(spectrum, detail, value.left);
  14942. var yValue = findValueOfOffset$1(spectrum, detail, value.top);
  14943. var val = sliderValue$2(xValue, yValue);
  14944. fireSliderChange$3(spectrum, val);
  14945. return val;
  14946. };
  14947. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  14948. var f = direction > 0 ? increaseBy : reduceBy;
  14949. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  14950. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  14951. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  14952. return Optional.some(xValue);
  14953. };
  14954. var handleMovement$2 = function (direction, isVerticalMovement) {
  14955. return function (spectrum, detail) {
  14956. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  14957. return true;
  14958. });
  14959. };
  14960. };
  14961. var setToMin$2 = function (spectrum, detail) {
  14962. var mX = minX(detail);
  14963. var mY = minY(detail);
  14964. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14965. };
  14966. var setToMax$2 = function (spectrum, detail) {
  14967. var mX = maxX(detail);
  14968. var mY = maxY(detail);
  14969. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14970. };
  14971. var getValueFromEvent$2 = function (simulatedEvent) {
  14972. return getEventSource(simulatedEvent);
  14973. };
  14974. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  14975. var value = currentValue(detail);
  14976. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14977. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14978. var thumbXRadius = get$7(thumb.element) / 2;
  14979. var thumbYRadius = get$6(thumb.element) / 2;
  14980. set$2(thumb.element, 'left', xPos - thumbXRadius + 'px');
  14981. set$2(thumb.element, 'top', yPos - thumbYRadius + 'px');
  14982. };
  14983. var onLeft$2 = handleMovement$2(-1, false);
  14984. var onRight$2 = handleMovement$2(1, false);
  14985. var onUp$2 = handleMovement$2(-1, true);
  14986. var onDown$2 = handleMovement$2(1, true);
  14987. var edgeActions$2 = {
  14988. 'top-left': Optional.some(setToTLEdgeXY),
  14989. 'top': Optional.some(setToTEdgeXY),
  14990. 'top-right': Optional.some(setToTREdgeXY),
  14991. 'right': Optional.some(setToREdgeXY),
  14992. 'bottom-right': Optional.some(setToBREdgeXY),
  14993. 'bottom': Optional.some(setToBEdgeXY),
  14994. 'bottom-left': Optional.some(setToBLEdgeXY),
  14995. 'left': Optional.some(setToLEdgeXY)
  14996. };
  14997. var TwoDModel = /*#__PURE__*/Object.freeze({
  14998. __proto__: null,
  14999. setValueFrom: setValueFrom$2,
  15000. setToMin: setToMin$2,
  15001. setToMax: setToMax$2,
  15002. getValueFromEvent: getValueFromEvent$2,
  15003. setPositionFromValue: setPositionFromValue$2,
  15004. onLeft: onLeft$2,
  15005. onRight: onRight$2,
  15006. onUp: onUp$2,
  15007. onDown: onDown$2,
  15008. edgeActions: edgeActions$2
  15009. });
  15010. var SliderSchema = [
  15011. defaulted$1('stepSize', 1),
  15012. defaulted$1('onChange', noop),
  15013. defaulted$1('onChoose', noop),
  15014. defaulted$1('onInit', noop),
  15015. defaulted$1('onDragStart', noop),
  15016. defaulted$1('onDragEnd', noop),
  15017. defaulted$1('snapToGrid', false),
  15018. defaulted$1('rounded', true),
  15019. option('snapStart'),
  15020. strictOf('model', choose$1('mode', {
  15021. x: [
  15022. defaulted$1('minX', 0),
  15023. defaulted$1('maxX', 100),
  15024. state$1('value', function (spec) {
  15025. return Cell(spec.mode.minX);
  15026. }),
  15027. strict$1('getInitialValue'),
  15028. output('manager', HorizontalModel)
  15029. ],
  15030. y: [
  15031. defaulted$1('minY', 0),
  15032. defaulted$1('maxY', 100),
  15033. state$1('value', function (spec) {
  15034. return Cell(spec.mode.minY);
  15035. }),
  15036. strict$1('getInitialValue'),
  15037. output('manager', VerticalModel)
  15038. ],
  15039. xy: [
  15040. defaulted$1('minX', 0),
  15041. defaulted$1('maxX', 100),
  15042. defaulted$1('minY', 0),
  15043. defaulted$1('maxY', 100),
  15044. state$1('value', function (spec) {
  15045. return Cell({
  15046. x: spec.mode.minX,
  15047. y: spec.mode.minY
  15048. });
  15049. }),
  15050. strict$1('getInitialValue'),
  15051. output('manager', TwoDModel)
  15052. ]
  15053. })),
  15054. field$1('sliderBehaviours', [
  15055. Keying,
  15056. Representing
  15057. ]),
  15058. state$1('mouseIsDown', function () {
  15059. return Cell(false);
  15060. })
  15061. ];
  15062. var sketch = function (detail, components, _spec, _externals) {
  15063. var _a;
  15064. var getThumb = function (component) {
  15065. return getPartOrDie(component, detail, 'thumb');
  15066. };
  15067. var getSpectrum = function (component) {
  15068. return getPartOrDie(component, detail, 'spectrum');
  15069. };
  15070. var getLeftEdge = function (component) {
  15071. return getPart(component, detail, 'left-edge');
  15072. };
  15073. var getRightEdge = function (component) {
  15074. return getPart(component, detail, 'right-edge');
  15075. };
  15076. var getTopEdge = function (component) {
  15077. return getPart(component, detail, 'top-edge');
  15078. };
  15079. var getBottomEdge = function (component) {
  15080. return getPart(component, detail, 'bottom-edge');
  15081. };
  15082. var modelDetail = detail.model;
  15083. var model = modelDetail.manager;
  15084. var refresh = function (slider, thumb) {
  15085. model.setPositionFromValue(slider, thumb, detail, {
  15086. getLeftEdge: getLeftEdge,
  15087. getRightEdge: getRightEdge,
  15088. getTopEdge: getTopEdge,
  15089. getBottomEdge: getBottomEdge,
  15090. getSpectrum: getSpectrum
  15091. });
  15092. };
  15093. var changeValue = function (slider, newValue) {
  15094. modelDetail.value.set(newValue);
  15095. var thumb = getThumb(slider);
  15096. refresh(slider, thumb);
  15097. detail.onChange(slider, thumb, newValue);
  15098. return Optional.some(true);
  15099. };
  15100. var resetToMin = function (slider) {
  15101. model.setToMin(slider, detail);
  15102. };
  15103. var resetToMax = function (slider) {
  15104. model.setToMax(slider, detail);
  15105. };
  15106. var choose = function (slider) {
  15107. var fireOnChoose = function () {
  15108. getPart(slider, detail, 'thumb').each(function (thumb) {
  15109. var value = modelDetail.value.get();
  15110. detail.onChoose(slider, thumb, value);
  15111. });
  15112. };
  15113. var wasDown = detail.mouseIsDown.get();
  15114. detail.mouseIsDown.set(false);
  15115. if (wasDown) {
  15116. fireOnChoose();
  15117. }
  15118. };
  15119. var onDragStart = function (slider, simulatedEvent) {
  15120. simulatedEvent.stop();
  15121. detail.mouseIsDown.set(true);
  15122. detail.onDragStart(slider, getThumb(slider));
  15123. };
  15124. var onDragEnd = function (slider, simulatedEvent) {
  15125. simulatedEvent.stop();
  15126. detail.onDragEnd(slider, getThumb(slider));
  15127. choose(slider);
  15128. };
  15129. return {
  15130. uid: detail.uid,
  15131. dom: detail.dom,
  15132. components: components,
  15133. behaviours: augment(detail.sliderBehaviours, [
  15134. Keying.config({
  15135. mode: 'special',
  15136. focusIn: function (slider) {
  15137. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  15138. }
  15139. }),
  15140. Representing.config({
  15141. store: {
  15142. mode: 'manual',
  15143. getValue: function (_) {
  15144. return modelDetail.value.get();
  15145. }
  15146. }
  15147. }),
  15148. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  15149. ]),
  15150. events: derive([
  15151. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  15152. changeValue(slider, simulatedEvent.event.value);
  15153. }),
  15154. runOnAttached(function (slider, _simulatedEvent) {
  15155. var getInitial = modelDetail.getInitialValue();
  15156. modelDetail.value.set(getInitial);
  15157. var thumb = getThumb(slider);
  15158. refresh(slider, thumb);
  15159. var spectrum = getSpectrum(slider);
  15160. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  15161. }),
  15162. run(touchstart(), onDragStart),
  15163. run(touchend(), onDragEnd),
  15164. run(mousedown(), onDragStart),
  15165. run(mouseup(), onDragEnd)
  15166. ]),
  15167. apis: {
  15168. resetToMin: resetToMin,
  15169. resetToMax: resetToMax,
  15170. changeValue: changeValue,
  15171. refresh: refresh
  15172. },
  15173. domModification: { styles: { position: 'relative' } }
  15174. };
  15175. };
  15176. var Slider = composite$1({
  15177. name: 'Slider',
  15178. configFields: SliderSchema,
  15179. partFields: SliderParts,
  15180. factory: sketch,
  15181. apis: {
  15182. resetToMin: function (apis, slider) {
  15183. apis.resetToMin(slider);
  15184. },
  15185. resetToMax: function (apis, slider) {
  15186. apis.resetToMax(slider);
  15187. },
  15188. refresh: function (apis, slider) {
  15189. apis.refresh(slider);
  15190. }
  15191. }
  15192. });
  15193. var sliderFactory = function (translate, getClass) {
  15194. var spectrum = Slider.parts.spectrum({
  15195. dom: {
  15196. tag: 'div',
  15197. classes: [getClass('hue-slider-spectrum')],
  15198. attributes: { role: 'presentation' }
  15199. }
  15200. });
  15201. var thumb = Slider.parts.thumb({
  15202. dom: {
  15203. tag: 'div',
  15204. classes: [getClass('hue-slider-thumb')],
  15205. attributes: { role: 'presentation' }
  15206. }
  15207. });
  15208. return Slider.sketch({
  15209. dom: {
  15210. tag: 'div',
  15211. classes: [getClass('hue-slider')],
  15212. attributes: { role: 'presentation' }
  15213. },
  15214. rounded: false,
  15215. model: {
  15216. mode: 'y',
  15217. getInitialValue: constant({ y: 0 })
  15218. },
  15219. components: [
  15220. spectrum,
  15221. thumb
  15222. ],
  15223. sliderBehaviours: derive$1([Focusing.config({})]),
  15224. onChange: function (slider, _thumb, value) {
  15225. emitWith(slider, sliderUpdate, { value: value });
  15226. }
  15227. });
  15228. };
  15229. var owner$3 = 'form';
  15230. var schema$h = [field$1('formBehaviours', [Representing])];
  15231. var getPartName = function (name) {
  15232. return '<alloy.field.' + name + '>';
  15233. };
  15234. var sketch$1 = function (fSpec) {
  15235. var parts = function () {
  15236. var record = [];
  15237. var field = function (name, config) {
  15238. record.push(name);
  15239. return generateOne(owner$3, getPartName(name), config);
  15240. };
  15241. return {
  15242. field: field,
  15243. record: function () {
  15244. return record;
  15245. }
  15246. };
  15247. }();
  15248. var spec = fSpec(parts);
  15249. var partNames = parts.record();
  15250. var fieldParts = map(partNames, function (n) {
  15251. return required({
  15252. name: n,
  15253. pname: getPartName(n)
  15254. });
  15255. });
  15256. return composite(owner$3, schema$h, fieldParts, make$4, spec);
  15257. };
  15258. var toResult$1 = function (o, e) {
  15259. return o.fold(function () {
  15260. return Result.error(e);
  15261. }, Result.value);
  15262. };
  15263. var make$4 = function (detail, components) {
  15264. return {
  15265. uid: detail.uid,
  15266. dom: detail.dom,
  15267. components: components,
  15268. behaviours: augment(detail.formBehaviours, [Representing.config({
  15269. store: {
  15270. mode: 'manual',
  15271. getValue: function (form) {
  15272. var resPs = getAllParts(form, detail);
  15273. return map$2(resPs, function (resPThunk, pName) {
  15274. return resPThunk().bind(function (v) {
  15275. var opt = Composing.getCurrent(v);
  15276. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  15277. }).map(Representing.getValue);
  15278. });
  15279. },
  15280. setValue: function (form, values) {
  15281. each$1(values, function (newValue, key) {
  15282. getPart(form, detail, key).each(function (wrapper) {
  15283. Composing.getCurrent(wrapper).each(function (field) {
  15284. Representing.setValue(field, newValue);
  15285. });
  15286. });
  15287. });
  15288. }
  15289. }
  15290. })]),
  15291. apis: {
  15292. getField: function (form, key) {
  15293. return getPart(form, detail, key).bind(Composing.getCurrent);
  15294. }
  15295. }
  15296. };
  15297. };
  15298. var Form = {
  15299. getField: makeApi(function (apis, component, key) {
  15300. return apis.getField(component, key);
  15301. }),
  15302. sketch: sketch$1
  15303. };
  15304. var validInput = generate$1('valid-input');
  15305. var invalidInput = generate$1('invalid-input');
  15306. var validatingInput = generate$1('validating-input');
  15307. var translatePrefix = 'colorcustom.rgb.';
  15308. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  15309. var invalidation = function (label, isValid) {
  15310. return Invalidating.config({
  15311. invalidClass: getClass('invalid'),
  15312. notify: {
  15313. onValidate: function (comp) {
  15314. emitWith(comp, validatingInput, { type: label });
  15315. },
  15316. onValid: function (comp) {
  15317. emitWith(comp, validInput, {
  15318. type: label,
  15319. value: Representing.getValue(comp)
  15320. });
  15321. },
  15322. onInvalid: function (comp) {
  15323. emitWith(comp, invalidInput, {
  15324. type: label,
  15325. value: Representing.getValue(comp)
  15326. });
  15327. }
  15328. },
  15329. validator: {
  15330. validate: function (comp) {
  15331. var value = Representing.getValue(comp);
  15332. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  15333. return Future.pure(res);
  15334. },
  15335. validateOnLoad: false
  15336. }
  15337. });
  15338. };
  15339. var renderTextField = function (isValid, name, label, description, data) {
  15340. var helptext = translate(translatePrefix + 'range');
  15341. var pLabel = FormField.parts.label({
  15342. dom: {
  15343. tag: 'label',
  15344. innerHtml: label,
  15345. attributes: { 'aria-label': description }
  15346. }
  15347. });
  15348. var pField = FormField.parts.field({
  15349. data: data,
  15350. factory: Input,
  15351. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15352. inputClasses: [getClass('textfield')],
  15353. inputBehaviours: derive$1([
  15354. invalidation(name, isValid),
  15355. Tabstopping.config({})
  15356. ]),
  15357. onSetValue: function (input) {
  15358. if (Invalidating.isInvalid(input)) {
  15359. var run = Invalidating.run(input);
  15360. run.get(noop);
  15361. }
  15362. }
  15363. });
  15364. var comps = [
  15365. pLabel,
  15366. pField
  15367. ];
  15368. var concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : [];
  15369. var components = comps.concat(concats);
  15370. return {
  15371. dom: {
  15372. tag: 'div',
  15373. attributes: { role: 'presentation' }
  15374. },
  15375. components: components
  15376. };
  15377. };
  15378. var copyRgbToHex = function (form, rgba) {
  15379. var hex = fromRgba(rgba);
  15380. Form.getField(form, 'hex').each(function (hexField) {
  15381. if (!Focusing.isFocused(hexField)) {
  15382. Representing.setValue(form, { hex: hex.value });
  15383. }
  15384. });
  15385. return hex;
  15386. };
  15387. var copyRgbToForm = function (form, rgb) {
  15388. var red = rgb.red;
  15389. var green = rgb.green;
  15390. var blue = rgb.blue;
  15391. Representing.setValue(form, {
  15392. red: red,
  15393. green: green,
  15394. blue: blue
  15395. });
  15396. };
  15397. var memPreview = record({
  15398. dom: {
  15399. tag: 'div',
  15400. classes: [getClass('rgba-preview')],
  15401. styles: { 'background-color': 'white' },
  15402. attributes: { role: 'presentation' }
  15403. }
  15404. });
  15405. var updatePreview = function (anyInSystem, hex) {
  15406. memPreview.getOpt(anyInSystem).each(function (preview) {
  15407. set$2(preview.element, 'background-color', '#' + hex.value);
  15408. });
  15409. };
  15410. var factory = function () {
  15411. var state = {
  15412. red: Cell(Optional.some(255)),
  15413. green: Cell(Optional.some(255)),
  15414. blue: Cell(Optional.some(255)),
  15415. hex: Cell(Optional.some('ffffff'))
  15416. };
  15417. var copyHexToRgb = function (form, hex) {
  15418. var rgb = fromHex(hex);
  15419. copyRgbToForm(form, rgb);
  15420. setValueRgb(rgb);
  15421. };
  15422. var get = function (prop) {
  15423. return state[prop].get();
  15424. };
  15425. var set = function (prop, value) {
  15426. state[prop].set(value);
  15427. };
  15428. var getValueRgb = function () {
  15429. return get('red').bind(function (red) {
  15430. return get('green').bind(function (green) {
  15431. return get('blue').map(function (blue) {
  15432. return rgbaColour(red, green, blue, 1);
  15433. });
  15434. });
  15435. });
  15436. };
  15437. var setValueRgb = function (rgb) {
  15438. var red = rgb.red;
  15439. var green = rgb.green;
  15440. var blue = rgb.blue;
  15441. set('red', Optional.some(red));
  15442. set('green', Optional.some(green));
  15443. set('blue', Optional.some(blue));
  15444. };
  15445. var onInvalidInput = function (form, simulatedEvent) {
  15446. var data = simulatedEvent.event;
  15447. if (data.type !== 'hex') {
  15448. set(data.type, Optional.none());
  15449. } else {
  15450. onInvalidHexx(form);
  15451. }
  15452. };
  15453. var onValidHex = function (form, value) {
  15454. onValidHexx(form);
  15455. var hex = hexColour(value);
  15456. set('hex', Optional.some(value));
  15457. var rgb = fromHex(hex);
  15458. copyRgbToForm(form, rgb);
  15459. setValueRgb(rgb);
  15460. emitWith(form, fieldsUpdate, { hex: hex });
  15461. updatePreview(form, hex);
  15462. };
  15463. var onValidRgb = function (form, prop, value) {
  15464. var val = parseInt(value, 10);
  15465. set(prop, Optional.some(val));
  15466. getValueRgb().each(function (rgb) {
  15467. var hex = copyRgbToHex(form, rgb);
  15468. updatePreview(form, hex);
  15469. });
  15470. };
  15471. var isHexInputEvent = function (data) {
  15472. return data.type === 'hex';
  15473. };
  15474. var onValidInput = function (form, simulatedEvent) {
  15475. var data = simulatedEvent.event;
  15476. if (isHexInputEvent(data)) {
  15477. onValidHex(form, data.value);
  15478. } else {
  15479. onValidRgb(form, data.type, data.value);
  15480. }
  15481. };
  15482. var formPartStrings = function (key) {
  15483. return {
  15484. label: translate(translatePrefix + key + '.label'),
  15485. description: translate(translatePrefix + key + '.description')
  15486. };
  15487. };
  15488. var redStrings = formPartStrings('red');
  15489. var greenStrings = formPartStrings('green');
  15490. var blueStrings = formPartStrings('blue');
  15491. var hexStrings = formPartStrings('hex');
  15492. return deepMerge(Form.sketch(function (parts) {
  15493. return {
  15494. dom: {
  15495. tag: 'form',
  15496. classes: [getClass('rgb-form')],
  15497. attributes: { 'aria-label': translate('aria.color.picker') }
  15498. },
  15499. components: [
  15500. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  15501. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  15502. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  15503. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  15504. memPreview.asSpec()
  15505. ],
  15506. formBehaviours: derive$1([
  15507. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  15508. config('rgb-form-events', [
  15509. run(validInput, onValidInput),
  15510. run(invalidInput, onInvalidInput),
  15511. run(validatingInput, onInvalidInput)
  15512. ])
  15513. ])
  15514. };
  15515. }), {
  15516. apis: {
  15517. updateHex: function (form, hex) {
  15518. Representing.setValue(form, { hex: hex.value });
  15519. copyHexToRgb(form, hex);
  15520. updatePreview(form, hex);
  15521. }
  15522. }
  15523. });
  15524. };
  15525. var rgbFormSketcher = single$2({
  15526. factory: factory,
  15527. name: 'RgbForm',
  15528. configFields: [],
  15529. apis: {
  15530. updateHex: function (apis, form, hex) {
  15531. apis.updateHex(form, hex);
  15532. }
  15533. },
  15534. extraApis: {}
  15535. });
  15536. return rgbFormSketcher;
  15537. };
  15538. var paletteFactory = function (_translate, getClass) {
  15539. var spectrumPart = Slider.parts.spectrum({
  15540. dom: {
  15541. tag: 'canvas',
  15542. attributes: { role: 'presentation' },
  15543. classes: [getClass('sv-palette-spectrum')]
  15544. }
  15545. });
  15546. var thumbPart = Slider.parts.thumb({
  15547. dom: {
  15548. tag: 'div',
  15549. attributes: { role: 'presentation' },
  15550. classes: [getClass('sv-palette-thumb')],
  15551. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  15552. }
  15553. });
  15554. var setColour = function (canvas, rgba) {
  15555. var width = canvas.width, height = canvas.height;
  15556. var ctx = canvas.getContext('2d');
  15557. if (ctx === null) {
  15558. return;
  15559. }
  15560. ctx.fillStyle = rgba;
  15561. ctx.fillRect(0, 0, width, height);
  15562. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  15563. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  15564. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  15565. ctx.fillStyle = grdWhite;
  15566. ctx.fillRect(0, 0, width, height);
  15567. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  15568. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  15569. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  15570. ctx.fillStyle = grdBlack;
  15571. ctx.fillRect(0, 0, width, height);
  15572. };
  15573. var setSliderColour = function (slider, rgba) {
  15574. var canvas = slider.components()[0].element.dom;
  15575. setColour(canvas, toString(rgba));
  15576. };
  15577. var factory = function (_detail) {
  15578. var getInitialValue = constant({
  15579. x: 0,
  15580. y: 0
  15581. });
  15582. var onChange = function (slider, _thumb, value) {
  15583. emitWith(slider, paletteUpdate, { value: value });
  15584. };
  15585. var onInit = function (_slider, _thumb, spectrum, _value) {
  15586. setColour(spectrum.element.dom, toString(red));
  15587. };
  15588. var sliderBehaviours = derive$1([
  15589. Composing.config({ find: Optional.some }),
  15590. Focusing.config({})
  15591. ]);
  15592. return Slider.sketch({
  15593. dom: {
  15594. tag: 'div',
  15595. attributes: { role: 'presentation' },
  15596. classes: [getClass('sv-palette')]
  15597. },
  15598. model: {
  15599. mode: 'xy',
  15600. getInitialValue: getInitialValue
  15601. },
  15602. rounded: false,
  15603. components: [
  15604. spectrumPart,
  15605. thumbPart
  15606. ],
  15607. onChange: onChange,
  15608. onInit: onInit,
  15609. sliderBehaviours: sliderBehaviours
  15610. });
  15611. };
  15612. var saturationBrightnessPaletteSketcher = single$2({
  15613. factory: factory,
  15614. name: 'SaturationBrightnessPalette',
  15615. configFields: [],
  15616. apis: {
  15617. setRgba: function (_apis, slider, rgba) {
  15618. setSliderColour(slider, rgba);
  15619. }
  15620. },
  15621. extraApis: {}
  15622. });
  15623. return saturationBrightnessPaletteSketcher;
  15624. };
  15625. var makeFactory = function (translate, getClass) {
  15626. var factory = function (detail) {
  15627. var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  15628. var sbPalette = paletteFactory(translate, getClass);
  15629. var state = { paletteRgba: Cell(red) };
  15630. var memPalette = record(sbPalette.sketch({}));
  15631. var memRgb = record(rgbForm.sketch({}));
  15632. var updatePalette = function (anyInSystem, hex) {
  15633. memPalette.getOpt(anyInSystem).each(function (palette) {
  15634. var rgba = fromHex(hex);
  15635. state.paletteRgba.set(rgba);
  15636. sbPalette.setRgba(palette, rgba);
  15637. });
  15638. };
  15639. var updateFields = function (anyInSystem, hex) {
  15640. memRgb.getOpt(anyInSystem).each(function (form) {
  15641. rgbForm.updateHex(form, hex);
  15642. });
  15643. };
  15644. var runUpdates = function (anyInSystem, hex, updates) {
  15645. each(updates, function (update) {
  15646. update(anyInSystem, hex);
  15647. });
  15648. };
  15649. var paletteUpdates = function () {
  15650. var updates = [updateFields];
  15651. return function (form, simulatedEvent) {
  15652. var value = simulatedEvent.event.value;
  15653. var oldRgb = state.paletteRgba.get();
  15654. var hsvColour$1 = fromRgb(oldRgb);
  15655. var newHsvColour = hsvColour(hsvColour$1.hue, value.x, 100 - value.y);
  15656. var rgb = fromHsv(newHsvColour);
  15657. var nuHex = fromRgba(rgb);
  15658. runUpdates(form, nuHex, updates);
  15659. };
  15660. };
  15661. var sliderUpdates = function () {
  15662. var updates = [
  15663. updatePalette,
  15664. updateFields
  15665. ];
  15666. return function (form, simulatedEvent) {
  15667. var value = simulatedEvent.event.value;
  15668. var hex = calcHex(value.y);
  15669. runUpdates(form, hex, updates);
  15670. };
  15671. };
  15672. return {
  15673. uid: detail.uid,
  15674. dom: detail.dom,
  15675. components: [
  15676. memPalette.asSpec(),
  15677. sliderFactory(translate, getClass),
  15678. memRgb.asSpec()
  15679. ],
  15680. behaviours: derive$1([
  15681. config('colour-picker-events', [
  15682. run(paletteUpdate, paletteUpdates()),
  15683. run(sliderUpdate, sliderUpdates())
  15684. ]),
  15685. Composing.config({
  15686. find: function (comp) {
  15687. return memRgb.getOpt(comp);
  15688. }
  15689. }),
  15690. Keying.config({ mode: 'acyclic' })
  15691. ])
  15692. };
  15693. };
  15694. var colourPickerSketcher = single$2({
  15695. name: 'ColourPicker',
  15696. configFields: [
  15697. strict$1('dom'),
  15698. defaulted$1('onValidHex', noop),
  15699. defaulted$1('onInvalidHex', noop)
  15700. ],
  15701. factory: factory
  15702. });
  15703. return colourPickerSketcher;
  15704. };
  15705. var self$1 = function () {
  15706. return Composing.config({ find: Optional.some });
  15707. };
  15708. var memento = function (mem) {
  15709. return Composing.config({ find: mem.getOpt });
  15710. };
  15711. var childAt = function (index) {
  15712. return Composing.config({
  15713. find: function (comp) {
  15714. return child(comp.element, index).bind(function (element) {
  15715. return comp.getSystem().getByDom(element).toOptional();
  15716. });
  15717. }
  15718. });
  15719. };
  15720. var ComposingConfigs = {
  15721. self: self$1,
  15722. memento: memento,
  15723. childAt: childAt
  15724. };
  15725. var english = {
  15726. 'colorcustom.rgb.red.label': 'R',
  15727. 'colorcustom.rgb.red.description': 'Red component',
  15728. 'colorcustom.rgb.green.label': 'G',
  15729. 'colorcustom.rgb.green.description': 'Green component',
  15730. 'colorcustom.rgb.blue.label': 'B',
  15731. 'colorcustom.rgb.blue.description': 'Blue component',
  15732. 'colorcustom.rgb.hex.label': '#',
  15733. 'colorcustom.rgb.hex.description': 'Hex color code',
  15734. 'colorcustom.rgb.range': 'Range 0 to 255',
  15735. 'colorcustom.sb.saturation': 'Saturation',
  15736. 'colorcustom.sb.brightness': 'Brightness',
  15737. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  15738. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  15739. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  15740. 'colorcustom.hue.hue': 'Hue',
  15741. 'colorcustom.hue.slider': 'Hue Slider',
  15742. 'colorcustom.hue.palette': 'Hue Palette',
  15743. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  15744. 'aria.color.picker': 'Color Picker',
  15745. 'aria.input.invalid': 'Invalid input'
  15746. };
  15747. var getEnglishText = function (key) {
  15748. return english[key];
  15749. };
  15750. var translate$1 = function (key) {
  15751. return getEnglishText(key);
  15752. };
  15753. var renderColorPicker = function (_spec) {
  15754. var getClass = function (key) {
  15755. return 'tox-' + key;
  15756. };
  15757. var colourPickerFactory = makeFactory(translate$1, getClass);
  15758. var onValidHex = function (form) {
  15759. emitWith(form, formActionEvent, {
  15760. name: 'hex-valid',
  15761. value: true
  15762. });
  15763. };
  15764. var onInvalidHex = function (form) {
  15765. emitWith(form, formActionEvent, {
  15766. name: 'hex-valid',
  15767. value: false
  15768. });
  15769. };
  15770. var memPicker = record(colourPickerFactory.sketch({
  15771. dom: {
  15772. tag: 'div',
  15773. classes: [getClass('color-picker-container')],
  15774. attributes: { role: 'presentation' }
  15775. },
  15776. onValidHex: onValidHex,
  15777. onInvalidHex: onInvalidHex
  15778. }));
  15779. return {
  15780. dom: { tag: 'div' },
  15781. components: [memPicker.asSpec()],
  15782. behaviours: derive$1([
  15783. Representing.config({
  15784. store: {
  15785. mode: 'manual',
  15786. getValue: function (comp) {
  15787. var picker = memPicker.get(comp);
  15788. var optRgbForm = Composing.getCurrent(picker);
  15789. var optHex = optRgbForm.bind(function (rgbForm) {
  15790. var formValues = Representing.getValue(rgbForm);
  15791. return formValues.hex;
  15792. });
  15793. return optHex.map(function (hex) {
  15794. return '#' + hex;
  15795. }).getOr('');
  15796. },
  15797. setValue: function (comp, newValue) {
  15798. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  15799. var m = pattern.exec(newValue);
  15800. var picker = memPicker.get(comp);
  15801. var optRgbForm = Composing.getCurrent(picker);
  15802. optRgbForm.fold(function () {
  15803. console.log('Can not find form');
  15804. }, function (rgbForm) {
  15805. Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') });
  15806. Form.getField(rgbForm, 'hex').each(function (hexField) {
  15807. emit(hexField, input());
  15808. });
  15809. });
  15810. }
  15811. }
  15812. }),
  15813. ComposingConfigs.self()
  15814. ])
  15815. };
  15816. };
  15817. var global$a = tinymce.util.Tools.resolve('tinymce.Resource');
  15818. var isOldCustomEditor = function (spec) {
  15819. return Object.prototype.hasOwnProperty.call(spec, 'init');
  15820. };
  15821. var renderCustomEditor = function (spec) {
  15822. var editorApi = Cell(Optional.none());
  15823. var memReplaced = record({ dom: { tag: spec.tag } });
  15824. var initialValue = Cell(Optional.none());
  15825. return {
  15826. dom: {
  15827. tag: 'div',
  15828. classes: ['tox-custom-editor']
  15829. },
  15830. behaviours: derive$1([
  15831. config('custom-editor-events', [runOnAttached(function (component) {
  15832. memReplaced.getOpt(component).each(function (ta) {
  15833. (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$a.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  15834. return init(ta.element.dom, spec.settings);
  15835. })).then(function (ea) {
  15836. initialValue.get().each(function (cvalue) {
  15837. ea.setValue(cvalue);
  15838. });
  15839. initialValue.set(Optional.none());
  15840. editorApi.set(Optional.some(ea));
  15841. });
  15842. });
  15843. })]),
  15844. Representing.config({
  15845. store: {
  15846. mode: 'manual',
  15847. getValue: function () {
  15848. return editorApi.get().fold(function () {
  15849. return initialValue.get().getOr('');
  15850. }, function (ed) {
  15851. return ed.getValue();
  15852. });
  15853. },
  15854. setValue: function (component, value) {
  15855. editorApi.get().fold(function () {
  15856. initialValue.set(Optional.some(value));
  15857. }, function (ed) {
  15858. return ed.setValue(value);
  15859. });
  15860. }
  15861. }
  15862. }),
  15863. ComposingConfigs.self()
  15864. ]),
  15865. components: [memReplaced.asSpec()]
  15866. };
  15867. };
  15868. var processors = objOf([
  15869. defaulted$1('preprocess', identity),
  15870. defaulted$1('postprocess', identity)
  15871. ]);
  15872. var memento$1 = function (mem, rawProcessors) {
  15873. var ps = asRawOrDie('RepresentingConfigs.memento processors', processors, rawProcessors);
  15874. return Representing.config({
  15875. store: {
  15876. mode: 'manual',
  15877. getValue: function (comp) {
  15878. var other = mem.get(comp);
  15879. var rawValue = Representing.getValue(other);
  15880. return ps.postprocess(rawValue);
  15881. },
  15882. setValue: function (comp, rawValue) {
  15883. var newValue = ps.preprocess(rawValue);
  15884. var other = mem.get(comp);
  15885. Representing.setValue(other, newValue);
  15886. }
  15887. }
  15888. });
  15889. };
  15890. var withComp = function (optInitialValue, getter, setter) {
  15891. return Representing.config(deepMerge({
  15892. store: {
  15893. mode: 'manual',
  15894. getValue: getter,
  15895. setValue: setter
  15896. }
  15897. }, optInitialValue.map(function (initialValue) {
  15898. return { store: { initialValue: initialValue } };
  15899. }).getOr({})));
  15900. };
  15901. var withElement = function (initialValue, getter, setter) {
  15902. return withComp(initialValue, function (c) {
  15903. return getter(c.element);
  15904. }, function (c, v) {
  15905. return setter(c.element, v);
  15906. });
  15907. };
  15908. var domValue = function (optInitialValue) {
  15909. return withElement(optInitialValue, get$5, set$3);
  15910. };
  15911. var domHtml = function (optInitialValue) {
  15912. return withElement(optInitialValue, get$1, set);
  15913. };
  15914. var memory$1 = function (initialValue) {
  15915. return Representing.config({
  15916. store: {
  15917. mode: 'memory',
  15918. initialValue: initialValue
  15919. }
  15920. });
  15921. };
  15922. var RepresentingConfigs = {
  15923. memento: memento$1,
  15924. withElement: withElement,
  15925. withComp: withComp,
  15926. domValue: domValue,
  15927. domHtml: domHtml,
  15928. memory: memory$1
  15929. };
  15930. var extensionsAccepted = '.jpg,.jpeg,.png,.gif';
  15931. var filterByExtension = function (files) {
  15932. var re = new RegExp('(' + extensionsAccepted.split(/\s*,\s*/).join('|') + ')$', 'i');
  15933. return filter(from$1(files), function (file) {
  15934. return re.test(file.name);
  15935. });
  15936. };
  15937. var renderDropZone = function (spec, providersBackstage) {
  15938. var stopper = function (_, se) {
  15939. se.stop();
  15940. };
  15941. var sequence = function (actions) {
  15942. return function (comp, se) {
  15943. each(actions, function (a) {
  15944. a(comp, se);
  15945. });
  15946. };
  15947. };
  15948. var onDrop = function (comp, se) {
  15949. if (!Disabling.isDisabled(comp)) {
  15950. var transferEvent = se.event.raw;
  15951. handleFiles(comp, transferEvent.dataTransfer.files);
  15952. }
  15953. };
  15954. var onSelect = function (component, simulatedEvent) {
  15955. var input = simulatedEvent.event.raw.target;
  15956. handleFiles(component, input.files);
  15957. };
  15958. var handleFiles = function (component, files) {
  15959. Representing.setValue(component, filterByExtension(files));
  15960. emitWith(component, formChangeEvent, { name: spec.name });
  15961. };
  15962. var memInput = record({
  15963. dom: {
  15964. tag: 'input',
  15965. attributes: {
  15966. type: 'file',
  15967. accept: 'image/*'
  15968. },
  15969. styles: { display: 'none' }
  15970. },
  15971. behaviours: derive$1([config('input-file-events', [
  15972. cutter(click()),
  15973. cutter(tap())
  15974. ])])
  15975. });
  15976. var renderField = function (s) {
  15977. return {
  15978. uid: s.uid,
  15979. dom: {
  15980. tag: 'div',
  15981. classes: ['tox-dropzone-container']
  15982. },
  15983. behaviours: derive$1([
  15984. RepresentingConfigs.memory([]),
  15985. ComposingConfigs.self(),
  15986. Disabling.config({}),
  15987. Toggling.config({
  15988. toggleClass: 'dragenter',
  15989. toggleOnExecute: false
  15990. }),
  15991. config('dropzone-events', [
  15992. run('dragenter', sequence([
  15993. stopper,
  15994. Toggling.toggle
  15995. ])),
  15996. run('dragleave', sequence([
  15997. stopper,
  15998. Toggling.toggle
  15999. ])),
  16000. run('dragover', stopper),
  16001. run('drop', sequence([
  16002. stopper,
  16003. onDrop
  16004. ])),
  16005. run(change(), onSelect)
  16006. ])
  16007. ]),
  16008. components: [{
  16009. dom: {
  16010. tag: 'div',
  16011. classes: ['tox-dropzone'],
  16012. styles: {}
  16013. },
  16014. components: [
  16015. {
  16016. dom: {
  16017. tag: 'p',
  16018. innerHtml: providersBackstage.translate('Drop an image here')
  16019. }
  16020. },
  16021. Button.sketch({
  16022. dom: {
  16023. tag: 'button',
  16024. innerHtml: providersBackstage.translate('Browse for an image'),
  16025. styles: { position: 'relative' },
  16026. classes: [
  16027. 'tox-button',
  16028. 'tox-button--secondary'
  16029. ]
  16030. },
  16031. components: [memInput.asSpec()],
  16032. action: function (comp) {
  16033. var inputComp = memInput.get(comp);
  16034. inputComp.element.dom.click();
  16035. },
  16036. buttonBehaviours: derive$1([
  16037. Tabstopping.config({}),
  16038. DisablingConfigs.button(providersBackstage.isReadOnly),
  16039. receivingConfig()
  16040. ])
  16041. })
  16042. ]
  16043. }]
  16044. };
  16045. };
  16046. var pLabel = spec.label.map(function (label) {
  16047. return renderLabel(label, providersBackstage);
  16048. });
  16049. var pField = FormField.parts.field({ factory: { sketch: renderField } });
  16050. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16051. };
  16052. var renderGrid = function (spec, backstage) {
  16053. return {
  16054. dom: {
  16055. tag: 'div',
  16056. classes: [
  16057. 'tox-form__grid',
  16058. 'tox-form__grid--' + spec.columns + 'col'
  16059. ]
  16060. },
  16061. components: map(spec.items, backstage.interpreter)
  16062. };
  16063. };
  16064. var beforeObject = generate$1('alloy-fake-before-tabstop');
  16065. var afterObject = generate$1('alloy-fake-after-tabstop');
  16066. var craftWithClasses = function (classes) {
  16067. return {
  16068. dom: {
  16069. tag: 'div',
  16070. styles: {
  16071. width: '1px',
  16072. height: '1px',
  16073. outline: 'none'
  16074. },
  16075. attributes: { tabindex: '0' },
  16076. classes: classes
  16077. },
  16078. behaviours: derive$1([
  16079. Focusing.config({ ignore: true }),
  16080. Tabstopping.config({})
  16081. ])
  16082. };
  16083. };
  16084. var craft = function (spec) {
  16085. return {
  16086. dom: {
  16087. tag: 'div',
  16088. classes: ['tox-navobj']
  16089. },
  16090. components: [
  16091. craftWithClasses([beforeObject]),
  16092. spec,
  16093. craftWithClasses([afterObject])
  16094. ],
  16095. behaviours: derive$1([ComposingConfigs.childAt(1)])
  16096. };
  16097. };
  16098. var triggerTab = function (placeholder, shiftKey) {
  16099. emitWith(placeholder, keydown(), {
  16100. raw: {
  16101. which: 9,
  16102. shiftKey: shiftKey
  16103. }
  16104. });
  16105. };
  16106. var onFocus$1 = function (container, targetComp) {
  16107. var target = targetComp.element;
  16108. if (has$2(target, beforeObject)) {
  16109. triggerTab(container, true);
  16110. } else if (has$2(target, afterObject)) {
  16111. triggerTab(container, false);
  16112. }
  16113. };
  16114. var isPseudoStop = function (element) {
  16115. return closest$4(element, [
  16116. '.' + beforeObject,
  16117. '.' + afterObject
  16118. ].join(','), never);
  16119. };
  16120. var platformNeedsSandboxing = !(detect$3().browser.isIE() || detect$3().browser.isEdge());
  16121. var getDynamicSource = function (isSandbox) {
  16122. var cachedValue = Cell('');
  16123. return {
  16124. getValue: function (_frameComponent) {
  16125. return cachedValue.get();
  16126. },
  16127. setValue: function (frameComponent, html) {
  16128. if (!isSandbox) {
  16129. set$1(frameComponent.element, 'src', 'javascript:\'\'');
  16130. var doc = frameComponent.element.dom.contentWindow.document;
  16131. doc.open();
  16132. doc.write(html);
  16133. doc.close();
  16134. } else {
  16135. set$1(frameComponent.element, 'srcdoc', html);
  16136. }
  16137. cachedValue.set(html);
  16138. }
  16139. };
  16140. };
  16141. var renderIFrame = function (spec, providersBackstage) {
  16142. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  16143. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  16144. return { title: title };
  16145. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  16146. var sourcing = getDynamicSource(isSandbox);
  16147. var pLabel = spec.label.map(function (label) {
  16148. return renderLabel(label, providersBackstage);
  16149. });
  16150. var factory = function (newSpec) {
  16151. return craft({
  16152. uid: newSpec.uid,
  16153. dom: {
  16154. tag: 'iframe',
  16155. attributes: attributes
  16156. },
  16157. behaviours: derive$1([
  16158. Tabstopping.config({}),
  16159. Focusing.config({}),
  16160. RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
  16161. ])
  16162. });
  16163. };
  16164. var pField = FormField.parts.field({ factory: { sketch: factory } });
  16165. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16166. };
  16167. function create$5(width, height) {
  16168. return resize(document.createElement('canvas'), width, height);
  16169. }
  16170. function clone$1(canvas) {
  16171. var tCanvas = create$5(canvas.width, canvas.height);
  16172. var ctx = get2dContext(tCanvas);
  16173. ctx.drawImage(canvas, 0, 0);
  16174. return tCanvas;
  16175. }
  16176. function get2dContext(canvas) {
  16177. return canvas.getContext('2d');
  16178. }
  16179. function resize(canvas, width, height) {
  16180. canvas.width = width;
  16181. canvas.height = height;
  16182. return canvas;
  16183. }
  16184. function getWidth(image) {
  16185. return image.naturalWidth || image.width;
  16186. }
  16187. function getHeight(image) {
  16188. return image.naturalHeight || image.height;
  16189. }
  16190. var promise = function () {
  16191. var Promise = function (fn) {
  16192. if (typeof this !== 'object') {
  16193. throw new TypeError('Promises must be constructed via new');
  16194. }
  16195. if (typeof fn !== 'function') {
  16196. throw new TypeError('not a function');
  16197. }
  16198. this._state = null;
  16199. this._value = null;
  16200. this._deferreds = [];
  16201. doResolve(fn, bind(resolve, this), bind(reject, this));
  16202. };
  16203. var anyWindow = window;
  16204. var asap = Promise.immediateFn || typeof anyWindow.setImmediate === 'function' && anyWindow.setImmediate || function (fn) {
  16205. setTimeout(fn, 1);
  16206. };
  16207. function bind(fn, thisArg) {
  16208. return function () {
  16209. return fn.apply(thisArg, arguments);
  16210. };
  16211. }
  16212. var isArray = Array.isArray || function (value) {
  16213. return Object.prototype.toString.call(value) === '[object Array]';
  16214. };
  16215. function handle(deferred) {
  16216. var me = this;
  16217. if (this._state === null) {
  16218. this._deferreds.push(deferred);
  16219. return;
  16220. }
  16221. asap(function () {
  16222. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  16223. if (cb === null) {
  16224. (me._state ? deferred.resolve : deferred.reject)(me._value);
  16225. return;
  16226. }
  16227. var ret;
  16228. try {
  16229. ret = cb(me._value);
  16230. } catch (e) {
  16231. deferred.reject(e);
  16232. return;
  16233. }
  16234. deferred.resolve(ret);
  16235. });
  16236. }
  16237. function resolve(newValue) {
  16238. try {
  16239. if (newValue === this) {
  16240. throw new TypeError('A promise cannot be resolved with itself.');
  16241. }
  16242. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  16243. var then = newValue.then;
  16244. if (typeof then === 'function') {
  16245. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  16246. return;
  16247. }
  16248. }
  16249. this._state = true;
  16250. this._value = newValue;
  16251. finale.call(this);
  16252. } catch (e) {
  16253. reject.call(this, e);
  16254. }
  16255. }
  16256. function reject(newValue) {
  16257. this._state = false;
  16258. this._value = newValue;
  16259. finale.call(this);
  16260. }
  16261. function finale() {
  16262. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  16263. var deferred = _a[_i];
  16264. handle.call(this, deferred);
  16265. }
  16266. this._deferreds = [];
  16267. }
  16268. function Handler(onFulfilled, onRejected, resolve, reject) {
  16269. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  16270. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  16271. this.resolve = resolve;
  16272. this.reject = reject;
  16273. }
  16274. function doResolve(fn, onFulfilled, onRejected) {
  16275. var done = false;
  16276. try {
  16277. fn(function (value) {
  16278. if (done) {
  16279. return;
  16280. }
  16281. done = true;
  16282. onFulfilled(value);
  16283. }, function (reason) {
  16284. if (done) {
  16285. return;
  16286. }
  16287. done = true;
  16288. onRejected(reason);
  16289. });
  16290. } catch (ex) {
  16291. if (done) {
  16292. return;
  16293. }
  16294. done = true;
  16295. onRejected(ex);
  16296. }
  16297. }
  16298. Promise.prototype.catch = function (onRejected) {
  16299. return this.then(null, onRejected);
  16300. };
  16301. Promise.prototype.then = function (onFulfilled, onRejected) {
  16302. var me = this;
  16303. return new Promise(function (resolve, reject) {
  16304. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  16305. });
  16306. };
  16307. Promise.all = function () {
  16308. var values = [];
  16309. for (var _i = 0; _i < arguments.length; _i++) {
  16310. values[_i] = arguments[_i];
  16311. }
  16312. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  16313. return new Promise(function (resolve, reject) {
  16314. if (args.length === 0) {
  16315. return resolve([]);
  16316. }
  16317. var remaining = args.length;
  16318. function res(i, val) {
  16319. try {
  16320. if (val && (typeof val === 'object' || typeof val === 'function')) {
  16321. var then = val.then;
  16322. if (typeof then === 'function') {
  16323. then.call(val, function (val) {
  16324. res(i, val);
  16325. }, reject);
  16326. return;
  16327. }
  16328. }
  16329. args[i] = val;
  16330. if (--remaining === 0) {
  16331. resolve(args);
  16332. }
  16333. } catch (ex) {
  16334. reject(ex);
  16335. }
  16336. }
  16337. for (var i = 0; i < args.length; i++) {
  16338. res(i, args[i]);
  16339. }
  16340. });
  16341. };
  16342. Promise.resolve = function (value) {
  16343. if (value && typeof value === 'object' && value.constructor === Promise) {
  16344. return value;
  16345. }
  16346. return new Promise(function (resolve) {
  16347. resolve(value);
  16348. });
  16349. };
  16350. Promise.reject = function (reason) {
  16351. return new Promise(function (resolve, reject) {
  16352. reject(reason);
  16353. });
  16354. };
  16355. Promise.race = function (values) {
  16356. return new Promise(function (resolve, reject) {
  16357. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  16358. var value = values_1[_i];
  16359. value.then(resolve, reject);
  16360. }
  16361. });
  16362. };
  16363. return Promise;
  16364. };
  16365. var Promise$1 = window.Promise ? window.Promise : promise();
  16366. function blobToImage(blob) {
  16367. return new Promise$1(function (resolve, reject) {
  16368. var blobUrl = URL.createObjectURL(blob);
  16369. var image = new Image();
  16370. var removeListeners = function () {
  16371. image.removeEventListener('load', loaded);
  16372. image.removeEventListener('error', error);
  16373. };
  16374. function loaded() {
  16375. removeListeners();
  16376. resolve(image);
  16377. }
  16378. function error() {
  16379. removeListeners();
  16380. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16381. }
  16382. image.addEventListener('load', loaded);
  16383. image.addEventListener('error', error);
  16384. image.src = blobUrl;
  16385. if (image.complete) {
  16386. loaded();
  16387. }
  16388. });
  16389. }
  16390. function dataUriToBlobSync(uri) {
  16391. var data = uri.split(',');
  16392. var matches = /data:([^;]+)/.exec(data[0]);
  16393. if (!matches) {
  16394. return Optional.none();
  16395. }
  16396. var mimetype = matches[1];
  16397. var base64 = data[1];
  16398. var sliceSize = 1024;
  16399. var byteCharacters = atob(base64);
  16400. var bytesLength = byteCharacters.length;
  16401. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16402. var byteArrays = new Array(slicesCount);
  16403. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16404. var begin = sliceIndex * sliceSize;
  16405. var end = Math.min(begin + sliceSize, bytesLength);
  16406. var bytes = new Array(end - begin);
  16407. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  16408. bytes[i] = byteCharacters[offset].charCodeAt(0);
  16409. }
  16410. byteArrays[sliceIndex] = new Uint8Array(bytes);
  16411. }
  16412. return Optional.some(new Blob(byteArrays, { type: mimetype }));
  16413. }
  16414. function dataUriToBlob(uri) {
  16415. return new Promise$1(function (resolve, reject) {
  16416. dataUriToBlobSync(uri).fold(function () {
  16417. reject('uri is not base64: ' + uri);
  16418. }, resolve);
  16419. });
  16420. }
  16421. function canvasToBlob(canvas, type, quality) {
  16422. type = type || 'image/png';
  16423. if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
  16424. return new Promise$1(function (resolve, reject) {
  16425. canvas.toBlob(function (blob) {
  16426. if (blob) {
  16427. resolve(blob);
  16428. } else {
  16429. reject();
  16430. }
  16431. }, type, quality);
  16432. });
  16433. } else {
  16434. return dataUriToBlob(canvas.toDataURL(type, quality));
  16435. }
  16436. }
  16437. function canvasToDataURL(canvas, type, quality) {
  16438. type = type || 'image/png';
  16439. return canvas.toDataURL(type, quality);
  16440. }
  16441. function blobToCanvas(blob) {
  16442. return blobToImage(blob).then(function (image) {
  16443. revokeImageUrl(image);
  16444. var canvas = create$5(getWidth(image), getHeight(image));
  16445. var context = get2dContext(canvas);
  16446. context.drawImage(image, 0, 0);
  16447. return canvas;
  16448. });
  16449. }
  16450. function blobToDataUri(blob) {
  16451. return new Promise$1(function (resolve) {
  16452. var reader = new FileReader();
  16453. reader.onloadend = function () {
  16454. resolve(reader.result);
  16455. };
  16456. reader.readAsDataURL(blob);
  16457. });
  16458. }
  16459. function revokeImageUrl(image) {
  16460. URL.revokeObjectURL(image.src);
  16461. }
  16462. function create$6(getCanvas, blob, uri) {
  16463. var initialType = blob.type;
  16464. var getType = constant(initialType);
  16465. function toBlob() {
  16466. return Promise$1.resolve(blob);
  16467. }
  16468. var toDataURL = constant(uri);
  16469. function toBase64() {
  16470. return uri.split(',')[1];
  16471. }
  16472. function toAdjustedBlob(type, quality) {
  16473. return getCanvas.then(function (canvas) {
  16474. return canvasToBlob(canvas, type, quality);
  16475. });
  16476. }
  16477. function toAdjustedDataURL(type, quality) {
  16478. return getCanvas.then(function (canvas) {
  16479. return canvasToDataURL(canvas, type, quality);
  16480. });
  16481. }
  16482. function toAdjustedBase64(type, quality) {
  16483. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  16484. return dataurl.split(',')[1];
  16485. });
  16486. }
  16487. function toCanvas() {
  16488. return getCanvas.then(clone$1);
  16489. }
  16490. return {
  16491. getType: getType,
  16492. toBlob: toBlob,
  16493. toDataURL: toDataURL,
  16494. toBase64: toBase64,
  16495. toAdjustedBlob: toAdjustedBlob,
  16496. toAdjustedDataURL: toAdjustedDataURL,
  16497. toAdjustedBase64: toAdjustedBase64,
  16498. toCanvas: toCanvas
  16499. };
  16500. }
  16501. function fromBlob(blob) {
  16502. return blobToDataUri(blob).then(function (uri) {
  16503. return create$6(blobToCanvas(blob), blob, uri);
  16504. });
  16505. }
  16506. function fromCanvas(canvas, type) {
  16507. return canvasToBlob(canvas, type).then(function (blob) {
  16508. return create$6(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  16509. });
  16510. }
  16511. var blobToImageResult = function (blob) {
  16512. return fromBlob(blob);
  16513. };
  16514. function clamp$1(value, min, max) {
  16515. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  16516. if (parsedValue > max) {
  16517. parsedValue = max;
  16518. } else if (parsedValue < min) {
  16519. parsedValue = min;
  16520. }
  16521. return parsedValue;
  16522. }
  16523. function identity$1() {
  16524. return [
  16525. 1,
  16526. 0,
  16527. 0,
  16528. 0,
  16529. 0,
  16530. 0,
  16531. 1,
  16532. 0,
  16533. 0,
  16534. 0,
  16535. 0,
  16536. 0,
  16537. 1,
  16538. 0,
  16539. 0,
  16540. 0,
  16541. 0,
  16542. 0,
  16543. 1,
  16544. 0,
  16545. 0,
  16546. 0,
  16547. 0,
  16548. 0,
  16549. 1
  16550. ];
  16551. }
  16552. var DELTA_INDEX = [
  16553. 0,
  16554. 0.01,
  16555. 0.02,
  16556. 0.04,
  16557. 0.05,
  16558. 0.06,
  16559. 0.07,
  16560. 0.08,
  16561. 0.1,
  16562. 0.11,
  16563. 0.12,
  16564. 0.14,
  16565. 0.15,
  16566. 0.16,
  16567. 0.17,
  16568. 0.18,
  16569. 0.2,
  16570. 0.21,
  16571. 0.22,
  16572. 0.24,
  16573. 0.25,
  16574. 0.27,
  16575. 0.28,
  16576. 0.3,
  16577. 0.32,
  16578. 0.34,
  16579. 0.36,
  16580. 0.38,
  16581. 0.4,
  16582. 0.42,
  16583. 0.44,
  16584. 0.46,
  16585. 0.48,
  16586. 0.5,
  16587. 0.53,
  16588. 0.56,
  16589. 0.59,
  16590. 0.62,
  16591. 0.65,
  16592. 0.68,
  16593. 0.71,
  16594. 0.74,
  16595. 0.77,
  16596. 0.8,
  16597. 0.83,
  16598. 0.86,
  16599. 0.89,
  16600. 0.92,
  16601. 0.95,
  16602. 0.98,
  16603. 1,
  16604. 1.06,
  16605. 1.12,
  16606. 1.18,
  16607. 1.24,
  16608. 1.3,
  16609. 1.36,
  16610. 1.42,
  16611. 1.48,
  16612. 1.54,
  16613. 1.6,
  16614. 1.66,
  16615. 1.72,
  16616. 1.78,
  16617. 1.84,
  16618. 1.9,
  16619. 1.96,
  16620. 2,
  16621. 2.12,
  16622. 2.25,
  16623. 2.37,
  16624. 2.5,
  16625. 2.62,
  16626. 2.75,
  16627. 2.87,
  16628. 3,
  16629. 3.2,
  16630. 3.4,
  16631. 3.6,
  16632. 3.8,
  16633. 4,
  16634. 4.3,
  16635. 4.7,
  16636. 4.9,
  16637. 5,
  16638. 5.5,
  16639. 6,
  16640. 6.5,
  16641. 6.8,
  16642. 7,
  16643. 7.3,
  16644. 7.5,
  16645. 7.8,
  16646. 8,
  16647. 8.4,
  16648. 8.7,
  16649. 9,
  16650. 9.4,
  16651. 9.6,
  16652. 9.8,
  16653. 10
  16654. ];
  16655. function multiply(matrix1, matrix2) {
  16656. var col = [];
  16657. var out = new Array(25);
  16658. var val;
  16659. for (var i = 0; i < 5; i++) {
  16660. for (var j = 0; j < 5; j++) {
  16661. col[j] = matrix2[j + i * 5];
  16662. }
  16663. for (var j = 0; j < 5; j++) {
  16664. val = 0;
  16665. for (var k = 0; k < 5; k++) {
  16666. val += matrix1[j + k * 5] * col[k];
  16667. }
  16668. out[j + i * 5] = val;
  16669. }
  16670. }
  16671. return out;
  16672. }
  16673. function adjustContrast(matrix, value) {
  16674. var x;
  16675. value = clamp$1(value, -1, 1);
  16676. value *= 100;
  16677. if (value < 0) {
  16678. x = 127 + value / 100 * 127;
  16679. } else {
  16680. x = value % 1;
  16681. if (x === 0) {
  16682. x = DELTA_INDEX[value];
  16683. } else {
  16684. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  16685. }
  16686. x = x * 127 + 127;
  16687. }
  16688. return multiply(matrix, [
  16689. x / 127,
  16690. 0,
  16691. 0,
  16692. 0,
  16693. 0.5 * (127 - x),
  16694. 0,
  16695. x / 127,
  16696. 0,
  16697. 0,
  16698. 0.5 * (127 - x),
  16699. 0,
  16700. 0,
  16701. x / 127,
  16702. 0,
  16703. 0.5 * (127 - x),
  16704. 0,
  16705. 0,
  16706. 0,
  16707. 1,
  16708. 0,
  16709. 0,
  16710. 0,
  16711. 0,
  16712. 0,
  16713. 1
  16714. ]);
  16715. }
  16716. function adjustBrightness(matrix, value) {
  16717. value = clamp$1(255 * value, -255, 255);
  16718. return multiply(matrix, [
  16719. 1,
  16720. 0,
  16721. 0,
  16722. 0,
  16723. value,
  16724. 0,
  16725. 1,
  16726. 0,
  16727. 0,
  16728. value,
  16729. 0,
  16730. 0,
  16731. 1,
  16732. 0,
  16733. value,
  16734. 0,
  16735. 0,
  16736. 0,
  16737. 1,
  16738. 0,
  16739. 0,
  16740. 0,
  16741. 0,
  16742. 0,
  16743. 1
  16744. ]);
  16745. }
  16746. function adjustColors(matrix, adjustR, adjustG, adjustB) {
  16747. adjustR = clamp$1(adjustR, 0, 2);
  16748. adjustG = clamp$1(adjustG, 0, 2);
  16749. adjustB = clamp$1(adjustB, 0, 2);
  16750. return multiply(matrix, [
  16751. adjustR,
  16752. 0,
  16753. 0,
  16754. 0,
  16755. 0,
  16756. 0,
  16757. adjustG,
  16758. 0,
  16759. 0,
  16760. 0,
  16761. 0,
  16762. 0,
  16763. adjustB,
  16764. 0,
  16765. 0,
  16766. 0,
  16767. 0,
  16768. 0,
  16769. 1,
  16770. 0,
  16771. 0,
  16772. 0,
  16773. 0,
  16774. 0,
  16775. 1
  16776. ]);
  16777. }
  16778. function colorFilter(ir, matrix) {
  16779. return ir.toCanvas().then(function (canvas) {
  16780. return applyColorFilter(canvas, ir.getType(), matrix);
  16781. });
  16782. }
  16783. function applyColorFilter(canvas, type, matrix) {
  16784. var context = get2dContext(canvas);
  16785. function applyMatrix(pixelsData, m) {
  16786. var r, g, b, a;
  16787. var data = pixelsData.data, m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8], m9 = m[9], m10 = m[10], m11 = m[11], m12 = m[12], m13 = m[13], m14 = m[14], m15 = m[15], m16 = m[16], m17 = m[17], m18 = m[18], m19 = m[19];
  16788. for (var i = 0; i < data.length; i += 4) {
  16789. r = data[i];
  16790. g = data[i + 1];
  16791. b = data[i + 2];
  16792. a = data[i + 3];
  16793. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  16794. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  16795. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  16796. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  16797. }
  16798. return pixelsData;
  16799. }
  16800. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  16801. context.putImageData(pixels, 0, 0);
  16802. return fromCanvas(canvas, type);
  16803. }
  16804. function convoluteFilter(ir, matrix) {
  16805. return ir.toCanvas().then(function (canvas) {
  16806. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  16807. });
  16808. }
  16809. function applyConvoluteFilter(canvas, type, matrix) {
  16810. var context = get2dContext(canvas);
  16811. function applyMatrix(pIn, pOut, aMatrix) {
  16812. function clamp(value, min, max) {
  16813. if (value > max) {
  16814. value = max;
  16815. } else if (value < min) {
  16816. value = min;
  16817. }
  16818. return value;
  16819. }
  16820. var side = Math.round(Math.sqrt(aMatrix.length));
  16821. var halfSide = Math.floor(side / 2);
  16822. var rgba = pIn.data;
  16823. var drgba = pOut.data;
  16824. var w = pIn.width;
  16825. var h = pIn.height;
  16826. for (var y = 0; y < h; y++) {
  16827. for (var x = 0; x < w; x++) {
  16828. var r = 0;
  16829. var g = 0;
  16830. var b = 0;
  16831. for (var cy = 0; cy < side; cy++) {
  16832. for (var cx = 0; cx < side; cx++) {
  16833. var scx = clamp(x + cx - halfSide, 0, w - 1);
  16834. var scy = clamp(y + cy - halfSide, 0, h - 1);
  16835. var innerOffset = (scy * w + scx) * 4;
  16836. var wt = aMatrix[cy * side + cx];
  16837. r += rgba[innerOffset] * wt;
  16838. g += rgba[innerOffset + 1] * wt;
  16839. b += rgba[innerOffset + 2] * wt;
  16840. }
  16841. }
  16842. var offset = (y * w + x) * 4;
  16843. drgba[offset] = clamp(r, 0, 255);
  16844. drgba[offset + 1] = clamp(g, 0, 255);
  16845. drgba[offset + 2] = clamp(b, 0, 255);
  16846. }
  16847. }
  16848. return pOut;
  16849. }
  16850. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  16851. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  16852. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  16853. context.putImageData(pixelsOut, 0, 0);
  16854. return fromCanvas(canvas, type);
  16855. }
  16856. function functionColorFilter(colorFn) {
  16857. var filterImpl = function (canvas, type, value) {
  16858. var context = get2dContext(canvas);
  16859. var lookup = new Array(256);
  16860. function applyLookup(pixelsData, lookupData) {
  16861. var data = pixelsData.data;
  16862. for (var i = 0; i < data.length; i += 4) {
  16863. data[i] = lookupData[data[i]];
  16864. data[i + 1] = lookupData[data[i + 1]];
  16865. data[i + 2] = lookupData[data[i + 2]];
  16866. }
  16867. return pixelsData;
  16868. }
  16869. for (var i = 0; i < lookup.length; i++) {
  16870. lookup[i] = colorFn(i, value);
  16871. }
  16872. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  16873. context.putImageData(pixels, 0, 0);
  16874. return fromCanvas(canvas, type);
  16875. };
  16876. return function (ir, value) {
  16877. return ir.toCanvas().then(function (canvas) {
  16878. return filterImpl(canvas, ir.getType(), value);
  16879. });
  16880. };
  16881. }
  16882. function complexAdjustableColorFilter(matrixAdjustFn) {
  16883. return function (ir, adjust) {
  16884. return colorFilter(ir, matrixAdjustFn(identity$1(), adjust));
  16885. };
  16886. }
  16887. function basicColorFilter(matrix) {
  16888. return function (ir) {
  16889. return colorFilter(ir, matrix);
  16890. };
  16891. }
  16892. function basicConvolutionFilter(kernel) {
  16893. return function (ir) {
  16894. return convoluteFilter(ir, kernel);
  16895. };
  16896. }
  16897. var invert = basicColorFilter([
  16898. -1,
  16899. 0,
  16900. 0,
  16901. 0,
  16902. 255,
  16903. 0,
  16904. -1,
  16905. 0,
  16906. 0,
  16907. 255,
  16908. 0,
  16909. 0,
  16910. -1,
  16911. 0,
  16912. 255,
  16913. 0,
  16914. 0,
  16915. 0,
  16916. 1,
  16917. 0,
  16918. 0,
  16919. 0,
  16920. 0,
  16921. 0,
  16922. 1
  16923. ]);
  16924. var brightness = complexAdjustableColorFilter(adjustBrightness);
  16925. var contrast = complexAdjustableColorFilter(adjustContrast);
  16926. var colorize = function (ir, adjustR, adjustG, adjustB) {
  16927. return colorFilter(ir, adjustColors(identity$1(), adjustR, adjustG, adjustB));
  16928. };
  16929. var sharpen = basicConvolutionFilter([
  16930. 0,
  16931. -1,
  16932. 0,
  16933. -1,
  16934. 5,
  16935. -1,
  16936. 0,
  16937. -1,
  16938. 0
  16939. ]);
  16940. var gamma = functionColorFilter(function (color, value) {
  16941. return Math.pow(color / 255, 1 - value) * 255;
  16942. });
  16943. function scale(image, dW, dH) {
  16944. var sW = getWidth(image);
  16945. var sH = getHeight(image);
  16946. var wRatio = dW / sW;
  16947. var hRatio = dH / sH;
  16948. var scaleCapped = false;
  16949. if (wRatio < 0.5 || wRatio > 2) {
  16950. wRatio = wRatio < 0.5 ? 0.5 : 2;
  16951. scaleCapped = true;
  16952. }
  16953. if (hRatio < 0.5 || hRatio > 2) {
  16954. hRatio = hRatio < 0.5 ? 0.5 : 2;
  16955. scaleCapped = true;
  16956. }
  16957. var scaled = _scale(image, wRatio, hRatio);
  16958. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  16959. return scale(tCanvas, dW, dH);
  16960. });
  16961. }
  16962. function _scale(image, wRatio, hRatio) {
  16963. return new Promise$1(function (resolve) {
  16964. var sW = getWidth(image);
  16965. var sH = getHeight(image);
  16966. var dW = Math.floor(sW * wRatio);
  16967. var dH = Math.floor(sH * hRatio);
  16968. var canvas = create$5(dW, dH);
  16969. var context = get2dContext(canvas);
  16970. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  16971. resolve(canvas);
  16972. });
  16973. }
  16974. function rotate(ir, angle) {
  16975. return ir.toCanvas().then(function (canvas) {
  16976. return applyRotate(canvas, ir.getType(), angle);
  16977. });
  16978. }
  16979. function applyRotate(image, type, angle) {
  16980. var canvas = create$5(image.width, image.height);
  16981. var context = get2dContext(canvas);
  16982. var translateX = 0;
  16983. var translateY = 0;
  16984. angle = angle < 0 ? 360 + angle : angle;
  16985. if (angle === 90 || angle === 270) {
  16986. resize(canvas, canvas.height, canvas.width);
  16987. }
  16988. if (angle === 90 || angle === 180) {
  16989. translateX = canvas.width;
  16990. }
  16991. if (angle === 270 || angle === 180) {
  16992. translateY = canvas.height;
  16993. }
  16994. context.translate(translateX, translateY);
  16995. context.rotate(angle * Math.PI / 180);
  16996. context.drawImage(image, 0, 0);
  16997. return fromCanvas(canvas, type);
  16998. }
  16999. function flip(ir, axis) {
  17000. return ir.toCanvas().then(function (canvas) {
  17001. return applyFlip(canvas, ir.getType(), axis);
  17002. });
  17003. }
  17004. function applyFlip(image, type, axis) {
  17005. var canvas = create$5(image.width, image.height);
  17006. var context = get2dContext(canvas);
  17007. if (axis === 'v') {
  17008. context.scale(1, -1);
  17009. context.drawImage(image, 0, -canvas.height);
  17010. } else {
  17011. context.scale(-1, 1);
  17012. context.drawImage(image, -canvas.width, 0);
  17013. }
  17014. return fromCanvas(canvas, type);
  17015. }
  17016. function crop(ir, x, y, w, h) {
  17017. return ir.toCanvas().then(function (canvas) {
  17018. return applyCrop(canvas, ir.getType(), x, y, w, h);
  17019. });
  17020. }
  17021. function applyCrop(image, type, x, y, w, h) {
  17022. var canvas = create$5(w, h);
  17023. var context = get2dContext(canvas);
  17024. context.drawImage(image, -x, -y);
  17025. return fromCanvas(canvas, type);
  17026. }
  17027. function resize$1(ir, w, h) {
  17028. return ir.toCanvas().then(function (canvas) {
  17029. return scale(canvas, w, h).then(function (newCanvas) {
  17030. return fromCanvas(newCanvas, ir.getType());
  17031. });
  17032. });
  17033. }
  17034. var invert$1 = function (ir) {
  17035. return invert(ir);
  17036. };
  17037. var sharpen$1 = function (ir) {
  17038. return sharpen(ir);
  17039. };
  17040. var gamma$1 = function (ir, value) {
  17041. return gamma(ir, value);
  17042. };
  17043. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  17044. return colorize(ir, adjustR, adjustG, adjustB);
  17045. };
  17046. var brightness$1 = function (ir, adjust) {
  17047. return brightness(ir, adjust);
  17048. };
  17049. var contrast$1 = function (ir, adjust) {
  17050. return contrast(ir, adjust);
  17051. };
  17052. var flip$1 = function (ir, axis) {
  17053. return flip(ir, axis);
  17054. };
  17055. var crop$1 = function (ir, x, y, w, h) {
  17056. return crop(ir, x, y, w, h);
  17057. };
  17058. var resize$2 = function (ir, w, h) {
  17059. return resize$1(ir, w, h);
  17060. };
  17061. var rotate$1 = function (ir, angle) {
  17062. return rotate(ir, angle);
  17063. };
  17064. var renderIcon$1 = function (iconHtml, behaviours) {
  17065. return __assign({
  17066. dom: {
  17067. tag: 'span',
  17068. innerHtml: iconHtml,
  17069. classes: [
  17070. 'tox-icon',
  17071. 'tox-tbtn__icon-wrap'
  17072. ]
  17073. }
  17074. }, behaviours);
  17075. };
  17076. var renderIconFromPack = function (iconName, iconsProvider) {
  17077. return renderIcon$1(get$d(iconName, iconsProvider), {});
  17078. };
  17079. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  17080. return renderIcon$1(get$d(iconName, iconsProvider), { behaviours: derive$1([Replacing.config({})]) });
  17081. };
  17082. var renderLabel$1 = function (text, prefix, providersBackstage) {
  17083. return {
  17084. dom: {
  17085. tag: 'span',
  17086. innerHtml: providersBackstage.translate(text),
  17087. classes: [prefix + '__select-label']
  17088. },
  17089. behaviours: derive$1([Replacing.config({})])
  17090. };
  17091. };
  17092. var _a$1;
  17093. var internalToolbarButtonExecute = generate$1('toolbar.button.execute');
  17094. var onToolbarButtonExecute = function (info) {
  17095. return runOnExecute(function (comp, _simulatedEvent) {
  17096. runWithApi(info, comp)(function (itemApi) {
  17097. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  17098. info.onAction(itemApi);
  17099. });
  17100. });
  17101. };
  17102. var toolbarButtonEventOrder = (_a$1 = {}, _a$1[execute()] = [
  17103. 'disabling',
  17104. 'alloy.base.behaviour',
  17105. 'toggling',
  17106. 'toolbar-button-events'
  17107. ], _a$1);
  17108. var updateMenuText = generate$1('update-menu-text');
  17109. var updateMenuIcon = generate$1('update-menu-icon');
  17110. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  17111. var editorOffCell = Cell(noop);
  17112. var optMemDisplayText = spec.text.map(function (text) {
  17113. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  17114. });
  17115. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  17116. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  17117. });
  17118. var onLeftOrRightInMenu = function (comp, se) {
  17119. var dropdown = Representing.getValue(comp);
  17120. Focusing.focus(dropdown);
  17121. emitWith(dropdown, 'keydown', { raw: se.event.raw });
  17122. Dropdown.close(dropdown);
  17123. return Optional.some(true);
  17124. };
  17125. var role = spec.role.fold(function () {
  17126. return {};
  17127. }, function (role) {
  17128. return { role: role };
  17129. });
  17130. var tooltipAttributes = spec.tooltip.fold(function () {
  17131. return {};
  17132. }, function (tooltip) {
  17133. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  17134. return {
  17135. 'title': translatedTooltip,
  17136. 'aria-label': translatedTooltip
  17137. };
  17138. });
  17139. var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
  17140. dom: {
  17141. tag: 'button',
  17142. classes: [
  17143. prefix,
  17144. prefix + '--select'
  17145. ].concat(map(spec.classes, function (c) {
  17146. return prefix + '--' + c;
  17147. })),
  17148. attributes: __assign({}, tooltipAttributes)
  17149. },
  17150. components: componentRenderPipeline([
  17151. optMemDisplayIcon.map(function (mem) {
  17152. return mem.asSpec();
  17153. }),
  17154. optMemDisplayText.map(function (mem) {
  17155. return mem.asSpec();
  17156. }),
  17157. Optional.some({
  17158. dom: {
  17159. tag: 'div',
  17160. classes: [prefix + '__select-chevron'],
  17161. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  17162. }
  17163. })
  17164. ]),
  17165. matchWidth: true,
  17166. useMinWidth: true,
  17167. dropdownBehaviours: derive$1(__spreadArrays(spec.dropdownBehaviours, [
  17168. DisablingConfigs.button(function () {
  17169. return spec.disabled || sharedBackstage.providers.isReadOnly();
  17170. }),
  17171. receivingConfig(),
  17172. Unselecting.config({}),
  17173. Replacing.config({}),
  17174. config('dropdown-events', [
  17175. onControlAttached(spec, editorOffCell),
  17176. onControlDetached(spec, editorOffCell)
  17177. ]),
  17178. config('menubutton-update-display-text', [
  17179. run(updateMenuText, function (comp, se) {
  17180. optMemDisplayText.bind(function (mem) {
  17181. return mem.getOpt(comp);
  17182. }).each(function (displayText) {
  17183. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event.text))]);
  17184. });
  17185. }),
  17186. run(updateMenuIcon, function (comp, se) {
  17187. optMemDisplayIcon.bind(function (mem) {
  17188. return mem.getOpt(comp);
  17189. }).each(function (displayIcon) {
  17190. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
  17191. });
  17192. })
  17193. ])
  17194. ])),
  17195. eventOrder: deepMerge(toolbarButtonEventOrder, {
  17196. mousedown: [
  17197. 'focusing',
  17198. 'alloy.base.behaviour',
  17199. 'item-type-events',
  17200. 'normal-dropdown-events'
  17201. ]
  17202. }),
  17203. sandboxBehaviours: derive$1([Keying.config({
  17204. mode: 'special',
  17205. onLeft: onLeftOrRightInMenu,
  17206. onRight: onLeftOrRightInMenu
  17207. })]),
  17208. lazySink: sharedBackstage.getSink,
  17209. toggleClass: prefix + '--active',
  17210. parts: { menu: part(false, spec.columns, spec.presets) },
  17211. fetch: function (comp) {
  17212. return Future.nu(curry(spec.fetch, comp));
  17213. }
  17214. })));
  17215. return memDropdown.asSpec();
  17216. };
  17217. var isMenuItemReference = function (item) {
  17218. return isString(item);
  17219. };
  17220. var isSeparator = function (item) {
  17221. return item.type === 'separator';
  17222. };
  17223. var isExpandingMenuItem = function (item) {
  17224. return has(item, 'getSubmenuItems');
  17225. };
  17226. var separator$1 = { type: 'separator' };
  17227. var unwrapReferences = function (items, menuItems) {
  17228. var realItems = foldl(items, function (acc, item) {
  17229. if (isMenuItemReference(item)) {
  17230. if (item === '') {
  17231. return acc;
  17232. } else if (item === '|') {
  17233. return acc.length > 0 && !isSeparator(acc[acc.length - 1]) ? acc.concat([separator$1]) : acc;
  17234. } else if (has(menuItems, item.toLowerCase())) {
  17235. return acc.concat([menuItems[item.toLowerCase()]]);
  17236. } else {
  17237. return acc;
  17238. }
  17239. } else {
  17240. return acc.concat([item]);
  17241. }
  17242. }, []);
  17243. if (realItems.length > 0 && isSeparator(realItems[realItems.length - 1])) {
  17244. realItems.pop();
  17245. }
  17246. return realItems;
  17247. };
  17248. var getFromExpandingItem = function (item, menuItems) {
  17249. var submenuItems = item.getSubmenuItems();
  17250. var rest = expand(submenuItems, menuItems);
  17251. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  17252. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  17253. return {
  17254. item: item,
  17255. menus: newMenus,
  17256. expansions: newExpansions
  17257. };
  17258. };
  17259. var getFromItem = function (item, menuItems) {
  17260. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  17261. item: item,
  17262. menus: {},
  17263. expansions: {}
  17264. };
  17265. };
  17266. var generateValueIfRequired = function (item) {
  17267. if (isSeparator(item)) {
  17268. return item;
  17269. } else {
  17270. var itemValue = get(item, 'value').getOrThunk(function () {
  17271. return generate$1('generated-menu-item');
  17272. });
  17273. return deepMerge({ value: itemValue }, item);
  17274. }
  17275. };
  17276. var expand = function (items, menuItems) {
  17277. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  17278. return foldr(realItems, function (acc, item) {
  17279. var itemWithValue = generateValueIfRequired(item);
  17280. var newData = getFromItem(itemWithValue, menuItems);
  17281. return {
  17282. menus: deepMerge(acc.menus, newData.menus),
  17283. items: [newData.item].concat(acc.items),
  17284. expansions: deepMerge(acc.expansions, newData.expansions)
  17285. };
  17286. }, {
  17287. menus: {},
  17288. expansions: {},
  17289. items: []
  17290. });
  17291. };
  17292. var build$2 = function (items, itemResponse, backstage, isHorizontalMenu) {
  17293. var primary = generate$1('primary-menu');
  17294. var data = expand(items, backstage.shared.providers.menuItems());
  17295. if (data.items.length === 0) {
  17296. return Optional.none();
  17297. }
  17298. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  17299. var submenus = map$2(data.menus, function (menuItems, menuName) {
  17300. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  17301. });
  17302. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  17303. return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
  17304. };
  17305. var getMenuButtonApi = function (component) {
  17306. return {
  17307. isDisabled: function () {
  17308. return Disabling.isDisabled(component);
  17309. },
  17310. setDisabled: function (state) {
  17311. return Disabling.set(component, state);
  17312. },
  17313. setActive: function (state) {
  17314. var elm = component.element;
  17315. if (state) {
  17316. add$2(elm, 'tox-tbtn--enabled');
  17317. set$1(elm, 'aria-pressed', true);
  17318. } else {
  17319. remove$4(elm, 'tox-tbtn--enabled');
  17320. remove$1(elm, 'aria-pressed');
  17321. }
  17322. },
  17323. isActive: function () {
  17324. return has$2(component.element, 'tox-tbtn--enabled');
  17325. }
  17326. };
  17327. };
  17328. var renderMenuButton = function (spec, prefix, backstage, role) {
  17329. return renderCommonDropdown({
  17330. text: spec.text,
  17331. icon: spec.icon,
  17332. tooltip: spec.tooltip,
  17333. role: role,
  17334. fetch: function (_comp, callback) {
  17335. spec.fetch(function (items) {
  17336. callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  17337. });
  17338. },
  17339. onSetup: spec.onSetup,
  17340. getApi: getMenuButtonApi,
  17341. columns: 1,
  17342. presets: 'normal',
  17343. classes: [],
  17344. dropdownBehaviours: [Tabstopping.config({})]
  17345. }, prefix, backstage.shared);
  17346. };
  17347. var getFetch$1 = function (items, getButton, backstage) {
  17348. var getMenuItemAction = function (item) {
  17349. return function (api) {
  17350. var newValue = !api.isActive();
  17351. api.setActive(newValue);
  17352. item.storage.set(newValue);
  17353. backstage.shared.getSink().each(function (sink) {
  17354. getButton().getOpt(sink).each(function (orig) {
  17355. focus$1(orig.element);
  17356. emitWith(orig, formActionEvent, {
  17357. name: item.name,
  17358. value: item.storage.get()
  17359. });
  17360. });
  17361. });
  17362. };
  17363. };
  17364. var getMenuItemSetup = function (item) {
  17365. return function (api) {
  17366. api.setActive(item.storage.get());
  17367. };
  17368. };
  17369. return function (success) {
  17370. success(map(items, function (item) {
  17371. var text = item.text.fold(function () {
  17372. return {};
  17373. }, function (text) {
  17374. return { text: text };
  17375. });
  17376. return __assign(__assign({
  17377. type: item.type,
  17378. active: false
  17379. }, text), {
  17380. onAction: getMenuItemAction(item),
  17381. onSetup: getMenuItemSetup(item)
  17382. });
  17383. }));
  17384. };
  17385. };
  17386. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) {
  17387. if (extraBehaviours === void 0) {
  17388. extraBehaviours = [];
  17389. }
  17390. var action = actionOpt.fold(function () {
  17391. return {};
  17392. }, function (action) {
  17393. return { action: action };
  17394. });
  17395. var common = __assign({
  17396. buttonBehaviours: derive$1([
  17397. DisablingConfigs.button(function () {
  17398. return spec.disabled || providersBackstage.isReadOnly();
  17399. }),
  17400. receivingConfig(),
  17401. Tabstopping.config({}),
  17402. config('button press', [
  17403. preventDefault('click'),
  17404. preventDefault('mousedown')
  17405. ])
  17406. ].concat(extraBehaviours)),
  17407. eventOrder: {
  17408. click: [
  17409. 'button press',
  17410. 'alloy.base.behaviour'
  17411. ],
  17412. mousedown: [
  17413. 'button press',
  17414. 'alloy.base.behaviour'
  17415. ]
  17416. }
  17417. }, action);
  17418. var domFinal = deepMerge(common, { dom: dom });
  17419. return deepMerge(domFinal, { components: components });
  17420. };
  17421. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  17422. if (extraBehaviours === void 0) {
  17423. extraBehaviours = [];
  17424. }
  17425. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  17426. return {
  17427. 'aria-label': providersBackstage.translate(tooltip),
  17428. 'title': providersBackstage.translate(tooltip)
  17429. };
  17430. }).getOr({});
  17431. var dom = {
  17432. tag: 'button',
  17433. classes: ['tox-tbtn'],
  17434. attributes: tooltipAttributes
  17435. };
  17436. var icon = spec.icon.map(function (iconName) {
  17437. return renderIconFromPack(iconName, providersBackstage.icons);
  17438. });
  17439. var components = componentRenderPipeline([icon]);
  17440. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17441. };
  17442. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  17443. if (extraBehaviours === void 0) {
  17444. extraBehaviours = [];
  17445. }
  17446. var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
  17447. return Button.sketch(iconButtonSpec);
  17448. };
  17449. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17450. if (extraBehaviours === void 0) {
  17451. extraBehaviours = [];
  17452. }
  17453. if (extraClasses === void 0) {
  17454. extraClasses = [];
  17455. }
  17456. var translatedText = providersBackstage.translate(spec.text);
  17457. var icon = spec.icon ? spec.icon.map(function (iconName) {
  17458. return renderIconFromPack(iconName, providersBackstage.icons);
  17459. }) : Optional.none();
  17460. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  17461. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  17462. var classes = __spreadArrays(!spec.primary && !spec.borderless ? [
  17463. 'tox-button',
  17464. 'tox-button--secondary'
  17465. ] : ['tox-button'], icon.isSome() ? ['tox-button--icon'] : [], spec.borderless ? ['tox-button--naked'] : [], extraClasses);
  17466. var dom = __assign(__assign({
  17467. tag: 'button',
  17468. classes: classes
  17469. }, innerHtml), { attributes: { title: translatedText } });
  17470. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17471. };
  17472. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17473. if (extraBehaviours === void 0) {
  17474. extraBehaviours = [];
  17475. }
  17476. if (extraClasses === void 0) {
  17477. extraClasses = [];
  17478. }
  17479. var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
  17480. return Button.sketch(buttonSpec);
  17481. };
  17482. var getAction = function (name, buttonType) {
  17483. return function (comp) {
  17484. if (buttonType === 'custom') {
  17485. emitWith(comp, formActionEvent, {
  17486. name: name,
  17487. value: {}
  17488. });
  17489. } else if (buttonType === 'submit') {
  17490. emit(comp, formSubmitEvent);
  17491. } else if (buttonType === 'cancel') {
  17492. emit(comp, formCancelEvent);
  17493. } else {
  17494. console.error('Unknown button type: ', buttonType);
  17495. }
  17496. };
  17497. };
  17498. var isMenuFooterButtonSpec = function (spec, buttonType) {
  17499. return buttonType === 'menu';
  17500. };
  17501. var isNormalFooterButtonSpec = function (spec, buttonType) {
  17502. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  17503. };
  17504. var renderFooterButton = function (spec, buttonType, backstage) {
  17505. if (isMenuFooterButtonSpec(spec, buttonType)) {
  17506. var getButton = function () {
  17507. return memButton_1;
  17508. };
  17509. var menuButtonSpec = spec;
  17510. var fixedSpec = __assign(__assign({}, spec), {
  17511. onSetup: function (api) {
  17512. api.setDisabled(spec.disabled);
  17513. return noop;
  17514. },
  17515. fetch: getFetch$1(menuButtonSpec.items, getButton, backstage)
  17516. });
  17517. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none()));
  17518. return memButton_1.asSpec();
  17519. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  17520. var action = getAction(spec.name, buttonType);
  17521. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  17522. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  17523. } else {
  17524. console.error('Unknown footer button type: ', buttonType);
  17525. }
  17526. };
  17527. var renderDialogButton = function (spec, providersBackstage) {
  17528. var action = getAction(spec.name, 'custom');
  17529. return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
  17530. RepresentingConfigs.memory(''),
  17531. ComposingConfigs.self()
  17532. ]))));
  17533. };
  17534. var schema$i = constant([
  17535. defaulted$1('field1Name', 'field1'),
  17536. defaulted$1('field2Name', 'field2'),
  17537. onStrictHandler('onLockedChange'),
  17538. markers(['lockClass']),
  17539. defaulted$1('locked', false),
  17540. SketchBehaviours.field('coupledFieldBehaviours', [
  17541. Composing,
  17542. Representing
  17543. ])
  17544. ]);
  17545. var getField = function (comp, detail, partName) {
  17546. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  17547. };
  17548. var coupledPart = function (selfName, otherName) {
  17549. return required({
  17550. factory: FormField,
  17551. name: selfName,
  17552. overrides: function (detail) {
  17553. return {
  17554. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run(input(), function (me) {
  17555. getField(me, detail, otherName).each(function (other) {
  17556. getPart(me, detail, 'lock').each(function (lock) {
  17557. if (Toggling.isOn(lock)) {
  17558. detail.onLockedChange(me, other, lock);
  17559. }
  17560. });
  17561. });
  17562. })])])
  17563. };
  17564. }
  17565. });
  17566. };
  17567. var parts$5 = constant([
  17568. coupledPart('field1', 'field2'),
  17569. coupledPart('field2', 'field1'),
  17570. required({
  17571. factory: Button,
  17572. schema: [strict$1('dom')],
  17573. name: 'lock',
  17574. overrides: function (detail) {
  17575. return {
  17576. buttonBehaviours: derive$1([Toggling.config({
  17577. selected: detail.locked,
  17578. toggleClass: detail.markers.lockClass,
  17579. aria: { mode: 'pressed' }
  17580. })])
  17581. };
  17582. }
  17583. })
  17584. ]);
  17585. var factory$7 = function (detail, components, _spec, _externals) {
  17586. return {
  17587. uid: detail.uid,
  17588. dom: detail.dom,
  17589. components: components,
  17590. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  17591. Composing.config({ find: Optional.some }),
  17592. Representing.config({
  17593. store: {
  17594. mode: 'manual',
  17595. getValue: function (comp) {
  17596. var _a;
  17597. var parts = getPartsOrDie(comp, detail, [
  17598. 'field1',
  17599. 'field2'
  17600. ]);
  17601. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  17602. },
  17603. setValue: function (comp, value) {
  17604. var parts = getPartsOrDie(comp, detail, [
  17605. 'field1',
  17606. 'field2'
  17607. ]);
  17608. if (hasNonNullableKey(value, detail.field1Name)) {
  17609. Representing.setValue(parts.field1(), value[detail.field1Name]);
  17610. }
  17611. if (hasNonNullableKey(value, detail.field2Name)) {
  17612. Representing.setValue(parts.field2(), value[detail.field2Name]);
  17613. }
  17614. }
  17615. }
  17616. })
  17617. ]),
  17618. apis: {
  17619. getField1: function (component) {
  17620. return getPart(component, detail, 'field1');
  17621. },
  17622. getField2: function (component) {
  17623. return getPart(component, detail, 'field2');
  17624. },
  17625. getLock: function (component) {
  17626. return getPart(component, detail, 'lock');
  17627. }
  17628. }
  17629. };
  17630. };
  17631. var FormCoupledInputs = composite$1({
  17632. name: 'FormCoupledInputs',
  17633. configFields: schema$i(),
  17634. partFields: parts$5(),
  17635. factory: factory$7,
  17636. apis: {
  17637. getField1: function (apis, component) {
  17638. return apis.getField1(component);
  17639. },
  17640. getField2: function (apis, component) {
  17641. return apis.getField2(component);
  17642. },
  17643. getLock: function (apis, component) {
  17644. return apis.getLock(component);
  17645. }
  17646. }
  17647. });
  17648. var formatSize = function (size) {
  17649. var unitDec = {
  17650. '': 0,
  17651. 'px': 0,
  17652. 'pt': 1,
  17653. 'mm': 1,
  17654. 'pc': 2,
  17655. 'ex': 2,
  17656. 'em': 2,
  17657. 'ch': 2,
  17658. 'rem': 2,
  17659. 'cm': 3,
  17660. 'in': 4,
  17661. '%': 4
  17662. };
  17663. var maxDecimal = function (unit) {
  17664. return unit in unitDec ? unitDec[unit] : 1;
  17665. };
  17666. var numText = size.value.toFixed(maxDecimal(size.unit));
  17667. if (numText.indexOf('.') !== -1) {
  17668. numText = numText.replace(/\.?0*$/, '');
  17669. }
  17670. return numText + size.unit;
  17671. };
  17672. var parseSize = function (sizeText) {
  17673. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  17674. var match = numPattern.exec(sizeText);
  17675. if (match !== null) {
  17676. var value = parseFloat(match[1]);
  17677. var unit = match[2];
  17678. return Result.value({
  17679. value: value,
  17680. unit: unit
  17681. });
  17682. } else {
  17683. return Result.error(sizeText);
  17684. }
  17685. };
  17686. var convertUnit = function (size, unit) {
  17687. var inInch = {
  17688. '': 96,
  17689. 'px': 96,
  17690. 'pt': 72,
  17691. 'cm': 2.54,
  17692. 'pc': 12,
  17693. 'mm': 25.4,
  17694. 'in': 1
  17695. };
  17696. var supported = function (u) {
  17697. return Object.prototype.hasOwnProperty.call(inInch, u);
  17698. };
  17699. if (size.unit === unit) {
  17700. return Optional.some(size.value);
  17701. } else if (supported(size.unit) && supported(unit)) {
  17702. if (inInch[size.unit] === inInch[unit]) {
  17703. return Optional.some(size.value);
  17704. } else {
  17705. return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
  17706. }
  17707. } else {
  17708. return Optional.none();
  17709. }
  17710. };
  17711. var noSizeConversion = function (_input) {
  17712. return Optional.none();
  17713. };
  17714. var ratioSizeConversion = function (scale, unit) {
  17715. return function (size) {
  17716. return convertUnit(size, unit).map(function (value) {
  17717. return {
  17718. value: value * scale,
  17719. unit: unit
  17720. };
  17721. });
  17722. };
  17723. };
  17724. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  17725. var cValue = parseSize(currentFieldText).toOptional();
  17726. var oValue = parseSize(otherFieldText).toOptional();
  17727. return lift2(cValue, oValue, function (cSize, oSize) {
  17728. return convertUnit(cSize, oSize.unit).map(function (val) {
  17729. return oSize.value / val;
  17730. }).map(function (r) {
  17731. return ratioSizeConversion(r, oSize.unit);
  17732. }).getOr(noSizeConversion);
  17733. }).getOr(noSizeConversion);
  17734. };
  17735. var renderSizeInput = function (spec, providersBackstage) {
  17736. var converter = noSizeConversion;
  17737. var ratioEvent = generate$1('ratio-event');
  17738. var pLock = FormCoupledInputs.parts.lock({
  17739. dom: {
  17740. tag: 'button',
  17741. classes: [
  17742. 'tox-lock',
  17743. 'tox-button',
  17744. 'tox-button--naked',
  17745. 'tox-button--icon'
  17746. ],
  17747. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  17748. },
  17749. components: [
  17750. {
  17751. dom: {
  17752. tag: 'span',
  17753. classes: [
  17754. 'tox-icon',
  17755. 'tox-lock-icon__lock'
  17756. ],
  17757. innerHtml: get$d('lock', providersBackstage.icons)
  17758. }
  17759. },
  17760. {
  17761. dom: {
  17762. tag: 'span',
  17763. classes: [
  17764. 'tox-icon',
  17765. 'tox-lock-icon__unlock'
  17766. ],
  17767. innerHtml: get$d('unlock', providersBackstage.icons)
  17768. }
  17769. }
  17770. ],
  17771. buttonBehaviours: derive$1([
  17772. Disabling.config({
  17773. disabled: function () {
  17774. return spec.disabled || providersBackstage.isReadOnly();
  17775. }
  17776. }),
  17777. receivingConfig(),
  17778. Tabstopping.config({})
  17779. ])
  17780. });
  17781. var formGroup = function (components) {
  17782. return {
  17783. dom: {
  17784. tag: 'div',
  17785. classes: ['tox-form__group']
  17786. },
  17787. components: components
  17788. };
  17789. };
  17790. var getFieldPart = function (isField1) {
  17791. return FormField.parts.field({
  17792. factory: Input,
  17793. inputClasses: ['tox-textfield'],
  17794. inputBehaviours: derive$1([
  17795. Disabling.config({
  17796. disabled: function () {
  17797. return spec.disabled || providersBackstage.isReadOnly();
  17798. }
  17799. }),
  17800. receivingConfig(),
  17801. Tabstopping.config({}),
  17802. config('size-input-events', [
  17803. run(focusin(), function (component, _simulatedEvent) {
  17804. emitWith(component, ratioEvent, { isField1: isField1 });
  17805. }),
  17806. run(change(), function (component, _simulatedEvent) {
  17807. emitWith(component, formChangeEvent, { name: spec.name });
  17808. })
  17809. ])
  17810. ]),
  17811. selectOnFocus: false
  17812. });
  17813. };
  17814. var getLabel = function (label) {
  17815. return {
  17816. dom: {
  17817. tag: 'label',
  17818. classes: ['tox-label'],
  17819. innerHtml: providersBackstage.translate(label)
  17820. }
  17821. };
  17822. };
  17823. var widthField = FormCoupledInputs.parts.field1(formGroup([
  17824. FormField.parts.label(getLabel('Width')),
  17825. getFieldPart(true)
  17826. ]));
  17827. var heightField = FormCoupledInputs.parts.field2(formGroup([
  17828. FormField.parts.label(getLabel('Height')),
  17829. getFieldPart(false)
  17830. ]));
  17831. return FormCoupledInputs.sketch({
  17832. dom: {
  17833. tag: 'div',
  17834. classes: ['tox-form__group']
  17835. },
  17836. components: [{
  17837. dom: {
  17838. tag: 'div',
  17839. classes: ['tox-form__controls-h-stack']
  17840. },
  17841. components: [
  17842. widthField,
  17843. heightField,
  17844. formGroup([
  17845. getLabel('&nbsp;'),
  17846. pLock
  17847. ])
  17848. ]
  17849. }],
  17850. field1Name: 'width',
  17851. field2Name: 'height',
  17852. locked: true,
  17853. markers: { lockClass: 'tox-locked' },
  17854. onLockedChange: function (current, other, _lock) {
  17855. parseSize(Representing.getValue(current)).each(function (size) {
  17856. converter(size).each(function (newSize) {
  17857. Representing.setValue(other, formatSize(newSize));
  17858. });
  17859. });
  17860. },
  17861. coupledFieldBehaviours: derive$1([
  17862. Disabling.config({
  17863. disabled: function () {
  17864. return spec.disabled || providersBackstage.isReadOnly();
  17865. },
  17866. onDisabled: function (comp) {
  17867. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  17868. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  17869. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  17870. },
  17871. onEnabled: function (comp) {
  17872. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  17873. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  17874. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  17875. }
  17876. }),
  17877. receivingConfig(),
  17878. config('size-input-events2', [run(ratioEvent, function (component, simulatedEvent) {
  17879. var isField1 = simulatedEvent.event.isField1;
  17880. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  17881. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  17882. var value1 = optCurrent.map(Representing.getValue).getOr('');
  17883. var value2 = optOther.map(Representing.getValue).getOr('');
  17884. converter = makeRatioConverter(value1, value2);
  17885. })])
  17886. ])
  17887. });
  17888. };
  17889. var undo = constant(generate$1('undo'));
  17890. var redo = constant(generate$1('redo'));
  17891. var zoom = constant(generate$1('zoom'));
  17892. var back = constant(generate$1('back'));
  17893. var apply = constant(generate$1('apply'));
  17894. var swap = constant(generate$1('swap'));
  17895. var transform = constant(generate$1('transform'));
  17896. var tempTransform = constant(generate$1('temp-transform'));
  17897. var transformApply = constant(generate$1('transform-apply'));
  17898. var internal = {
  17899. undo: undo,
  17900. redo: redo,
  17901. zoom: zoom,
  17902. back: back,
  17903. apply: apply,
  17904. swap: swap,
  17905. transform: transform,
  17906. tempTransform: tempTransform,
  17907. transformApply: transformApply
  17908. };
  17909. var saveState = constant('save-state');
  17910. var disable$1 = constant('disable');
  17911. var enable$1 = constant('enable');
  17912. var external$2 = {
  17913. formActionEvent: formActionEvent,
  17914. saveState: saveState,
  17915. disable: disable$1,
  17916. enable: enable$1
  17917. };
  17918. var renderEditPanel = function (imagePanel, providersBackstage) {
  17919. var createButton = function (text, action, disabled, primary) {
  17920. return record(renderButton({
  17921. name: text,
  17922. text: text,
  17923. disabled: disabled,
  17924. primary: primary,
  17925. icon: Optional.none(),
  17926. borderless: false
  17927. }, action, providersBackstage));
  17928. };
  17929. var createIconButton = function (icon, tooltip, action, disabled) {
  17930. return record(renderIconButton({
  17931. name: icon,
  17932. icon: Optional.some(icon),
  17933. tooltip: Optional.some(tooltip),
  17934. disabled: disabled,
  17935. primary: false,
  17936. borderless: false
  17937. }, action, providersBackstage));
  17938. };
  17939. var disableAllComponents = function (comps, eventcomp) {
  17940. comps.map(function (mem) {
  17941. var component = mem.get(eventcomp);
  17942. if (component.hasConfigured(Disabling)) {
  17943. Disabling.disable(component);
  17944. }
  17945. });
  17946. };
  17947. var enableAllComponents = function (comps, eventcomp) {
  17948. comps.map(function (mem) {
  17949. var component = mem.get(eventcomp);
  17950. if (component.hasConfigured(Disabling)) {
  17951. Disabling.enable(component);
  17952. }
  17953. });
  17954. };
  17955. var panelDom = {
  17956. tag: 'div',
  17957. classes: [
  17958. 'tox-image-tools__toolbar',
  17959. 'tox-image-tools-edit-panel'
  17960. ]
  17961. };
  17962. var noop$1 = noop;
  17963. var emit$1 = function (comp, event, data) {
  17964. emitWith(comp, event, data);
  17965. };
  17966. var emitDisable = function (component) {
  17967. return emit(component, external$2.disable());
  17968. };
  17969. var emitEnable = function (component) {
  17970. return emit(component, external$2.enable());
  17971. };
  17972. var emitTransform = function (comp, transform) {
  17973. emitDisable(comp);
  17974. emit$1(comp, internal.transform(), { transform: transform });
  17975. emitEnable(comp);
  17976. };
  17977. var emitTempTransform = function (comp, transform) {
  17978. emitDisable(comp);
  17979. emit$1(comp, internal.tempTransform(), { transform: transform });
  17980. emitEnable(comp);
  17981. };
  17982. var getBackSwap = function (anyInSystem) {
  17983. return function () {
  17984. memContainer.getOpt(anyInSystem).each(function (container) {
  17985. Replacing.set(container, [ButtonPanel]);
  17986. });
  17987. };
  17988. };
  17989. var emitTransformApply = function (comp, transform) {
  17990. emitDisable(comp);
  17991. emit$1(comp, internal.transformApply(), {
  17992. transform: transform,
  17993. swap: getBackSwap(comp)
  17994. });
  17995. emitEnable(comp);
  17996. };
  17997. var createBackButton = function () {
  17998. return createButton('Back', function (button) {
  17999. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  18000. }, false, false);
  18001. };
  18002. var createSpacer = function () {
  18003. return record({
  18004. dom: {
  18005. tag: 'div',
  18006. classes: ['tox-spacer']
  18007. },
  18008. behaviours: derive$1([Disabling.config({})])
  18009. });
  18010. };
  18011. var createApplyButton = function () {
  18012. return createButton('Apply', function (button) {
  18013. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  18014. }, true, true);
  18015. };
  18016. var makeCropTransform = function () {
  18017. return function (ir) {
  18018. var rect = imagePanel.getRect();
  18019. return crop$1(ir, rect.x, rect.y, rect.w, rect.h);
  18020. };
  18021. };
  18022. var cropPanelComponents = [
  18023. createBackButton(),
  18024. createSpacer(),
  18025. createButton('Apply', function (button) {
  18026. var transform = makeCropTransform();
  18027. emitTransformApply(button, transform);
  18028. imagePanel.hideCrop();
  18029. }, false, true)
  18030. ];
  18031. var CropPanel = Container.sketch({
  18032. dom: panelDom,
  18033. components: cropPanelComponents.map(function (mem) {
  18034. return mem.asSpec();
  18035. }),
  18036. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  18037. run(external$2.disable(), function (comp, _se) {
  18038. disableAllComponents(cropPanelComponents, comp);
  18039. }),
  18040. run(external$2.enable(), function (comp, _se) {
  18041. enableAllComponents(cropPanelComponents, comp);
  18042. })
  18043. ])])
  18044. });
  18045. var memSize = record(renderSizeInput({
  18046. name: 'size',
  18047. label: Optional.none(),
  18048. constrain: true,
  18049. disabled: false
  18050. }, providersBackstage));
  18051. var makeResizeTransform = function (width, height) {
  18052. return function (ir) {
  18053. return resize$2(ir, width, height);
  18054. };
  18055. };
  18056. var resizePanelComponents = [
  18057. createBackButton(),
  18058. createSpacer(),
  18059. memSize,
  18060. createSpacer(),
  18061. createButton('Apply', function (button) {
  18062. memSize.getOpt(button).each(function (sizeInput) {
  18063. var value = Representing.getValue(sizeInput);
  18064. var width = parseInt(value.width, 10);
  18065. var height = parseInt(value.height, 10);
  18066. var transform = makeResizeTransform(width, height);
  18067. emitTransformApply(button, transform);
  18068. });
  18069. }, false, true)
  18070. ];
  18071. var ResizePanel = Container.sketch({
  18072. dom: panelDom,
  18073. components: resizePanelComponents.map(function (mem) {
  18074. return mem.asSpec();
  18075. }),
  18076. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  18077. run(external$2.disable(), function (comp, _se) {
  18078. disableAllComponents(resizePanelComponents, comp);
  18079. }),
  18080. run(external$2.enable(), function (comp, _se) {
  18081. enableAllComponents(resizePanelComponents, comp);
  18082. })
  18083. ])])
  18084. });
  18085. var makeValueTransform = function (transform, value) {
  18086. return function (ir) {
  18087. return transform(ir, value);
  18088. };
  18089. };
  18090. var horizontalFlip = makeValueTransform(flip$1, 'h');
  18091. var verticalFlip = makeValueTransform(flip$1, 'v');
  18092. var counterclockwiseRotate = makeValueTransform(rotate$1, -90);
  18093. var clockwiseRotate = makeValueTransform(rotate$1, 90);
  18094. var flipRotateOnAction = function (comp, operation) {
  18095. emitTempTransform(comp, operation);
  18096. };
  18097. var flipRotateComponents = [
  18098. createBackButton(),
  18099. createSpacer(),
  18100. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  18101. flipRotateOnAction(button, horizontalFlip);
  18102. }, false),
  18103. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  18104. flipRotateOnAction(button, verticalFlip);
  18105. }, false),
  18106. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  18107. flipRotateOnAction(button, counterclockwiseRotate);
  18108. }, false),
  18109. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  18110. flipRotateOnAction(button, clockwiseRotate);
  18111. }, false),
  18112. createSpacer(),
  18113. createApplyButton()
  18114. ];
  18115. var FlipRotatePanel = Container.sketch({
  18116. dom: panelDom,
  18117. components: flipRotateComponents.map(function (mem) {
  18118. return mem.asSpec();
  18119. }),
  18120. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  18121. run(external$2.disable(), function (comp, _se) {
  18122. disableAllComponents(flipRotateComponents, comp);
  18123. }),
  18124. run(external$2.enable(), function (comp, _se) {
  18125. enableAllComponents(flipRotateComponents, comp);
  18126. })
  18127. ])])
  18128. });
  18129. var makeSlider = function (label, onChoose, min, value, max) {
  18130. var labelPart = Slider.parts.label({
  18131. dom: {
  18132. tag: 'label',
  18133. classes: ['tox-label'],
  18134. innerHtml: providersBackstage.translate(label)
  18135. }
  18136. });
  18137. var spectrum = Slider.parts.spectrum({
  18138. dom: {
  18139. tag: 'div',
  18140. classes: ['tox-slider__rail'],
  18141. attributes: { role: 'presentation' }
  18142. }
  18143. });
  18144. var thumb = Slider.parts.thumb({
  18145. dom: {
  18146. tag: 'div',
  18147. classes: ['tox-slider__handle'],
  18148. attributes: { role: 'presentation' }
  18149. }
  18150. });
  18151. return record(Slider.sketch({
  18152. dom: {
  18153. tag: 'div',
  18154. classes: ['tox-slider'],
  18155. attributes: { role: 'presentation' }
  18156. },
  18157. model: {
  18158. mode: 'x',
  18159. minX: min,
  18160. maxX: max,
  18161. getInitialValue: constant({ x: value })
  18162. },
  18163. components: [
  18164. labelPart,
  18165. spectrum,
  18166. thumb
  18167. ],
  18168. sliderBehaviours: derive$1([Focusing.config({})]),
  18169. onChoose: onChoose
  18170. }));
  18171. };
  18172. var makeVariableSlider = function (label, transform, min, value, max) {
  18173. var onChoose = function (slider, _thumb, value) {
  18174. var valTransform = makeValueTransform(transform, value.x / 100);
  18175. emitTransform(slider, valTransform);
  18176. };
  18177. return makeSlider(label, onChoose, min, value, max);
  18178. };
  18179. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  18180. return [
  18181. createBackButton(),
  18182. makeVariableSlider(label, transform, min, value, max),
  18183. createApplyButton()
  18184. ];
  18185. };
  18186. var createVariableFilterPanel = function (label, transform, min, value, max) {
  18187. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  18188. return Container.sketch({
  18189. dom: panelDom,
  18190. components: filterPanelComponents.map(function (mem) {
  18191. return mem.asSpec();
  18192. }),
  18193. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  18194. run(external$2.disable(), function (comp, _se) {
  18195. disableAllComponents(filterPanelComponents, comp);
  18196. }),
  18197. run(external$2.enable(), function (comp, _se) {
  18198. enableAllComponents(filterPanelComponents, comp);
  18199. })
  18200. ])])
  18201. });
  18202. };
  18203. var filterPanelComponents = [
  18204. createBackButton(),
  18205. createSpacer(),
  18206. createApplyButton()
  18207. ];
  18208. var FilterPanel = Container.sketch({
  18209. dom: panelDom,
  18210. components: filterPanelComponents.map(function (mem) {
  18211. return mem.asSpec();
  18212. })
  18213. });
  18214. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness$1, -100, 0, 100);
  18215. var ContrastPanel = createVariableFilterPanel('Contrast', contrast$1, -100, 0, 100);
  18216. var GammaPanel = createVariableFilterPanel('Gamma', gamma$1, -100, 0, 100);
  18217. var makeColorTransform = function (red, green, blue) {
  18218. return function (ir) {
  18219. return colorize$1(ir, red, green, blue);
  18220. };
  18221. };
  18222. var makeColorSlider = function (label) {
  18223. var onChoose = function (slider, _thumb, _value) {
  18224. var redOpt = memRed.getOpt(slider);
  18225. var blueOpt = memBlue.getOpt(slider);
  18226. var greenOpt = memGreen.getOpt(slider);
  18227. redOpt.each(function (red) {
  18228. blueOpt.each(function (blue) {
  18229. greenOpt.each(function (green) {
  18230. var r = Representing.getValue(red).x / 100;
  18231. var g = Representing.getValue(green).x / 100;
  18232. var b = Representing.getValue(blue).x / 100;
  18233. var transform = makeColorTransform(r, g, b);
  18234. emitTransform(slider, transform);
  18235. });
  18236. });
  18237. });
  18238. };
  18239. return makeSlider(label, onChoose, 0, 100, 200);
  18240. };
  18241. var memRed = makeColorSlider('R');
  18242. var memGreen = makeColorSlider('G');
  18243. var memBlue = makeColorSlider('B');
  18244. var colorizePanelComponents = [
  18245. createBackButton(),
  18246. memRed,
  18247. memGreen,
  18248. memBlue,
  18249. createApplyButton()
  18250. ];
  18251. var ColorizePanel = Container.sketch({
  18252. dom: panelDom,
  18253. components: colorizePanelComponents.map(function (mem) {
  18254. return mem.asSpec();
  18255. })
  18256. });
  18257. var getTransformPanelEvent = function (panel, transform, update) {
  18258. return function (button) {
  18259. var swap = function () {
  18260. memContainer.getOpt(button).each(function (container) {
  18261. Replacing.set(container, [panel]);
  18262. update(container);
  18263. });
  18264. };
  18265. emit$1(button, internal.swap(), {
  18266. transform: transform,
  18267. swap: swap
  18268. });
  18269. };
  18270. };
  18271. var cropPanelUpdate = function (_anyInSystem) {
  18272. imagePanel.showCrop();
  18273. };
  18274. var resizePanelUpdate = function (anyInSystem) {
  18275. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  18276. var measurements = imagePanel.getMeasurements();
  18277. var width = measurements.width;
  18278. var height = measurements.height;
  18279. Representing.setValue(sizeInput, {
  18280. width: width,
  18281. height: height
  18282. });
  18283. });
  18284. };
  18285. var sharpenTransform = Optional.some(sharpen$1);
  18286. var invertTransform = Optional.some(invert$1);
  18287. var buttonPanelComponents = [
  18288. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
  18289. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
  18290. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
  18291. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
  18292. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  18293. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
  18294. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
  18295. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
  18296. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  18297. ];
  18298. var ButtonPanel = Container.sketch({
  18299. dom: panelDom,
  18300. components: buttonPanelComponents.map(function (mem) {
  18301. return mem.asSpec();
  18302. })
  18303. });
  18304. var container = Container.sketch({
  18305. dom: { tag: 'div' },
  18306. components: [ButtonPanel],
  18307. containerBehaviours: derive$1([Replacing.config({})])
  18308. });
  18309. var memContainer = record(container);
  18310. var getApplyButton = function (anyInSystem) {
  18311. return memContainer.getOpt(anyInSystem).map(function (container) {
  18312. var panel = container.components()[0];
  18313. return panel.components()[panel.components().length - 1];
  18314. });
  18315. };
  18316. return {
  18317. memContainer: memContainer,
  18318. getApplyButton: getApplyButton
  18319. };
  18320. };
  18321. var global$b = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  18322. var global$c = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
  18323. var global$d = tinymce.util.Tools.resolve('tinymce.util.Observable');
  18324. var global$e = tinymce.util.Tools.resolve('tinymce.util.Tools');
  18325. var global$f = tinymce.util.Tools.resolve('tinymce.util.VK');
  18326. function getDocumentSize(doc) {
  18327. var max = Math.max;
  18328. var documentElement = doc.documentElement;
  18329. var body = doc.body;
  18330. var scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  18331. var clientWidth = max(documentElement.clientWidth, body.clientWidth);
  18332. var offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  18333. var scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  18334. var clientHeight = max(documentElement.clientHeight, body.clientHeight);
  18335. var offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  18336. return {
  18337. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  18338. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  18339. };
  18340. }
  18341. function updateWithTouchData(e) {
  18342. var keys, i;
  18343. if (e.changedTouches) {
  18344. keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  18345. for (i = 0; i < keys.length; i++) {
  18346. e[keys[i]] = e.changedTouches[0][keys[i]];
  18347. }
  18348. }
  18349. }
  18350. function DragHelper (id, settings) {
  18351. var $eventOverlay;
  18352. var doc = settings.document || document;
  18353. var downButton;
  18354. var startX, startY;
  18355. var handleElement = doc.getElementById(settings.handle || id);
  18356. var start = function (e) {
  18357. var docSize = getDocumentSize(doc);
  18358. var cursor;
  18359. updateWithTouchData(e);
  18360. e.preventDefault();
  18361. downButton = e.button;
  18362. var handleElm = handleElement;
  18363. startX = e.screenX;
  18364. startY = e.screenY;
  18365. if (window.getComputedStyle) {
  18366. cursor = window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
  18367. } else {
  18368. cursor = handleElm.runtimeStyle.cursor;
  18369. }
  18370. $eventOverlay = global$c('<div></div>').css({
  18371. position: 'absolute',
  18372. top: 0,
  18373. left: 0,
  18374. width: docSize.width,
  18375. height: docSize.height,
  18376. zIndex: 2147483647,
  18377. opacity: 0.0001,
  18378. cursor: cursor
  18379. }).appendTo(doc.body);
  18380. global$c(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
  18381. settings.start(e);
  18382. };
  18383. var drag = function (e) {
  18384. updateWithTouchData(e);
  18385. if (e.button !== downButton) {
  18386. return stop(e);
  18387. }
  18388. e.deltaX = e.screenX - startX;
  18389. e.deltaY = e.screenY - startY;
  18390. e.preventDefault();
  18391. settings.drag(e);
  18392. };
  18393. var stop = function (e) {
  18394. updateWithTouchData(e);
  18395. global$c(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
  18396. $eventOverlay.remove();
  18397. if (settings.stop) {
  18398. settings.stop(e);
  18399. }
  18400. };
  18401. this.destroy = function () {
  18402. global$c(handleElement).off();
  18403. };
  18404. global$c(handleElement).on('mousedown touchstart', start);
  18405. }
  18406. var count = 0;
  18407. var create$7 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18408. var dragHelpers;
  18409. var prefix = 'tox-';
  18410. var id = prefix + 'crid-' + count++;
  18411. var handles = [
  18412. {
  18413. name: 'move',
  18414. xMul: 0,
  18415. yMul: 0,
  18416. deltaX: 1,
  18417. deltaY: 1,
  18418. deltaW: 0,
  18419. deltaH: 0,
  18420. label: 'Crop Mask'
  18421. },
  18422. {
  18423. name: 'nw',
  18424. xMul: 0,
  18425. yMul: 0,
  18426. deltaX: 1,
  18427. deltaY: 1,
  18428. deltaW: -1,
  18429. deltaH: -1,
  18430. label: 'Top Left Crop Handle'
  18431. },
  18432. {
  18433. name: 'ne',
  18434. xMul: 1,
  18435. yMul: 0,
  18436. deltaX: 0,
  18437. deltaY: 1,
  18438. deltaW: 1,
  18439. deltaH: -1,
  18440. label: 'Top Right Crop Handle'
  18441. },
  18442. {
  18443. name: 'sw',
  18444. xMul: 0,
  18445. yMul: 1,
  18446. deltaX: 1,
  18447. deltaY: 0,
  18448. deltaW: -1,
  18449. deltaH: 1,
  18450. label: 'Bottom Left Crop Handle'
  18451. },
  18452. {
  18453. name: 'se',
  18454. xMul: 1,
  18455. yMul: 1,
  18456. deltaX: 0,
  18457. deltaY: 0,
  18458. deltaW: 1,
  18459. deltaH: 1,
  18460. label: 'Bottom Right Crop Handle'
  18461. }
  18462. ];
  18463. var blockers = [
  18464. 'top',
  18465. 'right',
  18466. 'bottom',
  18467. 'left'
  18468. ];
  18469. var getAbsoluteRect = function (outerRect, relativeRect) {
  18470. return {
  18471. x: relativeRect.x + outerRect.x,
  18472. y: relativeRect.y + outerRect.y,
  18473. w: relativeRect.w,
  18474. h: relativeRect.h
  18475. };
  18476. };
  18477. var getRelativeRect = function (outerRect, innerRect) {
  18478. return {
  18479. x: innerRect.x - outerRect.x,
  18480. y: innerRect.y - outerRect.y,
  18481. w: innerRect.w,
  18482. h: innerRect.h
  18483. };
  18484. };
  18485. var getInnerRect = function () {
  18486. return getRelativeRect(clampRect, currentRect);
  18487. };
  18488. function moveRect(handle, startRect, deltaX, deltaY) {
  18489. var x, y, w, h, rect;
  18490. x = startRect.x;
  18491. y = startRect.y;
  18492. w = startRect.w;
  18493. h = startRect.h;
  18494. x += deltaX * handle.deltaX;
  18495. y += deltaY * handle.deltaY;
  18496. w += deltaX * handle.deltaW;
  18497. h += deltaY * handle.deltaH;
  18498. if (w < 20) {
  18499. w = 20;
  18500. }
  18501. if (h < 20) {
  18502. h = 20;
  18503. }
  18504. rect = currentRect = global$b.clamp({
  18505. x: x,
  18506. y: y,
  18507. w: w,
  18508. h: h
  18509. }, clampRect, handle.name === 'move');
  18510. rect = getRelativeRect(clampRect, rect);
  18511. instance.fire('updateRect', { rect: rect });
  18512. setInnerRect(rect);
  18513. }
  18514. function render() {
  18515. function createDragHelper(handle) {
  18516. var startRect;
  18517. return new DragHelper(id, {
  18518. document: containerElm.ownerDocument,
  18519. handle: id + '-' + handle.name,
  18520. start: function () {
  18521. startRect = currentRect;
  18522. },
  18523. drag: function (e) {
  18524. moveRect(handle, startRect, e.deltaX, e.deltaY);
  18525. }
  18526. });
  18527. }
  18528. global$c('<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">').appendTo(containerElm);
  18529. global$e.each(blockers, function (blocker) {
  18530. global$c('#' + id, containerElm).append('<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">');
  18531. });
  18532. global$e.each(handles, function (handle) {
  18533. global$c('#' + id, containerElm).append('<div id="' + id + '-' + handle.name + '" class="' + prefix + 'croprect-handle ' + prefix + 'croprect-handle-' + handle.name + '"' + 'style="display: none" data-mce-bogus="all" role="gridcell" tabindex="-1"' + ' aria-label="' + handle.label + '" aria-grabbed="false" title="' + handle.label + '">');
  18534. });
  18535. dragHelpers = global$e.map(handles, createDragHelper);
  18536. repaint(currentRect);
  18537. global$c(containerElm).on('focusin focusout', function (e) {
  18538. global$c(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
  18539. });
  18540. global$c(containerElm).on('keydown', function (e) {
  18541. var activeHandle;
  18542. global$e.each(handles, function (handle) {
  18543. if (e.target.id === id + '-' + handle.name) {
  18544. activeHandle = handle;
  18545. return false;
  18546. }
  18547. });
  18548. function moveAndBlock(evt, handle, startRect, deltaX, deltaY) {
  18549. evt.stopPropagation();
  18550. evt.preventDefault();
  18551. moveRect(activeHandle, startRect, deltaX, deltaY);
  18552. }
  18553. switch (e.keyCode) {
  18554. case global$f.LEFT:
  18555. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  18556. break;
  18557. case global$f.RIGHT:
  18558. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  18559. break;
  18560. case global$f.UP:
  18561. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  18562. break;
  18563. case global$f.DOWN:
  18564. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  18565. break;
  18566. case global$f.ENTER:
  18567. case global$f.SPACEBAR:
  18568. e.preventDefault();
  18569. action();
  18570. break;
  18571. }
  18572. });
  18573. }
  18574. function toggleVisibility(state) {
  18575. var selectors = global$e.map(handles, function (handle) {
  18576. return '#' + id + '-' + handle.name;
  18577. }).concat(global$e.map(blockers, function (blocker) {
  18578. return '#' + id + '-' + blocker;
  18579. })).join(',');
  18580. if (state) {
  18581. global$c(selectors, containerElm).show();
  18582. } else {
  18583. global$c(selectors, containerElm).hide();
  18584. }
  18585. }
  18586. function repaint(rect) {
  18587. function updateElementRect(name, rect) {
  18588. if (rect.h < 0) {
  18589. rect.h = 0;
  18590. }
  18591. if (rect.w < 0) {
  18592. rect.w = 0;
  18593. }
  18594. global$c('#' + id + '-' + name, containerElm).css({
  18595. left: rect.x,
  18596. top: rect.y,
  18597. width: rect.w,
  18598. height: rect.h
  18599. });
  18600. }
  18601. global$e.each(handles, function (handle) {
  18602. global$c('#' + id + '-' + handle.name, containerElm).css({
  18603. left: rect.w * handle.xMul + rect.x,
  18604. top: rect.h * handle.yMul + rect.y
  18605. });
  18606. });
  18607. updateElementRect('top', {
  18608. x: viewPortRect.x,
  18609. y: viewPortRect.y,
  18610. w: viewPortRect.w,
  18611. h: rect.y - viewPortRect.y
  18612. });
  18613. updateElementRect('right', {
  18614. x: rect.x + rect.w,
  18615. y: rect.y,
  18616. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  18617. h: rect.h
  18618. });
  18619. updateElementRect('bottom', {
  18620. x: viewPortRect.x,
  18621. y: rect.y + rect.h,
  18622. w: viewPortRect.w,
  18623. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  18624. });
  18625. updateElementRect('left', {
  18626. x: viewPortRect.x,
  18627. y: rect.y,
  18628. w: rect.x - viewPortRect.x,
  18629. h: rect.h
  18630. });
  18631. updateElementRect('move', rect);
  18632. }
  18633. function setRect(rect) {
  18634. currentRect = rect;
  18635. repaint(currentRect);
  18636. }
  18637. function setViewPortRect(rect) {
  18638. viewPortRect = rect;
  18639. repaint(currentRect);
  18640. }
  18641. function setInnerRect(rect) {
  18642. setRect(getAbsoluteRect(clampRect, rect));
  18643. }
  18644. function setClampRect(rect) {
  18645. clampRect = rect;
  18646. repaint(currentRect);
  18647. }
  18648. function destroy() {
  18649. global$e.each(dragHelpers, function (helper) {
  18650. helper.destroy();
  18651. });
  18652. dragHelpers = [];
  18653. }
  18654. render();
  18655. var instance = global$e.extend({
  18656. toggleVisibility: toggleVisibility,
  18657. setClampRect: setClampRect,
  18658. setRect: setRect,
  18659. getInnerRect: getInnerRect,
  18660. setInnerRect: setInnerRect,
  18661. setViewPortRect: setViewPortRect,
  18662. destroy: destroy
  18663. }, global$d);
  18664. return instance;
  18665. };
  18666. var CropRect = { create: create$7 };
  18667. var loadImage = function (image) {
  18668. return new global$4(function (resolve) {
  18669. var loaded = function () {
  18670. image.removeEventListener('load', loaded);
  18671. resolve(image);
  18672. };
  18673. if (image.complete) {
  18674. resolve(image);
  18675. } else {
  18676. image.addEventListener('load', loaded);
  18677. }
  18678. });
  18679. };
  18680. var renderImagePanel = function (initialUrl) {
  18681. var memBg = record({
  18682. dom: {
  18683. tag: 'div',
  18684. classes: ['tox-image-tools__image-bg'],
  18685. attributes: { role: 'presentation' }
  18686. }
  18687. });
  18688. var zoomState = Cell(1);
  18689. var cropRect = Cell(Optional.none());
  18690. var rectState = Cell({
  18691. x: 0,
  18692. y: 0,
  18693. w: 1,
  18694. h: 1
  18695. });
  18696. var viewRectState = Cell({
  18697. x: 0,
  18698. y: 0,
  18699. w: 1,
  18700. h: 1
  18701. });
  18702. var repaintImg = function (anyInSystem, img) {
  18703. memContainer.getOpt(anyInSystem).each(function (panel) {
  18704. var zoom = zoomState.get();
  18705. var panelW = get$7(panel.element);
  18706. var panelH = get$6(panel.element);
  18707. var width = img.dom.naturalWidth * zoom;
  18708. var height = img.dom.naturalHeight * zoom;
  18709. var left = Math.max(0, panelW / 2 - width / 2);
  18710. var top = Math.max(0, panelH / 2 - height / 2);
  18711. var css = {
  18712. left: left.toString() + 'px',
  18713. top: top.toString() + 'px',
  18714. width: width.toString() + 'px',
  18715. height: height.toString() + 'px',
  18716. position: 'absolute'
  18717. };
  18718. setAll$1(img, css);
  18719. memBg.getOpt(panel).each(function (bg) {
  18720. setAll$1(bg.element, css);
  18721. });
  18722. cropRect.get().each(function (cRect) {
  18723. var rect = rectState.get();
  18724. cRect.setRect({
  18725. x: rect.x * zoom + left,
  18726. y: rect.y * zoom + top,
  18727. w: rect.w * zoom,
  18728. h: rect.h * zoom
  18729. });
  18730. cRect.setClampRect({
  18731. x: left,
  18732. y: top,
  18733. w: width,
  18734. h: height
  18735. });
  18736. cRect.setViewPortRect({
  18737. x: 0,
  18738. y: 0,
  18739. w: panelW,
  18740. h: panelH
  18741. });
  18742. });
  18743. });
  18744. };
  18745. var zoomFit = function (anyInSystem, img) {
  18746. memContainer.getOpt(anyInSystem).each(function (panel) {
  18747. var panelW = get$7(panel.element);
  18748. var panelH = get$6(panel.element);
  18749. var width = img.dom.naturalWidth;
  18750. var height = img.dom.naturalHeight;
  18751. var zoom = Math.min(panelW / width, panelH / height);
  18752. if (zoom >= 1) {
  18753. zoomState.set(1);
  18754. } else {
  18755. zoomState.set(zoom);
  18756. }
  18757. });
  18758. };
  18759. var updateSrc = function (anyInSystem, url) {
  18760. var img = SugarElement.fromTag('img');
  18761. set$1(img, 'src', url);
  18762. return loadImage(img.dom).then(function () {
  18763. return memContainer.getOpt(anyInSystem).map(function (panel) {
  18764. var aImg = external({ element: img });
  18765. Replacing.replaceAt(panel, 1, Optional.some(aImg));
  18766. var lastViewRect = viewRectState.get();
  18767. var viewRect = {
  18768. x: 0,
  18769. y: 0,
  18770. w: img.dom.naturalWidth,
  18771. h: img.dom.naturalHeight
  18772. };
  18773. viewRectState.set(viewRect);
  18774. var rect = global$b.inflate(viewRect, -20, -20);
  18775. rectState.set(rect);
  18776. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  18777. zoomFit(panel, img);
  18778. }
  18779. repaintImg(panel, img);
  18780. return img;
  18781. });
  18782. });
  18783. };
  18784. var zoom = function (anyInSystem, direction) {
  18785. var currentZoom = zoomState.get();
  18786. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  18787. zoomState.set(newZoom);
  18788. memContainer.getOpt(anyInSystem).each(function (panel) {
  18789. var img = panel.components()[1].element;
  18790. repaintImg(panel, img);
  18791. });
  18792. };
  18793. var showCrop = function () {
  18794. cropRect.get().each(function (cRect) {
  18795. cRect.toggleVisibility(true);
  18796. });
  18797. };
  18798. var hideCrop = function () {
  18799. cropRect.get().each(function (cRect) {
  18800. cRect.toggleVisibility(false);
  18801. });
  18802. };
  18803. var getRect = function () {
  18804. return rectState.get();
  18805. };
  18806. var container = Container.sketch({
  18807. dom: {
  18808. tag: 'div',
  18809. classes: ['tox-image-tools__image']
  18810. },
  18811. components: [
  18812. memBg.asSpec(),
  18813. {
  18814. dom: {
  18815. tag: 'img',
  18816. attributes: { src: initialUrl }
  18817. }
  18818. },
  18819. {
  18820. dom: { tag: 'div' },
  18821. behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
  18822. memContainer.getOpt(comp).each(function (container) {
  18823. var el = container.element.dom;
  18824. var cRect = CropRect.create({
  18825. x: 10,
  18826. y: 10,
  18827. w: 100,
  18828. h: 100
  18829. }, {
  18830. x: 0,
  18831. y: 0,
  18832. w: 200,
  18833. h: 200
  18834. }, {
  18835. x: 0,
  18836. y: 0,
  18837. w: 200,
  18838. h: 200
  18839. }, el, function () {
  18840. });
  18841. cRect.toggleVisibility(false);
  18842. cRect.on('updateRect', function (e) {
  18843. var rect = e.rect;
  18844. var zoom = zoomState.get();
  18845. var newRect = {
  18846. x: Math.round(rect.x / zoom),
  18847. y: Math.round(rect.y / zoom),
  18848. w: Math.round(rect.w / zoom),
  18849. h: Math.round(rect.h / zoom)
  18850. };
  18851. rectState.set(newRect);
  18852. });
  18853. cropRect.set(Optional.some(cRect));
  18854. });
  18855. })])])
  18856. }
  18857. ],
  18858. containerBehaviours: derive$1([
  18859. Replacing.config({}),
  18860. config('image-panel-events', [runOnAttached(function (comp) {
  18861. updateSrc(comp, initialUrl);
  18862. })])
  18863. ])
  18864. });
  18865. var memContainer = record(container);
  18866. var getMeasurements = function () {
  18867. var viewRect = viewRectState.get();
  18868. return {
  18869. width: viewRect.w,
  18870. height: viewRect.h
  18871. };
  18872. };
  18873. return {
  18874. memContainer: memContainer,
  18875. updateSrc: updateSrc,
  18876. zoom: zoom,
  18877. showCrop: showCrop,
  18878. hideCrop: hideCrop,
  18879. getRect: getRect,
  18880. getMeasurements: getMeasurements
  18881. };
  18882. };
  18883. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  18884. return renderIconButton({
  18885. name: innerHtml,
  18886. icon: Optional.some(icon),
  18887. disabled: disabled,
  18888. tooltip: Optional.some(innerHtml),
  18889. primary: false,
  18890. borderless: false
  18891. }, action, providersBackstage);
  18892. };
  18893. var setButtonEnabled = function (button, enabled) {
  18894. if (enabled) {
  18895. Disabling.enable(button);
  18896. } else {
  18897. Disabling.disable(button);
  18898. }
  18899. };
  18900. var renderSideBar = function (providersBackstage) {
  18901. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  18902. memUndo.getOpt(anyInSystem).each(function (undo) {
  18903. setButtonEnabled(undo, undoEnabled);
  18904. });
  18905. memRedo.getOpt(anyInSystem).each(function (redo) {
  18906. setButtonEnabled(redo, redoEnabled);
  18907. });
  18908. };
  18909. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  18910. emitWith(button, internal.undo(), { direction: 1 });
  18911. }, providersBackstage));
  18912. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  18913. emitWith(button, internal.redo(), { direction: 1 });
  18914. }, providersBackstage));
  18915. var container = Container.sketch({
  18916. dom: {
  18917. tag: 'div',
  18918. classes: [
  18919. 'tox-image-tools__toolbar',
  18920. 'tox-image-tools__sidebar'
  18921. ]
  18922. },
  18923. components: [
  18924. memUndo.asSpec(),
  18925. memRedo.asSpec(),
  18926. createButton('Zoom in', 'zoom-in', false, function (button) {
  18927. emitWith(button, internal.zoom(), { direction: 1 });
  18928. }, providersBackstage),
  18929. createButton('Zoom out', 'zoom-out', false, function (button) {
  18930. emitWith(button, internal.zoom(), { direction: -1 });
  18931. }, providersBackstage)
  18932. ]
  18933. });
  18934. return {
  18935. container: container,
  18936. updateButtonUndoStates: updateButtonUndoStates
  18937. };
  18938. };
  18939. function UndoStack () {
  18940. var data = [];
  18941. var index = -1;
  18942. function add(state) {
  18943. var removed = data.splice(++index);
  18944. data.push(state);
  18945. return {
  18946. state: state,
  18947. removed: removed
  18948. };
  18949. }
  18950. function undo() {
  18951. if (canUndo()) {
  18952. return data[--index];
  18953. }
  18954. }
  18955. function redo() {
  18956. if (canRedo()) {
  18957. return data[++index];
  18958. }
  18959. }
  18960. function canUndo() {
  18961. return index > 0;
  18962. }
  18963. function canRedo() {
  18964. return index !== -1 && index < data.length - 1;
  18965. }
  18966. return {
  18967. data: data,
  18968. add: add,
  18969. undo: undo,
  18970. redo: redo,
  18971. canUndo: canUndo,
  18972. canRedo: canRedo
  18973. };
  18974. }
  18975. var makeState = function (initialState) {
  18976. var blobState = Cell(initialState);
  18977. var tempState = Cell(Optional.none());
  18978. var undoStack = UndoStack();
  18979. undoStack.add(initialState);
  18980. var getBlobState = function () {
  18981. return blobState.get();
  18982. };
  18983. var setBlobState = function (state) {
  18984. blobState.set(state);
  18985. };
  18986. var getTempState = function () {
  18987. return tempState.get().fold(function () {
  18988. return blobState.get();
  18989. }, function (temp) {
  18990. return temp;
  18991. });
  18992. };
  18993. var updateTempState = function (blob) {
  18994. var newTempState = createState(blob);
  18995. destroyTempState();
  18996. tempState.set(Optional.some(newTempState));
  18997. return newTempState.url;
  18998. };
  18999. var createState = function (blob) {
  19000. return {
  19001. blob: blob,
  19002. url: URL.createObjectURL(blob)
  19003. };
  19004. };
  19005. var destroyState = function (state) {
  19006. URL.revokeObjectURL(state.url);
  19007. };
  19008. var destroyStates = function (states) {
  19009. global$e.each(states, destroyState);
  19010. };
  19011. var destroyTempState = function () {
  19012. tempState.get().each(destroyState);
  19013. tempState.set(Optional.none());
  19014. };
  19015. var addBlobState = function (blob) {
  19016. var newState = createState(blob);
  19017. setBlobState(newState);
  19018. var removed = undoStack.add(newState).removed;
  19019. destroyStates(removed);
  19020. return newState.url;
  19021. };
  19022. var addTempState = function (blob) {
  19023. var newState = createState(blob);
  19024. tempState.set(Optional.some(newState));
  19025. return newState.url;
  19026. };
  19027. var applyTempState = function (postApply) {
  19028. return tempState.get().fold(function () {
  19029. }, function (temp) {
  19030. addBlobState(temp.blob);
  19031. postApply();
  19032. });
  19033. };
  19034. var undo = function () {
  19035. var currentState = undoStack.undo();
  19036. setBlobState(currentState);
  19037. return currentState.url;
  19038. };
  19039. var redo = function () {
  19040. var currentState = undoStack.redo();
  19041. setBlobState(currentState);
  19042. return currentState.url;
  19043. };
  19044. var getHistoryStates = function () {
  19045. var undoEnabled = undoStack.canUndo();
  19046. var redoEnabled = undoStack.canRedo();
  19047. return {
  19048. undoEnabled: undoEnabled,
  19049. redoEnabled: redoEnabled
  19050. };
  19051. };
  19052. return {
  19053. getBlobState: getBlobState,
  19054. setBlobState: setBlobState,
  19055. addBlobState: addBlobState,
  19056. getTempState: getTempState,
  19057. updateTempState: updateTempState,
  19058. addTempState: addTempState,
  19059. applyTempState: applyTempState,
  19060. destroyTempState: destroyTempState,
  19061. undo: undo,
  19062. redo: redo,
  19063. getHistoryStates: getHistoryStates
  19064. };
  19065. };
  19066. var renderImageTools = function (detail, providersBackstage) {
  19067. var state = makeState(detail.currentState);
  19068. var zoom = function (anyInSystem, simulatedEvent) {
  19069. var direction = simulatedEvent.event.direction;
  19070. imagePanel.zoom(anyInSystem, direction);
  19071. };
  19072. var updateButtonUndoStates = function (anyInSystem) {
  19073. var historyStates = state.getHistoryStates();
  19074. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  19075. emitWith(anyInSystem, external$2.formActionEvent, {
  19076. name: external$2.saveState(),
  19077. value: historyStates.undoEnabled
  19078. });
  19079. };
  19080. var disableUndoRedo = function (anyInSystem) {
  19081. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  19082. };
  19083. var undo = function (anyInSystem, _simulatedEvent) {
  19084. var url = state.undo();
  19085. updateSrc(anyInSystem, url).then(function (_oImg) {
  19086. unblock(anyInSystem);
  19087. updateButtonUndoStates(anyInSystem);
  19088. });
  19089. };
  19090. var redo = function (anyInSystem, _simulatedEvent) {
  19091. var url = state.redo();
  19092. updateSrc(anyInSystem, url).then(function (_oImg) {
  19093. unblock(anyInSystem);
  19094. updateButtonUndoStates(anyInSystem);
  19095. });
  19096. };
  19097. var imageResultToBlob = function (ir) {
  19098. return ir.toBlob();
  19099. };
  19100. var block = function (anyInSystem) {
  19101. emitWith(anyInSystem, external$2.formActionEvent, {
  19102. name: external$2.disable(),
  19103. value: {}
  19104. });
  19105. };
  19106. var unblock = function (anyInSystem) {
  19107. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  19108. Disabling.enable(applyButton);
  19109. });
  19110. emitWith(anyInSystem, external$2.formActionEvent, {
  19111. name: external$2.enable(),
  19112. value: {}
  19113. });
  19114. };
  19115. var updateSrc = function (anyInSystem, src) {
  19116. block(anyInSystem);
  19117. return imagePanel.updateSrc(anyInSystem, src);
  19118. };
  19119. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  19120. block(anyInSystem);
  19121. return blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  19122. return updateSrc(anyInSystem, url).then(function (oImg) {
  19123. updateButtonUndoStates(anyInSystem);
  19124. swap();
  19125. unblock(anyInSystem);
  19126. return oImg;
  19127. });
  19128. }).catch(function (err) {
  19129. console.log(err);
  19130. unblock(anyInSystem);
  19131. return err;
  19132. });
  19133. };
  19134. var manipulate = function (anyInSystem, filter, swap) {
  19135. var blob = state.getBlobState().blob;
  19136. var action = function (blob) {
  19137. return state.updateTempState(blob);
  19138. };
  19139. blobManipulate(anyInSystem, blob, filter, action, swap);
  19140. };
  19141. var tempManipulate = function (anyInSystem, filter) {
  19142. var blob = state.getTempState().blob;
  19143. var action = function (blob) {
  19144. return state.addTempState(blob);
  19145. };
  19146. blobManipulate(anyInSystem, blob, filter, action, noop);
  19147. };
  19148. var manipulateApply = function (anyInSystem, filter, swap) {
  19149. var blob = state.getBlobState().blob;
  19150. var action = function (blob) {
  19151. var url = state.addBlobState(blob);
  19152. destroyTempState(anyInSystem);
  19153. return url;
  19154. };
  19155. blobManipulate(anyInSystem, blob, filter, action, swap);
  19156. };
  19157. var apply = function (anyInSystem, simulatedEvent) {
  19158. var postApply = function () {
  19159. destroyTempState(anyInSystem);
  19160. var swap = simulatedEvent.event.swap;
  19161. swap();
  19162. };
  19163. state.applyTempState(postApply);
  19164. };
  19165. var destroyTempState = function (anyInSystem) {
  19166. var currentUrl = state.getBlobState().url;
  19167. state.destroyTempState();
  19168. updateButtonUndoStates(anyInSystem);
  19169. return currentUrl;
  19170. };
  19171. var cancel = function (anyInSystem) {
  19172. var currentUrl = destroyTempState(anyInSystem);
  19173. updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
  19174. unblock(anyInSystem);
  19175. });
  19176. };
  19177. var back = function (anyInSystem, simulatedEvent) {
  19178. cancel(anyInSystem);
  19179. var swap = simulatedEvent.event.swap;
  19180. swap();
  19181. imagePanel.hideCrop();
  19182. };
  19183. var transform = function (anyInSystem, simulatedEvent) {
  19184. return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
  19185. };
  19186. var tempTransform = function (anyInSystem, simulatedEvent) {
  19187. return tempManipulate(anyInSystem, simulatedEvent.event.transform);
  19188. };
  19189. var transformApply = function (anyInSystem, simulatedEvent) {
  19190. return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
  19191. };
  19192. var imagePanel = renderImagePanel(detail.currentState.url);
  19193. var sideBar = renderSideBar(providersBackstage);
  19194. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  19195. var swap = function (anyInSystem, simulatedEvent) {
  19196. disableUndoRedo(anyInSystem);
  19197. var transform = simulatedEvent.event.transform;
  19198. var swap = simulatedEvent.event.swap;
  19199. transform.fold(function () {
  19200. swap();
  19201. }, function (transform) {
  19202. manipulate(anyInSystem, transform, swap);
  19203. });
  19204. };
  19205. return {
  19206. dom: {
  19207. tag: 'div',
  19208. attributes: { role: 'presentation' }
  19209. },
  19210. components: [
  19211. editPanel.memContainer.asSpec(),
  19212. imagePanel.memContainer.asSpec(),
  19213. sideBar.container
  19214. ],
  19215. behaviours: derive$1([
  19216. Representing.config({
  19217. store: {
  19218. mode: 'manual',
  19219. getValue: function () {
  19220. return state.getBlobState();
  19221. }
  19222. }
  19223. }),
  19224. config('image-tools-events', [
  19225. run(internal.undo(), undo),
  19226. run(internal.redo(), redo),
  19227. run(internal.zoom(), zoom),
  19228. run(internal.back(), back),
  19229. run(internal.apply(), apply),
  19230. run(internal.transform(), transform),
  19231. run(internal.tempTransform(), tempTransform),
  19232. run(internal.transformApply(), transformApply),
  19233. run(internal.swap(), swap)
  19234. ]),
  19235. ComposingConfigs.self()
  19236. ])
  19237. };
  19238. };
  19239. var renderLabel$2 = function (spec, backstageShared) {
  19240. var label = {
  19241. dom: {
  19242. tag: 'label',
  19243. innerHtml: backstageShared.providers.translate(spec.label),
  19244. classes: ['tox-label']
  19245. }
  19246. };
  19247. var comps = map(spec.items, backstageShared.interpreter);
  19248. return {
  19249. dom: {
  19250. tag: 'div',
  19251. classes: ['tox-form__group']
  19252. },
  19253. components: [label].concat(comps),
  19254. behaviours: derive$1([
  19255. ComposingConfigs.self(),
  19256. Replacing.config({}),
  19257. RepresentingConfigs.domHtml(Optional.none()),
  19258. Keying.config({ mode: 'acyclic' })
  19259. ])
  19260. };
  19261. };
  19262. var isSingleListItem = function (item) {
  19263. return !has(item, 'items');
  19264. };
  19265. var dataAttribute = 'data-value';
  19266. var fetchItems = function (dropdownComp, name, items, selectedValue) {
  19267. return map(items, function (item) {
  19268. if (!isSingleListItem(item)) {
  19269. return {
  19270. type: 'nestedmenuitem',
  19271. text: item.text,
  19272. getSubmenuItems: function () {
  19273. return fetchItems(dropdownComp, name, item.items, selectedValue);
  19274. }
  19275. };
  19276. } else {
  19277. return {
  19278. type: 'togglemenuitem',
  19279. text: item.text,
  19280. value: item.value,
  19281. active: item.value === selectedValue,
  19282. onAction: function () {
  19283. Representing.setValue(dropdownComp, item.value);
  19284. emitWith(dropdownComp, formChangeEvent, { name: name });
  19285. Focusing.focus(dropdownComp);
  19286. }
  19287. };
  19288. }
  19289. });
  19290. };
  19291. var findItemByValue = function (items, value) {
  19292. return findMap(items, function (item) {
  19293. if (!isSingleListItem(item)) {
  19294. return findItemByValue(item.items, value);
  19295. } else {
  19296. return someIf(item.value === value, item);
  19297. }
  19298. });
  19299. };
  19300. var renderListBox = function (spec, backstage) {
  19301. var providersBackstage = backstage.shared.providers;
  19302. var initialItem = head(spec.items).filter(isSingleListItem);
  19303. var pLabel = spec.label.map(function (label) {
  19304. return renderLabel(label, providersBackstage);
  19305. });
  19306. var pField = FormField.parts.field({
  19307. dom: {},
  19308. factory: {
  19309. sketch: function (sketchSpec) {
  19310. return renderCommonDropdown({
  19311. uid: sketchSpec.uid,
  19312. text: initialItem.map(function (item) {
  19313. return item.text;
  19314. }),
  19315. icon: Optional.none(),
  19316. tooltip: spec.label,
  19317. role: Optional.none(),
  19318. fetch: function (comp, callback) {
  19319. var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
  19320. callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  19321. },
  19322. onSetup: constant(noop),
  19323. getApi: constant({}),
  19324. columns: 1,
  19325. presets: 'normal',
  19326. classes: [],
  19327. dropdownBehaviours: [
  19328. Tabstopping.config({}),
  19329. Representing.config({
  19330. store: {
  19331. mode: 'manual',
  19332. initialValue: initialItem.map(function (item) {
  19333. return item.value;
  19334. }).getOr(''),
  19335. getValue: function (comp) {
  19336. return get$2(comp.element, dataAttribute);
  19337. },
  19338. setValue: function (comp, data) {
  19339. findItemByValue(spec.items, data).each(function (item) {
  19340. set$1(comp.element, dataAttribute, item.value);
  19341. emitWith(comp, updateMenuText, { text: item.text });
  19342. });
  19343. }
  19344. }
  19345. })
  19346. ]
  19347. }, 'tox-listbox', backstage.shared);
  19348. }
  19349. }
  19350. });
  19351. var listBoxWrap = {
  19352. dom: {
  19353. tag: 'div',
  19354. classes: ['tox-listboxfield']
  19355. },
  19356. components: [pField]
  19357. };
  19358. return FormField.sketch({
  19359. dom: {
  19360. tag: 'div',
  19361. classes: ['tox-form__group']
  19362. },
  19363. components: flatten([
  19364. pLabel.toArray(),
  19365. [listBoxWrap]
  19366. ]),
  19367. fieldBehaviours: derive$1([Disabling.config({
  19368. disabled: constant(spec.disabled),
  19369. onDisabled: function (comp) {
  19370. FormField.getField(comp).each(Disabling.disable);
  19371. },
  19372. onEnabled: function (comp) {
  19373. FormField.getField(comp).each(Disabling.enable);
  19374. }
  19375. })])
  19376. });
  19377. };
  19378. var renderPanel = function (spec, backstage) {
  19379. return {
  19380. dom: {
  19381. tag: 'div',
  19382. classes: spec.classes
  19383. },
  19384. components: map(spec.items, backstage.shared.interpreter)
  19385. };
  19386. };
  19387. var factory$8 = function (detail, _spec) {
  19388. var options = map(detail.options, function (option) {
  19389. return {
  19390. dom: {
  19391. tag: 'option',
  19392. value: option.value,
  19393. innerHtml: option.text
  19394. }
  19395. };
  19396. });
  19397. var initialValues = detail.data.map(function (v) {
  19398. return wrap$1('initialValue', v);
  19399. }).getOr({});
  19400. return {
  19401. uid: detail.uid,
  19402. dom: {
  19403. tag: 'select',
  19404. classes: detail.selectClasses,
  19405. attributes: detail.selectAttributes
  19406. },
  19407. components: options,
  19408. behaviours: augment(detail.selectBehaviours, [
  19409. Focusing.config({}),
  19410. Representing.config({
  19411. store: __assign({
  19412. mode: 'manual',
  19413. getValue: function (select) {
  19414. return get$5(select.element);
  19415. },
  19416. setValue: function (select, newValue) {
  19417. var found = find(detail.options, function (opt) {
  19418. return opt.value === newValue;
  19419. });
  19420. if (found.isSome()) {
  19421. set$3(select.element, newValue);
  19422. }
  19423. }
  19424. }, initialValues)
  19425. })
  19426. ])
  19427. };
  19428. };
  19429. var HtmlSelect = single$2({
  19430. name: 'HtmlSelect',
  19431. configFields: [
  19432. strict$1('options'),
  19433. field$1('selectBehaviours', [
  19434. Focusing,
  19435. Representing
  19436. ]),
  19437. defaulted$1('selectClasses', []),
  19438. defaulted$1('selectAttributes', {}),
  19439. option('data')
  19440. ],
  19441. factory: factory$8
  19442. });
  19443. var renderSelectBox = function (spec, providersBackstage) {
  19444. var translatedOptions = map(spec.items, function (item) {
  19445. return {
  19446. text: providersBackstage.translate(item.text),
  19447. value: item.value
  19448. };
  19449. });
  19450. var pLabel = spec.label.map(function (label) {
  19451. return renderLabel(label, providersBackstage);
  19452. });
  19453. var pField = FormField.parts.field({
  19454. dom: {},
  19455. selectAttributes: { size: spec.size },
  19456. options: translatedOptions,
  19457. factory: HtmlSelect,
  19458. selectBehaviours: derive$1([
  19459. Disabling.config({
  19460. disabled: function () {
  19461. return spec.disabled || providersBackstage.isReadOnly();
  19462. }
  19463. }),
  19464. Tabstopping.config({}),
  19465. config('selectbox-change', [run(change(), function (component, _) {
  19466. emitWith(component, formChangeEvent, { name: spec.name });
  19467. })])
  19468. ])
  19469. });
  19470. var chevron = spec.size > 1 ? Optional.none() : Optional.some({
  19471. dom: {
  19472. tag: 'div',
  19473. classes: ['tox-selectfield__icon-js'],
  19474. innerHtml: get$d('chevron-down', providersBackstage.icons)
  19475. }
  19476. });
  19477. var selectWrap = {
  19478. dom: {
  19479. tag: 'div',
  19480. classes: ['tox-selectfield']
  19481. },
  19482. components: flatten([
  19483. [pField],
  19484. chevron.toArray()
  19485. ])
  19486. };
  19487. return FormField.sketch({
  19488. dom: {
  19489. tag: 'div',
  19490. classes: ['tox-form__group']
  19491. },
  19492. components: flatten([
  19493. pLabel.toArray(),
  19494. [selectWrap]
  19495. ]),
  19496. fieldBehaviours: derive$1([
  19497. Disabling.config({
  19498. disabled: function () {
  19499. return spec.disabled || providersBackstage.isReadOnly();
  19500. },
  19501. onDisabled: function (comp) {
  19502. FormField.getField(comp).each(Disabling.disable);
  19503. },
  19504. onEnabled: function (comp) {
  19505. FormField.getField(comp).each(Disabling.enable);
  19506. }
  19507. }),
  19508. receivingConfig()
  19509. ])
  19510. });
  19511. };
  19512. var renderTable = function (spec, providersBackstage) {
  19513. var renderTh = function (text) {
  19514. return {
  19515. dom: {
  19516. tag: 'th',
  19517. innerHtml: providersBackstage.translate(text)
  19518. }
  19519. };
  19520. };
  19521. var renderHeader = function (header) {
  19522. return {
  19523. dom: { tag: 'thead' },
  19524. components: [{
  19525. dom: { tag: 'tr' },
  19526. components: map(header, renderTh)
  19527. }]
  19528. };
  19529. };
  19530. var renderTd = function (text) {
  19531. return {
  19532. dom: {
  19533. tag: 'td',
  19534. innerHtml: providersBackstage.translate(text)
  19535. }
  19536. };
  19537. };
  19538. var renderTr = function (row) {
  19539. return {
  19540. dom: { tag: 'tr' },
  19541. components: map(row, renderTd)
  19542. };
  19543. };
  19544. var renderRows = function (rows) {
  19545. return {
  19546. dom: { tag: 'tbody' },
  19547. components: map(rows, renderTr)
  19548. };
  19549. };
  19550. return {
  19551. dom: {
  19552. tag: 'table',
  19553. classes: ['tox-dialog__table']
  19554. },
  19555. components: [
  19556. renderHeader(spec.header),
  19557. renderRows(spec.cells)
  19558. ],
  19559. behaviours: derive$1([
  19560. Tabstopping.config({}),
  19561. Focusing.config({})
  19562. ])
  19563. };
  19564. };
  19565. var renderTextField = function (spec, providersBackstage) {
  19566. var pLabel = spec.label.map(function (label) {
  19567. return renderLabel(label, providersBackstage);
  19568. });
  19569. var baseInputBehaviours = [
  19570. Disabling.config({
  19571. disabled: function () {
  19572. return spec.disabled || providersBackstage.isReadOnly();
  19573. }
  19574. }),
  19575. receivingConfig(),
  19576. Keying.config({
  19577. mode: 'execution',
  19578. useEnter: spec.multiline !== true,
  19579. useControlEnter: spec.multiline === true,
  19580. execute: function (comp) {
  19581. emit(comp, formSubmitEvent);
  19582. return Optional.some(true);
  19583. }
  19584. }),
  19585. config('textfield-change', [
  19586. run(input(), function (component, _) {
  19587. emitWith(component, formChangeEvent, { name: spec.name });
  19588. }),
  19589. run(postPaste(), function (component, _) {
  19590. emitWith(component, formChangeEvent, { name: spec.name });
  19591. })
  19592. ]),
  19593. Tabstopping.config({})
  19594. ];
  19595. var validatingBehaviours = spec.validation.map(function (vl) {
  19596. return Invalidating.config({
  19597. getRoot: function (input) {
  19598. return parent(input.element);
  19599. },
  19600. invalidClass: 'tox-invalid',
  19601. validator: {
  19602. validate: function (input) {
  19603. var v = Representing.getValue(input);
  19604. var result = vl.validator(v);
  19605. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  19606. },
  19607. validateOnLoad: vl.validateOnLoad
  19608. }
  19609. });
  19610. }).toArray();
  19611. var placeholder = spec.placeholder.fold(constant({}), function (p) {
  19612. return { placeholder: providersBackstage.translate(p) };
  19613. });
  19614. var inputMode = spec.inputMode.fold(constant({}), function (mode) {
  19615. return { inputmode: mode };
  19616. });
  19617. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  19618. var pField = FormField.parts.field({
  19619. tag: spec.multiline === true ? 'textarea' : 'input',
  19620. inputAttributes: inputAttributes,
  19621. inputClasses: [spec.classname],
  19622. inputBehaviours: derive$1(flatten([
  19623. baseInputBehaviours,
  19624. validatingBehaviours
  19625. ])),
  19626. selectOnFocus: false,
  19627. factory: Input
  19628. });
  19629. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  19630. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  19631. var extraBehaviours = [
  19632. Disabling.config({
  19633. disabled: function () {
  19634. return spec.disabled || providersBackstage.isReadOnly();
  19635. },
  19636. onDisabled: function (comp) {
  19637. FormField.getField(comp).each(Disabling.disable);
  19638. },
  19639. onEnabled: function (comp) {
  19640. FormField.getField(comp).each(Disabling.enable);
  19641. }
  19642. }),
  19643. receivingConfig()
  19644. ];
  19645. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  19646. };
  19647. var renderInput = function (spec, providersBackstage) {
  19648. return renderTextField({
  19649. name: spec.name,
  19650. multiline: false,
  19651. label: spec.label,
  19652. inputMode: spec.inputMode,
  19653. placeholder: spec.placeholder,
  19654. flex: false,
  19655. disabled: spec.disabled,
  19656. classname: 'tox-textfield',
  19657. validation: Optional.none(),
  19658. maximized: spec.maximized
  19659. }, providersBackstage);
  19660. };
  19661. var renderTextarea = function (spec, providersBackstage) {
  19662. return renderTextField({
  19663. name: spec.name,
  19664. multiline: true,
  19665. label: spec.label,
  19666. inputMode: Optional.none(),
  19667. placeholder: spec.placeholder,
  19668. flex: true,
  19669. disabled: spec.disabled,
  19670. classname: 'tox-textarea',
  19671. validation: Optional.none(),
  19672. maximized: spec.maximized
  19673. }, providersBackstage);
  19674. };
  19675. var events$c = function (streamConfig, streamState) {
  19676. var streams = streamConfig.stream.streams;
  19677. var processor = streams.setup(streamConfig, streamState);
  19678. return derive([
  19679. run(streamConfig.event, processor),
  19680. runOnDetached(function () {
  19681. return streamState.cancel();
  19682. })
  19683. ].concat(streamConfig.cancelEvent.map(function (e) {
  19684. return [run(e, function () {
  19685. return streamState.cancel();
  19686. })];
  19687. }).getOr([])));
  19688. };
  19689. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  19690. __proto__: null,
  19691. events: events$c
  19692. });
  19693. var throttle = function (_config) {
  19694. var state = Cell(null);
  19695. var readState = function () {
  19696. return { timer: state.get() !== null ? 'set' : 'unset' };
  19697. };
  19698. var setTimer = function (t) {
  19699. state.set(t);
  19700. };
  19701. var cancel = function () {
  19702. var t = state.get();
  19703. if (t !== null) {
  19704. t.cancel();
  19705. }
  19706. };
  19707. return nu$5({
  19708. readState: readState,
  19709. setTimer: setTimer,
  19710. cancel: cancel
  19711. });
  19712. };
  19713. var init$6 = function (spec) {
  19714. return spec.stream.streams.state(spec);
  19715. };
  19716. var StreamingState = /*#__PURE__*/Object.freeze({
  19717. __proto__: null,
  19718. throttle: throttle,
  19719. init: init$6
  19720. });
  19721. var setup$2 = function (streamInfo, streamState) {
  19722. var sInfo = streamInfo.stream;
  19723. var throttler = last$2(streamInfo.onStream, sInfo.delay);
  19724. streamState.setTimer(throttler);
  19725. return function (component, simulatedEvent) {
  19726. throttler.throttle(component, simulatedEvent);
  19727. if (sInfo.stopEvent) {
  19728. simulatedEvent.stop();
  19729. }
  19730. };
  19731. };
  19732. var StreamingSchema = [
  19733. strictOf('stream', choose$1('mode', {
  19734. throttle: [
  19735. strict$1('delay'),
  19736. defaulted$1('stopEvent', true),
  19737. output('streams', {
  19738. setup: setup$2,
  19739. state: throttle
  19740. })
  19741. ]
  19742. })),
  19743. defaulted$1('event', 'input'),
  19744. option('cancelEvent'),
  19745. onStrictHandler('onStream')
  19746. ];
  19747. var Streaming = create$1({
  19748. fields: StreamingSchema,
  19749. name: 'streaming',
  19750. active: ActiveStreaming,
  19751. state: StreamingState
  19752. });
  19753. var setValueFromItem = function (model, input, item) {
  19754. var itemData = Representing.getValue(item);
  19755. Representing.setValue(input, itemData);
  19756. setCursorAtEnd(input);
  19757. };
  19758. var setSelectionOn = function (input, f) {
  19759. var el = input.element;
  19760. var value = get$5(el);
  19761. var node = el.dom;
  19762. if (get$2(el, 'type') !== 'number') {
  19763. f(node, value);
  19764. }
  19765. };
  19766. var setCursorAtEnd = function (input) {
  19767. setSelectionOn(input, function (node, value) {
  19768. return node.setSelectionRange(value.length, value.length);
  19769. });
  19770. };
  19771. var setSelectionToEnd = function (input, startOffset) {
  19772. setSelectionOn(input, function (node, value) {
  19773. return node.setSelectionRange(startOffset, value.length);
  19774. });
  19775. };
  19776. var attemptSelectOver = function (model, input, item) {
  19777. if (!model.selectsOver) {
  19778. return Optional.none();
  19779. } else {
  19780. var currentValue = Representing.getValue(input);
  19781. var inputDisplay_1 = model.getDisplayText(currentValue);
  19782. var itemValue = Representing.getValue(item);
  19783. var itemDisplay = model.getDisplayText(itemValue);
  19784. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () {
  19785. setValueFromItem(model, input, item);
  19786. setSelectionToEnd(input, inputDisplay_1.length);
  19787. }) : Optional.none();
  19788. }
  19789. };
  19790. var itemExecute = constant('alloy.typeahead.itemexecute');
  19791. var make$5 = function (detail, components, spec, externals) {
  19792. var navigateList = function (comp, simulatedEvent, highlighter) {
  19793. detail.previewing.set(false);
  19794. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19795. if (Sandboxing.isOpen(sandbox)) {
  19796. Composing.getCurrent(sandbox).each(function (menu) {
  19797. Highlighting.getHighlighted(menu).fold(function () {
  19798. highlighter(menu);
  19799. }, function () {
  19800. dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
  19801. });
  19802. });
  19803. } else {
  19804. var onOpenSync = function (sandbox) {
  19805. Composing.getCurrent(sandbox).each(highlighter);
  19806. };
  19807. open$1(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19808. }
  19809. };
  19810. var focusBehaviours$1 = focusBehaviours(detail);
  19811. var mapFetch = function (comp) {
  19812. return function (tdata) {
  19813. return tdata.map(function (data) {
  19814. var menus = values(data.menus);
  19815. var items = bind(menus, function (menu) {
  19816. return filter(menu.items, function (item) {
  19817. return item.type === 'item';
  19818. });
  19819. });
  19820. var repState = Representing.getState(comp);
  19821. repState.update(map(items, function (item) {
  19822. return item.data;
  19823. }));
  19824. return data;
  19825. });
  19826. };
  19827. };
  19828. var behaviours = [
  19829. Focusing.config({}),
  19830. Representing.config({
  19831. onSetValue: detail.onSetValue,
  19832. store: __assign({
  19833. mode: 'dataset',
  19834. getDataKey: function (comp) {
  19835. return get$5(comp.element);
  19836. },
  19837. getFallbackEntry: function (itemString) {
  19838. return {
  19839. value: itemString,
  19840. meta: {}
  19841. };
  19842. },
  19843. setValue: function (comp, data) {
  19844. set$3(comp.element, detail.model.getDisplayText(data));
  19845. }
  19846. }, detail.initialData.map(function (d) {
  19847. return wrap$1('initialValue', d);
  19848. }).getOr({}))
  19849. }),
  19850. Streaming.config({
  19851. stream: {
  19852. mode: 'throttle',
  19853. delay: detail.responseTime,
  19854. stopEvent: false
  19855. },
  19856. onStream: function (component, _simulatedEvent) {
  19857. var sandbox = Coupling.getCoupled(component, 'sandbox');
  19858. var focusInInput = Focusing.isFocused(component);
  19859. if (focusInInput) {
  19860. if (get$5(component.element).length >= detail.minChars) {
  19861. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  19862. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  19863. });
  19864. detail.previewing.set(true);
  19865. var onOpenSync = function (_sandbox) {
  19866. Composing.getCurrent(sandbox).each(function (menu) {
  19867. previousValue_1.fold(function () {
  19868. if (detail.model.selectsOver) {
  19869. Highlighting.highlightFirst(menu);
  19870. }
  19871. }, function (pv) {
  19872. Highlighting.highlightBy(menu, function (item) {
  19873. var itemData = Representing.getValue(item);
  19874. return itemData.value === pv.value;
  19875. });
  19876. Highlighting.getHighlighted(menu).orThunk(function () {
  19877. Highlighting.highlightFirst(menu);
  19878. return Optional.none();
  19879. });
  19880. });
  19881. });
  19882. };
  19883. open$1(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19884. }
  19885. }
  19886. },
  19887. cancelEvent: typeaheadCancel()
  19888. }),
  19889. Keying.config({
  19890. mode: 'special',
  19891. onDown: function (comp, simulatedEvent) {
  19892. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  19893. return Optional.some(true);
  19894. },
  19895. onEscape: function (comp) {
  19896. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19897. if (Sandboxing.isOpen(sandbox)) {
  19898. Sandboxing.close(sandbox);
  19899. return Optional.some(true);
  19900. }
  19901. return Optional.none();
  19902. },
  19903. onUp: function (comp, simulatedEvent) {
  19904. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  19905. return Optional.some(true);
  19906. },
  19907. onEnter: function (comp) {
  19908. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19909. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  19910. if (sandboxIsOpen && !detail.previewing.get()) {
  19911. return Composing.getCurrent(sandbox).bind(function (menu) {
  19912. return Highlighting.getHighlighted(menu);
  19913. }).map(function (item) {
  19914. emitWith(comp, itemExecute(), { item: item });
  19915. return true;
  19916. });
  19917. } else {
  19918. var currentValue = Representing.getValue(comp);
  19919. emit(comp, typeaheadCancel());
  19920. detail.onExecute(sandbox, comp, currentValue);
  19921. if (sandboxIsOpen) {
  19922. Sandboxing.close(sandbox);
  19923. }
  19924. return Optional.some(true);
  19925. }
  19926. }
  19927. }),
  19928. Toggling.config({
  19929. toggleClass: detail.markers.openClass,
  19930. aria: { mode: 'expanded' }
  19931. }),
  19932. Coupling.config({
  19933. others: {
  19934. sandbox: function (hotspot) {
  19935. return makeSandbox(detail, hotspot, {
  19936. onOpen: function () {
  19937. return Toggling.on(hotspot);
  19938. },
  19939. onClose: function () {
  19940. return Toggling.off(hotspot);
  19941. }
  19942. });
  19943. }
  19944. }
  19945. }),
  19946. config('typeaheadevents', [
  19947. runOnExecute(function (comp) {
  19948. var onOpenSync = noop;
  19949. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19950. }),
  19951. run(itemExecute(), function (comp, se) {
  19952. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19953. setValueFromItem(detail.model, comp, se.event.item);
  19954. emit(comp, typeaheadCancel());
  19955. detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
  19956. Sandboxing.close(sandbox);
  19957. setCursorAtEnd(comp);
  19958. })
  19959. ].concat(detail.dismissOnBlur ? [run(postBlur(), function (typeahead) {
  19960. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  19961. if (search(sandbox.element).isNone()) {
  19962. Sandboxing.close(sandbox);
  19963. }
  19964. })] : []))
  19965. ];
  19966. return {
  19967. uid: detail.uid,
  19968. dom: dom$2(deepMerge(detail, {
  19969. inputAttributes: {
  19970. 'role': 'combobox',
  19971. 'aria-autocomplete': 'list',
  19972. 'aria-haspopup': 'true'
  19973. }
  19974. })),
  19975. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  19976. eventOrder: detail.eventOrder
  19977. };
  19978. };
  19979. var schema$j = constant([
  19980. option('lazySink'),
  19981. strict$1('fetch'),
  19982. defaulted$1('minChars', 5),
  19983. defaulted$1('responseTime', 1000),
  19984. onHandler('onOpen'),
  19985. defaulted$1('getHotspot', Optional.some),
  19986. defaulted$1('getAnchorOverrides', constant({})),
  19987. defaulted$1('layouts', Optional.none()),
  19988. defaulted$1('eventOrder', {}),
  19989. defaultedObjOf('model', {}, [
  19990. defaulted$1('getDisplayText', function (itemData) {
  19991. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  19992. }),
  19993. defaulted$1('selectsOver', true),
  19994. defaulted$1('populateFromBrowse', true)
  19995. ]),
  19996. onHandler('onSetValue'),
  19997. onKeyboardHandler('onExecute'),
  19998. onHandler('onItemExecute'),
  19999. defaulted$1('inputClasses', []),
  20000. defaulted$1('inputAttributes', {}),
  20001. defaulted$1('inputStyles', {}),
  20002. defaulted$1('matchWidth', true),
  20003. defaulted$1('useMinWidth', false),
  20004. defaulted$1('dismissOnBlur', true),
  20005. markers(['openClass']),
  20006. option('initialData'),
  20007. field$1('typeaheadBehaviours', [
  20008. Focusing,
  20009. Representing,
  20010. Streaming,
  20011. Keying,
  20012. Toggling,
  20013. Coupling
  20014. ]),
  20015. state$1('previewing', function () {
  20016. return Cell(true);
  20017. })
  20018. ].concat(schema$f()).concat(sandboxFields()));
  20019. var parts$6 = constant([external$1({
  20020. schema: [tieredMenuMarkers()],
  20021. name: 'menu',
  20022. overrides: function (detail) {
  20023. return {
  20024. fakeFocus: true,
  20025. onHighlight: function (menu, item) {
  20026. if (!detail.previewing.get()) {
  20027. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20028. if (detail.model.populateFromBrowse) {
  20029. setValueFromItem(detail.model, input, item);
  20030. }
  20031. });
  20032. } else {
  20033. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20034. attemptSelectOver(detail.model, input, item).fold(function () {
  20035. return Highlighting.dehighlight(menu, item);
  20036. }, function (fn) {
  20037. return fn();
  20038. });
  20039. });
  20040. }
  20041. detail.previewing.set(false);
  20042. },
  20043. onExecute: function (menu, item) {
  20044. return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) {
  20045. emitWith(typeahead, itemExecute(), { item: item });
  20046. return true;
  20047. });
  20048. },
  20049. onHover: function (menu, item) {
  20050. detail.previewing.set(false);
  20051. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20052. if (detail.model.populateFromBrowse) {
  20053. setValueFromItem(detail.model, input, item);
  20054. }
  20055. });
  20056. }
  20057. };
  20058. }
  20059. })]);
  20060. var Typeahead = composite$1({
  20061. name: 'Typeahead',
  20062. configFields: schema$j(),
  20063. partFields: parts$6(),
  20064. factory: make$5
  20065. });
  20066. var wrap$2 = function (delegate) {
  20067. var toCached = function () {
  20068. return wrap$2(delegate.toCached());
  20069. };
  20070. var bindFuture = function (f) {
  20071. return wrap$2(delegate.bind(function (resA) {
  20072. return resA.fold(function (err) {
  20073. return Future.pure(Result.error(err));
  20074. }, function (a) {
  20075. return f(a);
  20076. });
  20077. }));
  20078. };
  20079. var bindResult = function (f) {
  20080. return wrap$2(delegate.map(function (resA) {
  20081. return resA.bind(f);
  20082. }));
  20083. };
  20084. var mapResult = function (f) {
  20085. return wrap$2(delegate.map(function (resA) {
  20086. return resA.map(f);
  20087. }));
  20088. };
  20089. var mapError = function (f) {
  20090. return wrap$2(delegate.map(function (resA) {
  20091. return resA.mapError(f);
  20092. }));
  20093. };
  20094. var foldResult = function (whenError, whenValue) {
  20095. return delegate.map(function (res) {
  20096. return res.fold(whenError, whenValue);
  20097. });
  20098. };
  20099. var withTimeout = function (timeout, errorThunk) {
  20100. return wrap$2(Future.nu(function (callback) {
  20101. var timedOut = false;
  20102. var timer = setTimeout(function () {
  20103. timedOut = true;
  20104. callback(Result.error(errorThunk()));
  20105. }, timeout);
  20106. delegate.get(function (result) {
  20107. if (!timedOut) {
  20108. clearTimeout(timer);
  20109. callback(result);
  20110. }
  20111. });
  20112. }));
  20113. };
  20114. return __assign(__assign({}, delegate), {
  20115. toCached: toCached,
  20116. bindFuture: bindFuture,
  20117. bindResult: bindResult,
  20118. mapResult: mapResult,
  20119. mapError: mapError,
  20120. foldResult: foldResult,
  20121. withTimeout: withTimeout
  20122. });
  20123. };
  20124. var nu$c = function (worker) {
  20125. return wrap$2(Future.nu(worker));
  20126. };
  20127. var value$2 = function (value) {
  20128. return wrap$2(Future.pure(Result.value(value)));
  20129. };
  20130. var error$1 = function (error) {
  20131. return wrap$2(Future.pure(Result.error(error)));
  20132. };
  20133. var fromResult$1 = function (result) {
  20134. return wrap$2(Future.pure(result));
  20135. };
  20136. var fromFuture = function (future) {
  20137. return wrap$2(future.map(Result.value));
  20138. };
  20139. var fromPromise = function (promise) {
  20140. return nu$c(function (completer) {
  20141. promise.then(function (value) {
  20142. completer(Result.value(value));
  20143. }, function (error) {
  20144. completer(Result.error(error));
  20145. });
  20146. });
  20147. };
  20148. var FutureResult = {
  20149. nu: nu$c,
  20150. wrap: wrap$2,
  20151. pure: value$2,
  20152. value: value$2,
  20153. error: error$1,
  20154. fromResult: fromResult$1,
  20155. fromFuture: fromFuture,
  20156. fromPromise: fromPromise
  20157. };
  20158. var separator$2 = { type: 'separator' };
  20159. var toMenuItem = function (target) {
  20160. return {
  20161. type: 'menuitem',
  20162. value: target.url,
  20163. text: target.title,
  20164. meta: { attach: target.attach },
  20165. onAction: function () {
  20166. }
  20167. };
  20168. };
  20169. var staticMenuItem = function (title, url) {
  20170. return {
  20171. type: 'menuitem',
  20172. value: url,
  20173. text: title,
  20174. meta: { attach: undefined },
  20175. onAction: function () {
  20176. }
  20177. };
  20178. };
  20179. var toMenuItems = function (targets) {
  20180. return map(targets, toMenuItem);
  20181. };
  20182. var filterLinkTargets = function (type, targets) {
  20183. return filter(targets, function (target) {
  20184. return target.type === type;
  20185. });
  20186. };
  20187. var filteredTargets = function (type, targets) {
  20188. return toMenuItems(filterLinkTargets(type, targets));
  20189. };
  20190. var headerTargets = function (linkInfo) {
  20191. return filteredTargets('header', linkInfo.targets);
  20192. };
  20193. var anchorTargets = function (linkInfo) {
  20194. return filteredTargets('anchor', linkInfo.targets);
  20195. };
  20196. var anchorTargetTop = function (linkInfo) {
  20197. return Optional.from(linkInfo.anchorTop).map(function (url) {
  20198. return staticMenuItem('<top>', url);
  20199. }).toArray();
  20200. };
  20201. var anchorTargetBottom = function (linkInfo) {
  20202. return Optional.from(linkInfo.anchorBottom).map(function (url) {
  20203. return staticMenuItem('<bottom>', url);
  20204. }).toArray();
  20205. };
  20206. var historyTargets = function (history) {
  20207. return map(history, function (url) {
  20208. return staticMenuItem(url, url);
  20209. });
  20210. };
  20211. var joinMenuLists = function (items) {
  20212. return foldl(items, function (a, b) {
  20213. var bothEmpty = a.length === 0 || b.length === 0;
  20214. return bothEmpty ? a.concat(b) : a.concat(separator$2, b);
  20215. }, []);
  20216. };
  20217. var filterByQuery = function (term, menuItems) {
  20218. var lowerCaseTerm = term.toLowerCase();
  20219. return filter(menuItems, function (item) {
  20220. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  20221. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  20222. });
  20223. };
  20224. var getItems = function (fileType, input, urlBackstage) {
  20225. var urlInputValue = Representing.getValue(input);
  20226. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  20227. var info = urlBackstage.getLinkInformation();
  20228. return info.fold(function () {
  20229. return [];
  20230. }, function (linkInfo) {
  20231. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  20232. return fileType === 'file' ? joinMenuLists([
  20233. history,
  20234. filterByQuery(term, headerTargets(linkInfo)),
  20235. filterByQuery(term, flatten([
  20236. anchorTargetTop(linkInfo),
  20237. anchorTargets(linkInfo),
  20238. anchorTargetBottom(linkInfo)
  20239. ]))
  20240. ]) : history;
  20241. });
  20242. };
  20243. var errorId = generate$1('aria-invalid');
  20244. var renderUrlInput = function (spec, backstage, urlBackstage) {
  20245. var _a;
  20246. var providersBackstage = backstage.shared.providers;
  20247. var updateHistory = function (component) {
  20248. var urlEntry = Representing.getValue(component);
  20249. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  20250. };
  20251. var pField = FormField.parts.field({
  20252. factory: Typeahead,
  20253. dismissOnBlur: true,
  20254. inputClasses: ['tox-textfield'],
  20255. sandboxClasses: ['tox-dialog__popups'],
  20256. inputAttributes: {
  20257. 'aria-errormessage': errorId,
  20258. 'type': 'url'
  20259. },
  20260. minChars: 0,
  20261. responseTime: 0,
  20262. fetch: function (input) {
  20263. var items = getItems(spec.filetype, input, urlBackstage);
  20264. var tdata = build$2(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  20265. return Future.pure(tdata);
  20266. },
  20267. getHotspot: function (comp) {
  20268. return memUrlBox.getOpt(comp);
  20269. },
  20270. onSetValue: function (comp, _newValue) {
  20271. if (comp.hasConfigured(Invalidating)) {
  20272. Invalidating.run(comp).get(noop);
  20273. }
  20274. },
  20275. typeaheadBehaviours: derive$1(flatten([
  20276. urlBackstage.getValidationHandler().map(function (handler) {
  20277. return Invalidating.config({
  20278. getRoot: function (comp) {
  20279. return parent(comp.element);
  20280. },
  20281. invalidClass: 'tox-control-wrap--status-invalid',
  20282. notify: {
  20283. onInvalid: function (comp, err) {
  20284. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  20285. set$1(invalidComp.element, 'title', providersBackstage.translate(err));
  20286. });
  20287. }
  20288. },
  20289. validator: {
  20290. validate: function (input) {
  20291. var urlEntry = Representing.getValue(input);
  20292. return FutureResult.nu(function (completer) {
  20293. handler({
  20294. type: spec.filetype,
  20295. url: urlEntry.value
  20296. }, function (validation) {
  20297. if (validation.status === 'invalid') {
  20298. var err = Result.error(validation.message);
  20299. completer(err);
  20300. } else {
  20301. var val = Result.value(validation.message);
  20302. completer(val);
  20303. }
  20304. });
  20305. });
  20306. },
  20307. validateOnLoad: false
  20308. }
  20309. });
  20310. }).toArray(),
  20311. [
  20312. Disabling.config({
  20313. disabled: function () {
  20314. return spec.disabled || providersBackstage.isReadOnly();
  20315. }
  20316. }),
  20317. Tabstopping.config({}),
  20318. config('urlinput-events', flatten([
  20319. spec.filetype === 'file' ? [run(input(), function (comp) {
  20320. emitWith(comp, formChangeEvent, { name: spec.name });
  20321. })] : [],
  20322. [
  20323. run(change(), function (comp) {
  20324. emitWith(comp, formChangeEvent, { name: spec.name });
  20325. updateHistory(comp);
  20326. }),
  20327. run(postPaste(), function (comp) {
  20328. emitWith(comp, formChangeEvent, { name: spec.name });
  20329. updateHistory(comp);
  20330. })
  20331. ]
  20332. ]))
  20333. ]
  20334. ])),
  20335. eventOrder: (_a = {}, _a[input()] = [
  20336. 'streaming',
  20337. 'urlinput-events',
  20338. 'invalidating'
  20339. ], _a),
  20340. model: {
  20341. getDisplayText: function (itemData) {
  20342. return itemData.value;
  20343. },
  20344. selectsOver: false,
  20345. populateFromBrowse: false
  20346. },
  20347. markers: { openClass: 'tox-textfield--popup-open' },
  20348. lazySink: backstage.shared.getSink,
  20349. parts: { menu: part(false, 1, 'normal') },
  20350. onExecute: function (_menu, component, _entry) {
  20351. emitWith(component, formSubmitEvent, {});
  20352. },
  20353. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  20354. updateHistory(typeahead);
  20355. emitWith(typeahead, formChangeEvent, { name: spec.name });
  20356. }
  20357. });
  20358. var pLabel = spec.label.map(function (label) {
  20359. return renderLabel(label, providersBackstage);
  20360. });
  20361. var makeIcon = function (name, errId, icon, label) {
  20362. if (icon === void 0) {
  20363. icon = name;
  20364. }
  20365. if (label === void 0) {
  20366. label = name;
  20367. }
  20368. return {
  20369. dom: {
  20370. tag: 'div',
  20371. classes: [
  20372. 'tox-icon',
  20373. 'tox-control-wrap__status-icon-' + name
  20374. ],
  20375. innerHtml: get$d(icon, providersBackstage.icons),
  20376. attributes: __assign({
  20377. 'title': providersBackstage.translate(label),
  20378. 'aria-live': 'polite'
  20379. }, errId.fold(function () {
  20380. return {};
  20381. }, function (id) {
  20382. return { id: id };
  20383. }))
  20384. }
  20385. };
  20386. };
  20387. var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
  20388. var memStatus = record({
  20389. dom: {
  20390. tag: 'div',
  20391. classes: ['tox-control-wrap__status-icon-wrap']
  20392. },
  20393. components: [memInvalidIcon.asSpec()]
  20394. });
  20395. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  20396. var browseUrlEvent = generate$1('browser.url.event');
  20397. var memUrlBox = record({
  20398. dom: {
  20399. tag: 'div',
  20400. classes: ['tox-control-wrap']
  20401. },
  20402. components: [
  20403. pField,
  20404. memStatus.asSpec()
  20405. ],
  20406. behaviours: derive$1([Disabling.config({
  20407. disabled: function () {
  20408. return spec.disabled || providersBackstage.isReadOnly();
  20409. }
  20410. })])
  20411. });
  20412. var memUrlPickerButton = record(renderButton({
  20413. name: spec.name,
  20414. icon: Optional.some('browse'),
  20415. text: spec.label.getOr(''),
  20416. disabled: spec.disabled,
  20417. primary: false,
  20418. borderless: true
  20419. }, function (component) {
  20420. return emit(component, browseUrlEvent);
  20421. }, providersBackstage, [], ['tox-browse-url']));
  20422. var controlHWrapper = function () {
  20423. return {
  20424. dom: {
  20425. tag: 'div',
  20426. classes: ['tox-form__controls-h-stack']
  20427. },
  20428. components: flatten([
  20429. [memUrlBox.asSpec()],
  20430. optUrlPicker.map(function () {
  20431. return memUrlPickerButton.asSpec();
  20432. }).toArray()
  20433. ])
  20434. };
  20435. };
  20436. var openUrlPicker = function (comp) {
  20437. Composing.getCurrent(comp).each(function (field) {
  20438. var componentData = Representing.getValue(field);
  20439. var urlData = __assign({ fieldname: spec.name }, componentData);
  20440. optUrlPicker.each(function (picker) {
  20441. picker(urlData).get(function (chosenData) {
  20442. Representing.setValue(field, chosenData);
  20443. emitWith(comp, formChangeEvent, { name: spec.name });
  20444. });
  20445. });
  20446. });
  20447. };
  20448. return FormField.sketch({
  20449. dom: renderFormFieldDom(),
  20450. components: pLabel.toArray().concat([controlHWrapper()]),
  20451. fieldBehaviours: derive$1([
  20452. Disabling.config({
  20453. disabled: function () {
  20454. return spec.disabled || providersBackstage.isReadOnly();
  20455. },
  20456. onDisabled: function (comp) {
  20457. FormField.getField(comp).each(Disabling.disable);
  20458. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  20459. },
  20460. onEnabled: function (comp) {
  20461. FormField.getField(comp).each(Disabling.enable);
  20462. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  20463. }
  20464. }),
  20465. receivingConfig(),
  20466. config('url-input-events', [run(browseUrlEvent, openUrlPicker)])
  20467. ])
  20468. });
  20469. };
  20470. var renderAlertBanner = function (spec, providersBackstage) {
  20471. return Container.sketch({
  20472. dom: {
  20473. tag: 'div',
  20474. attributes: { role: 'alert' },
  20475. classes: [
  20476. 'tox-notification',
  20477. 'tox-notification--in',
  20478. 'tox-notification--' + spec.level
  20479. ]
  20480. },
  20481. components: [
  20482. {
  20483. dom: {
  20484. tag: 'div',
  20485. classes: ['tox-notification__icon']
  20486. },
  20487. components: [Button.sketch({
  20488. dom: {
  20489. tag: 'button',
  20490. classes: [
  20491. 'tox-button',
  20492. 'tox-button--naked',
  20493. 'tox-button--icon'
  20494. ],
  20495. innerHtml: get$d(spec.icon, providersBackstage.icons),
  20496. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  20497. },
  20498. action: function (comp) {
  20499. emitWith(comp, formActionEvent, {
  20500. name: 'alert-banner',
  20501. value: spec.url
  20502. });
  20503. }
  20504. })]
  20505. },
  20506. {
  20507. dom: {
  20508. tag: 'div',
  20509. classes: ['tox-notification__body'],
  20510. innerHtml: providersBackstage.translate(spec.text)
  20511. }
  20512. }
  20513. ]
  20514. });
  20515. };
  20516. var renderCheckbox = function (spec, providerBackstage) {
  20517. var repBehaviour = Representing.config({
  20518. store: {
  20519. mode: 'manual',
  20520. getValue: function (comp) {
  20521. var el = comp.element.dom;
  20522. return el.checked;
  20523. },
  20524. setValue: function (comp, value) {
  20525. var el = comp.element.dom;
  20526. el.checked = value;
  20527. }
  20528. }
  20529. });
  20530. var toggleCheckboxHandler = function (comp) {
  20531. comp.element.dom.click();
  20532. return Optional.some(true);
  20533. };
  20534. var pField = FormField.parts.field({
  20535. factory: { sketch: identity },
  20536. dom: {
  20537. tag: 'input',
  20538. classes: ['tox-checkbox__input'],
  20539. attributes: { type: 'checkbox' }
  20540. },
  20541. behaviours: derive$1([
  20542. ComposingConfigs.self(),
  20543. Disabling.config({
  20544. disabled: function () {
  20545. return spec.disabled || providerBackstage.isReadOnly();
  20546. }
  20547. }),
  20548. Tabstopping.config({}),
  20549. Focusing.config({}),
  20550. repBehaviour,
  20551. Keying.config({
  20552. mode: 'special',
  20553. onEnter: toggleCheckboxHandler,
  20554. onSpace: toggleCheckboxHandler,
  20555. stopSpaceKeyup: true
  20556. }),
  20557. config('checkbox-events', [run(change(), function (component, _) {
  20558. emitWith(component, formChangeEvent, { name: spec.name });
  20559. })])
  20560. ])
  20561. });
  20562. var pLabel = FormField.parts.label({
  20563. dom: {
  20564. tag: 'span',
  20565. classes: ['tox-checkbox__label'],
  20566. innerHtml: providerBackstage.translate(spec.label)
  20567. },
  20568. behaviours: derive$1([Unselecting.config({})])
  20569. });
  20570. var makeIcon = function (className) {
  20571. var iconName = className === 'checked' ? 'selected' : 'unselected';
  20572. return {
  20573. dom: {
  20574. tag: 'span',
  20575. classes: [
  20576. 'tox-icon',
  20577. 'tox-checkbox-icon__' + className
  20578. ],
  20579. innerHtml: get$d(iconName, providerBackstage.icons)
  20580. }
  20581. };
  20582. };
  20583. var memIcons = record({
  20584. dom: {
  20585. tag: 'div',
  20586. classes: ['tox-checkbox__icons']
  20587. },
  20588. components: [
  20589. makeIcon('checked'),
  20590. makeIcon('unchecked')
  20591. ]
  20592. });
  20593. return FormField.sketch({
  20594. dom: {
  20595. tag: 'label',
  20596. classes: ['tox-checkbox']
  20597. },
  20598. components: [
  20599. pField,
  20600. memIcons.asSpec(),
  20601. pLabel
  20602. ],
  20603. fieldBehaviours: derive$1([
  20604. Disabling.config({
  20605. disabled: function () {
  20606. return spec.disabled || providerBackstage.isReadOnly();
  20607. },
  20608. disableClass: 'tox-checkbox--disabled',
  20609. onDisabled: function (comp) {
  20610. FormField.getField(comp).each(Disabling.disable);
  20611. },
  20612. onEnabled: function (comp) {
  20613. FormField.getField(comp).each(Disabling.enable);
  20614. }
  20615. }),
  20616. receivingConfig()
  20617. ])
  20618. });
  20619. };
  20620. var renderHtmlPanel = function (spec) {
  20621. if (spec.presets === 'presentation') {
  20622. return Container.sketch({
  20623. dom: {
  20624. tag: 'div',
  20625. classes: ['tox-form__group'],
  20626. innerHtml: spec.html
  20627. }
  20628. });
  20629. } else {
  20630. return Container.sketch({
  20631. dom: {
  20632. tag: 'div',
  20633. classes: ['tox-form__group'],
  20634. innerHtml: spec.html,
  20635. attributes: { role: 'document' }
  20636. },
  20637. containerBehaviours: derive$1([
  20638. Tabstopping.config({}),
  20639. Focusing.config({})
  20640. ])
  20641. });
  20642. }
  20643. };
  20644. var make$6 = function (render) {
  20645. return function (parts, spec, backstage) {
  20646. return get(spec, 'name').fold(function () {
  20647. return render(spec, backstage);
  20648. }, function (fieldName) {
  20649. return parts.field(fieldName, render(spec, backstage));
  20650. });
  20651. };
  20652. };
  20653. var makeIframe = function (render) {
  20654. return function (parts, spec, backstage) {
  20655. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  20656. return make$6(render)(parts, iframeSpec, backstage);
  20657. };
  20658. };
  20659. var factories = {
  20660. bar: make$6(function (spec, backstage) {
  20661. return renderBar(spec, backstage.shared);
  20662. }),
  20663. collection: make$6(function (spec, backstage) {
  20664. return renderCollection(spec, backstage.shared.providers);
  20665. }),
  20666. alertbanner: make$6(function (spec, backstage) {
  20667. return renderAlertBanner(spec, backstage.shared.providers);
  20668. }),
  20669. input: make$6(function (spec, backstage) {
  20670. return renderInput(spec, backstage.shared.providers);
  20671. }),
  20672. textarea: make$6(function (spec, backstage) {
  20673. return renderTextarea(spec, backstage.shared.providers);
  20674. }),
  20675. label: make$6(function (spec, backstage) {
  20676. return renderLabel$2(spec, backstage.shared);
  20677. }),
  20678. iframe: makeIframe(function (spec, backstage) {
  20679. return renderIFrame(spec, backstage.shared.providers);
  20680. }),
  20681. button: make$6(function (spec, backstage) {
  20682. return renderDialogButton(spec, backstage.shared.providers);
  20683. }),
  20684. checkbox: make$6(function (spec, backstage) {
  20685. return renderCheckbox(spec, backstage.shared.providers);
  20686. }),
  20687. colorinput: make$6(function (spec, backstage) {
  20688. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  20689. }),
  20690. colorpicker: make$6(renderColorPicker),
  20691. dropzone: make$6(function (spec, backstage) {
  20692. return renderDropZone(spec, backstage.shared.providers);
  20693. }),
  20694. grid: make$6(function (spec, backstage) {
  20695. return renderGrid(spec, backstage.shared);
  20696. }),
  20697. listbox: make$6(function (spec, backstage) {
  20698. return renderListBox(spec, backstage);
  20699. }),
  20700. selectbox: make$6(function (spec, backstage) {
  20701. return renderSelectBox(spec, backstage.shared.providers);
  20702. }),
  20703. sizeinput: make$6(function (spec, backstage) {
  20704. return renderSizeInput(spec, backstage.shared.providers);
  20705. }),
  20706. urlinput: make$6(function (spec, backstage) {
  20707. return renderUrlInput(spec, backstage, backstage.urlinput);
  20708. }),
  20709. customeditor: make$6(renderCustomEditor),
  20710. htmlpanel: make$6(renderHtmlPanel),
  20711. imagetools: make$6(function (spec, backstage) {
  20712. return renderImageTools(spec, backstage.shared.providers);
  20713. }),
  20714. table: make$6(function (spec, backstage) {
  20715. return renderTable(spec, backstage.shared.providers);
  20716. }),
  20717. panel: make$6(function (spec, backstage) {
  20718. return renderPanel(spec, backstage);
  20719. })
  20720. };
  20721. var noFormParts = {
  20722. field: function (_name, spec) {
  20723. return spec;
  20724. }
  20725. };
  20726. var interpretInForm = function (parts, spec, oldBackstage) {
  20727. var newBackstage = deepMerge(oldBackstage, {
  20728. shared: {
  20729. interpreter: function (childSpec) {
  20730. return interpretParts(parts, childSpec, newBackstage);
  20731. }
  20732. }
  20733. });
  20734. return interpretParts(parts, spec, newBackstage);
  20735. };
  20736. var interpretParts = function (parts, spec, backstage) {
  20737. return get(factories, spec.type).fold(function () {
  20738. console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  20739. return spec;
  20740. }, function (factory) {
  20741. return factory(parts, spec, backstage);
  20742. });
  20743. };
  20744. var interpretWithoutForm = function (spec, backstage) {
  20745. var parts = noFormParts;
  20746. return interpretParts(parts, spec, backstage);
  20747. };
  20748. var bubbleAlignments = {
  20749. valignCentre: [],
  20750. alignCentre: [],
  20751. alignLeft: [],
  20752. alignRight: [],
  20753. right: [],
  20754. left: [],
  20755. bottom: [],
  20756. top: []
  20757. };
  20758. var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20759. var bubble = nu$8(-12, 12, bubbleAlignments);
  20760. var overrides = { maxHeightFunction: expandable() };
  20761. var editableAreaAnchor = function () {
  20762. return {
  20763. anchor: 'node',
  20764. root: getContentContainer(contentAreaElement()),
  20765. node: Optional.from(contentAreaElement()),
  20766. bubble: bubble,
  20767. layouts: {
  20768. onRtl: function () {
  20769. return [northwest$3];
  20770. },
  20771. onLtr: function () {
  20772. return [northeast$3];
  20773. }
  20774. },
  20775. overrides: overrides
  20776. };
  20777. };
  20778. var standardAnchor = function () {
  20779. return {
  20780. anchor: 'hotspot',
  20781. hotspot: lazyAnchorbar(),
  20782. bubble: bubble,
  20783. layouts: {
  20784. onRtl: function () {
  20785. return [southeast$1];
  20786. },
  20787. onLtr: function () {
  20788. return [southwest$1];
  20789. }
  20790. },
  20791. overrides: overrides
  20792. };
  20793. };
  20794. return function () {
  20795. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20796. };
  20797. };
  20798. var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20799. var editableAreaAnchor = function () {
  20800. return {
  20801. anchor: 'node',
  20802. root: getContentContainer(contentAreaElement()),
  20803. node: Optional.from(contentAreaElement()),
  20804. layouts: {
  20805. onRtl: function () {
  20806. return [north$3];
  20807. },
  20808. onLtr: function () {
  20809. return [north$3];
  20810. }
  20811. }
  20812. };
  20813. };
  20814. var standardAnchor = function () {
  20815. return {
  20816. anchor: 'hotspot',
  20817. hotspot: lazyAnchorbar(),
  20818. layouts: {
  20819. onRtl: function () {
  20820. return [south$1];
  20821. },
  20822. onLtr: function () {
  20823. return [south$1];
  20824. }
  20825. }
  20826. };
  20827. };
  20828. return function () {
  20829. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20830. };
  20831. };
  20832. var getCursorAnchor = function (editor, bodyElement) {
  20833. return function () {
  20834. return {
  20835. anchor: 'selection',
  20836. root: bodyElement(),
  20837. getSelection: function () {
  20838. var rng = editor.selection.getRng();
  20839. return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  20840. }
  20841. };
  20842. };
  20843. };
  20844. var getNodeAnchor = function (bodyElement) {
  20845. return function (element) {
  20846. return {
  20847. anchor: 'node',
  20848. root: bodyElement(),
  20849. node: element
  20850. };
  20851. };
  20852. };
  20853. var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
  20854. var useFixedToolbarContainer = useFixedContainer(editor);
  20855. var bodyElement = function () {
  20856. return SugarElement.fromDom(editor.getBody());
  20857. };
  20858. var contentAreaElement = function () {
  20859. return SugarElement.fromDom(editor.getContentAreaContainer());
  20860. };
  20861. var lazyUseEditableAreaAnchor = function () {
  20862. return useFixedToolbarContainer || !isToolbarTop();
  20863. };
  20864. return {
  20865. inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  20866. banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  20867. cursor: getCursorAnchor(editor, bodyElement),
  20868. node: getNodeAnchor(bodyElement)
  20869. };
  20870. };
  20871. var colorPicker = function (editor) {
  20872. return function (callback, value) {
  20873. var dialog = colorPickerDialog(editor);
  20874. dialog(callback, value);
  20875. };
  20876. };
  20877. var hasCustomColors$1 = function (editor) {
  20878. return function () {
  20879. return hasCustomColors(editor);
  20880. };
  20881. };
  20882. var getColors$2 = function (editor) {
  20883. return function () {
  20884. return getColors(editor);
  20885. };
  20886. };
  20887. var getColorCols$2 = function (editor) {
  20888. return function () {
  20889. return getColorCols$1(editor);
  20890. };
  20891. };
  20892. var ColorInputBackstage = function (editor) {
  20893. return {
  20894. colorPicker: colorPicker(editor),
  20895. hasCustomColors: hasCustomColors$1(editor),
  20896. getColors: getColors$2(editor),
  20897. getColorCols: getColorCols$2(editor)
  20898. };
  20899. };
  20900. var isDraggableModal$1 = function (editor) {
  20901. return function () {
  20902. return isDraggableModal(editor);
  20903. };
  20904. };
  20905. var DialogBackstage = function (editor) {
  20906. return { isDraggableModal: isDraggableModal$1(editor) };
  20907. };
  20908. var HeaderBackstage = function (editor) {
  20909. var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  20910. return {
  20911. isPositionedAtTop: function () {
  20912. return mode.get() === 'top';
  20913. },
  20914. getDockingMode: mode.get,
  20915. setDockingMode: mode.set
  20916. };
  20917. };
  20918. var defaultStyleFormats = [
  20919. {
  20920. title: 'Headings',
  20921. items: [
  20922. {
  20923. title: 'Heading 1',
  20924. format: 'h1'
  20925. },
  20926. {
  20927. title: 'Heading 2',
  20928. format: 'h2'
  20929. },
  20930. {
  20931. title: 'Heading 3',
  20932. format: 'h3'
  20933. },
  20934. {
  20935. title: 'Heading 4',
  20936. format: 'h4'
  20937. },
  20938. {
  20939. title: 'Heading 5',
  20940. format: 'h5'
  20941. },
  20942. {
  20943. title: 'Heading 6',
  20944. format: 'h6'
  20945. }
  20946. ]
  20947. },
  20948. {
  20949. title: 'Inline',
  20950. items: [
  20951. {
  20952. title: 'Bold',
  20953. format: 'bold'
  20954. },
  20955. {
  20956. title: 'Italic',
  20957. format: 'italic'
  20958. },
  20959. {
  20960. title: 'Underline',
  20961. format: 'underline'
  20962. },
  20963. {
  20964. title: 'Strikethrough',
  20965. format: 'strikethrough'
  20966. },
  20967. {
  20968. title: 'Superscript',
  20969. format: 'superscript'
  20970. },
  20971. {
  20972. title: 'Subscript',
  20973. format: 'subscript'
  20974. },
  20975. {
  20976. title: 'Code',
  20977. format: 'code'
  20978. }
  20979. ]
  20980. },
  20981. {
  20982. title: 'Blocks',
  20983. items: [
  20984. {
  20985. title: 'Paragraph',
  20986. format: 'p'
  20987. },
  20988. {
  20989. title: 'Blockquote',
  20990. format: 'blockquote'
  20991. },
  20992. {
  20993. title: 'Div',
  20994. format: 'div'
  20995. },
  20996. {
  20997. title: 'Pre',
  20998. format: 'pre'
  20999. }
  21000. ]
  21001. },
  21002. {
  21003. title: 'Align',
  21004. items: [
  21005. {
  21006. title: 'Left',
  21007. format: 'alignleft'
  21008. },
  21009. {
  21010. title: 'Center',
  21011. format: 'aligncenter'
  21012. },
  21013. {
  21014. title: 'Right',
  21015. format: 'alignright'
  21016. },
  21017. {
  21018. title: 'Justify',
  21019. format: 'alignjustify'
  21020. }
  21021. ]
  21022. }
  21023. ];
  21024. var isNestedFormat = function (format) {
  21025. return has(format, 'items');
  21026. };
  21027. var isBlockFormat = function (format) {
  21028. return has(format, 'block');
  21029. };
  21030. var isInlineFormat = function (format) {
  21031. return has(format, 'inline');
  21032. };
  21033. var isSelectorFormat = function (format) {
  21034. return has(format, 'selector');
  21035. };
  21036. var mapFormats = function (userFormats) {
  21037. return foldl(userFormats, function (acc, fmt) {
  21038. if (isNestedFormat(fmt)) {
  21039. var result = mapFormats(fmt.items);
  21040. return {
  21041. customFormats: acc.customFormats.concat(result.customFormats),
  21042. formats: acc.formats.concat([{
  21043. title: fmt.title,
  21044. items: result.formats
  21045. }])
  21046. };
  21047. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  21048. var formatName = 'custom-' + fmt.title.toLowerCase();
  21049. return {
  21050. customFormats: acc.customFormats.concat([{
  21051. name: formatName,
  21052. format: fmt
  21053. }]),
  21054. formats: acc.formats.concat([{
  21055. title: fmt.title,
  21056. format: formatName,
  21057. icon: fmt.icon
  21058. }])
  21059. };
  21060. } else {
  21061. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  21062. }
  21063. }, {
  21064. customFormats: [],
  21065. formats: []
  21066. });
  21067. };
  21068. var registerCustomFormats = function (editor, userFormats) {
  21069. var result = mapFormats(userFormats);
  21070. var registerFormats = function (customFormats) {
  21071. each(customFormats, function (fmt) {
  21072. if (!editor.formatter.has(fmt.name)) {
  21073. editor.formatter.register(fmt.name, fmt.format);
  21074. }
  21075. });
  21076. };
  21077. if (editor.formatter) {
  21078. registerFormats(result.customFormats);
  21079. } else {
  21080. editor.on('init', function () {
  21081. registerFormats(result.customFormats);
  21082. });
  21083. }
  21084. return result.formats;
  21085. };
  21086. var getStyleFormats = function (editor) {
  21087. return getUserStyleFormats(editor).map(function (userFormats) {
  21088. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  21089. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  21090. }).getOr(defaultStyleFormats);
  21091. };
  21092. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  21093. var formatterSpec = {
  21094. type: 'formatter',
  21095. isSelected: isSelectedFor(item.format),
  21096. getStylePreview: getPreviewFor(item.format)
  21097. };
  21098. return deepMerge(item, formatterSpec);
  21099. };
  21100. var register$3 = function (editor, formats, isSelectedFor, getPreviewFor) {
  21101. var enrichSupported = function (item) {
  21102. return processBasic(item, isSelectedFor, getPreviewFor);
  21103. };
  21104. var enrichMenu = function (item) {
  21105. var submenuSpec = { type: 'submenu' };
  21106. return deepMerge(item, submenuSpec);
  21107. };
  21108. var enrichCustom = function (item) {
  21109. var formatName = generate$1(item.title);
  21110. var customSpec = {
  21111. type: 'formatter',
  21112. format: formatName,
  21113. isSelected: isSelectedFor(formatName),
  21114. getStylePreview: getPreviewFor(formatName)
  21115. };
  21116. var newItem = deepMerge(item, customSpec);
  21117. editor.formatter.register(formatName, newItem);
  21118. return newItem;
  21119. };
  21120. var doEnrich = function (items) {
  21121. return map(items, function (item) {
  21122. var keys$1 = keys(item);
  21123. if (hasNonNullableKey(item, 'items')) {
  21124. var newItems_1 = doEnrich(item.items);
  21125. return deepMerge(enrichMenu(item), {
  21126. getStyleItems: function () {
  21127. return newItems_1;
  21128. }
  21129. });
  21130. } else if (hasNonNullableKey(item, 'format')) {
  21131. return enrichSupported(item);
  21132. } else if (keys$1.length === 1 && contains(keys$1, 'title')) {
  21133. return deepMerge(item, { type: 'separator' });
  21134. } else {
  21135. return enrichCustom(item);
  21136. }
  21137. });
  21138. };
  21139. return doEnrich(formats);
  21140. };
  21141. var init$7 = function (editor) {
  21142. var isSelectedFor = function (format) {
  21143. return function () {
  21144. return editor.formatter.match(format);
  21145. };
  21146. };
  21147. var getPreviewFor = function (format) {
  21148. return function () {
  21149. var fmt = editor.formatter.get(format);
  21150. return fmt !== undefined ? Optional.some({
  21151. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  21152. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  21153. }) : Optional.none();
  21154. };
  21155. };
  21156. var flatten = function (fmt) {
  21157. var subs = fmt.items;
  21158. return subs !== undefined && subs.length > 0 ? bind(subs, flatten) : [fmt.format];
  21159. };
  21160. var settingsFormats = Cell([]);
  21161. var settingsFlattenedFormats = Cell([]);
  21162. var eventsFormats = Cell([]);
  21163. var eventsFlattenedFormats = Cell([]);
  21164. var replaceSettings = Cell(false);
  21165. editor.on('PreInit', function (_e) {
  21166. var formats = getStyleFormats(editor);
  21167. var enriched = register$3(editor, formats, isSelectedFor, getPreviewFor);
  21168. settingsFormats.set(enriched);
  21169. settingsFlattenedFormats.set(bind(enriched, flatten));
  21170. });
  21171. editor.on('addStyleModifications', function (e) {
  21172. var modifications = register$3(editor, e.items, isSelectedFor, getPreviewFor);
  21173. eventsFormats.set(modifications);
  21174. replaceSettings.set(e.replace);
  21175. eventsFlattenedFormats.set(bind(modifications, flatten));
  21176. });
  21177. var getData = function () {
  21178. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  21179. var fromEvents = eventsFormats.get();
  21180. return fromSettings.concat(fromEvents);
  21181. };
  21182. var getFlattenedKeys = function () {
  21183. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  21184. var fromEvents = eventsFlattenedFormats.get();
  21185. return fromSettings.concat(fromEvents);
  21186. };
  21187. return {
  21188. getData: getData,
  21189. getFlattenedKeys: getFlattenedKeys
  21190. };
  21191. };
  21192. var trim$1 = global$e.trim;
  21193. var hasContentEditableState = function (value) {
  21194. return function (node) {
  21195. if (node && node.nodeType === 1) {
  21196. if (node.contentEditable === value) {
  21197. return true;
  21198. }
  21199. if (node.getAttribute('data-mce-contenteditable') === value) {
  21200. return true;
  21201. }
  21202. }
  21203. return false;
  21204. };
  21205. };
  21206. var isContentEditableTrue = hasContentEditableState('true');
  21207. var isContentEditableFalse = hasContentEditableState('false');
  21208. var create$8 = function (type, title, url, level, attach) {
  21209. return {
  21210. type: type,
  21211. title: title,
  21212. url: url,
  21213. level: level,
  21214. attach: attach
  21215. };
  21216. };
  21217. var isChildOfContentEditableTrue = function (node) {
  21218. while (node = node.parentNode) {
  21219. var value = node.contentEditable;
  21220. if (value && value !== 'inherit') {
  21221. return isContentEditableTrue(node);
  21222. }
  21223. }
  21224. return false;
  21225. };
  21226. var select = function (selector, root) {
  21227. return map(descendants(SugarElement.fromDom(root), selector), function (element) {
  21228. return element.dom;
  21229. });
  21230. };
  21231. var getElementText = function (elm) {
  21232. return elm.innerText || elm.textContent;
  21233. };
  21234. var getOrGenerateId = function (elm) {
  21235. return elm.id ? elm.id : generate$1('h');
  21236. };
  21237. var isAnchor = function (elm) {
  21238. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  21239. };
  21240. var isValidAnchor = function (elm) {
  21241. return isAnchor(elm) && isEditable(elm);
  21242. };
  21243. var isHeader = function (elm) {
  21244. return elm && /^(H[1-6])$/.test(elm.nodeName);
  21245. };
  21246. var isEditable = function (elm) {
  21247. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  21248. };
  21249. var isValidHeader = function (elm) {
  21250. return isHeader(elm) && isEditable(elm);
  21251. };
  21252. var getLevel = function (elm) {
  21253. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  21254. };
  21255. var headerTarget = function (elm) {
  21256. var headerId = getOrGenerateId(elm);
  21257. var attach = function () {
  21258. elm.id = headerId;
  21259. };
  21260. return create$8('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  21261. };
  21262. var anchorTarget = function (elm) {
  21263. var anchorId = elm.id || elm.name;
  21264. var anchorText = getElementText(elm);
  21265. return create$8('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  21266. };
  21267. var getHeaderTargets = function (elms) {
  21268. return map(filter(elms, isValidHeader), headerTarget);
  21269. };
  21270. var getAnchorTargets = function (elms) {
  21271. return map(filter(elms, isValidAnchor), anchorTarget);
  21272. };
  21273. var getTargetElements = function (elm) {
  21274. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  21275. return elms;
  21276. };
  21277. var hasTitle = function (target) {
  21278. return trim$1(target.title).length > 0;
  21279. };
  21280. var find$5 = function (elm) {
  21281. var elms = getTargetElements(elm);
  21282. return filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  21283. };
  21284. var LinkTargets = { find: find$5 };
  21285. var STORAGE_KEY = 'tinymce-url-history';
  21286. var HISTORY_LENGTH = 5;
  21287. var isHttpUrl = function (url) {
  21288. return isString(url) && /^https?/.test(url);
  21289. };
  21290. var isArrayOfUrl = function (a) {
  21291. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  21292. };
  21293. var isRecordOfUrlArray = function (r) {
  21294. return isObject(r) && find$1(r, function (value) {
  21295. return !isArrayOfUrl(value);
  21296. }).isNone();
  21297. };
  21298. var getAllHistory = function () {
  21299. var unparsedHistory = global$9.getItem(STORAGE_KEY);
  21300. if (unparsedHistory === null) {
  21301. return {};
  21302. }
  21303. var history;
  21304. try {
  21305. history = JSON.parse(unparsedHistory);
  21306. } catch (e) {
  21307. if (e instanceof SyntaxError) {
  21308. console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  21309. return {};
  21310. }
  21311. throw e;
  21312. }
  21313. if (!isRecordOfUrlArray(history)) {
  21314. console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  21315. return {};
  21316. }
  21317. return history;
  21318. };
  21319. var setAllHistory = function (history) {
  21320. if (!isRecordOfUrlArray(history)) {
  21321. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  21322. }
  21323. global$9.setItem(STORAGE_KEY, JSON.stringify(history));
  21324. };
  21325. var getHistory = function (fileType) {
  21326. var history = getAllHistory();
  21327. return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  21328. };
  21329. var addToHistory = function (url, fileType) {
  21330. if (!isHttpUrl(url)) {
  21331. return;
  21332. }
  21333. var history = getAllHistory();
  21334. var items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  21335. var itemsWithoutUrl = filter(items, function (item) {
  21336. return item !== url;
  21337. });
  21338. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  21339. setAllHistory(history);
  21340. };
  21341. var isTruthy = function (value) {
  21342. return !!value;
  21343. };
  21344. var makeMap = function (value) {
  21345. return map$2(global$e.makeMap(value, /[, ]/), isTruthy);
  21346. };
  21347. var getPicker = function (editor) {
  21348. return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
  21349. };
  21350. var getPickerTypes = function (editor) {
  21351. var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
  21352. var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
  21353. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  21354. return getPicker(editor).fold(function () {
  21355. return false;
  21356. }, function (_picker) {
  21357. return optTypes.fold(function () {
  21358. return true;
  21359. }, function (types) {
  21360. return keys(types).length > 0 ? types : false;
  21361. });
  21362. });
  21363. };
  21364. var getPickerSetting = function (editor, filetype) {
  21365. var pickerTypes = getPickerTypes(editor);
  21366. if (isBoolean(pickerTypes)) {
  21367. return pickerTypes ? getPicker(editor) : Optional.none();
  21368. } else {
  21369. return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
  21370. }
  21371. };
  21372. var getUrlPicker = function (editor, filetype) {
  21373. return getPickerSetting(editor, filetype).map(function (picker) {
  21374. return function (entry) {
  21375. return Future.nu(function (completer) {
  21376. var handler = function (value, meta) {
  21377. if (!isString(value)) {
  21378. throw new Error('Expected value to be string');
  21379. }
  21380. if (meta !== undefined && !isObject(meta)) {
  21381. throw new Error('Expected meta to be a object');
  21382. }
  21383. var r = {
  21384. value: value,
  21385. meta: meta
  21386. };
  21387. completer(r);
  21388. };
  21389. var meta = __assign({
  21390. filetype: filetype,
  21391. fieldname: entry.fieldname
  21392. }, Optional.from(entry.meta).getOr({}));
  21393. picker.call(editor, handler, entry.value, meta);
  21394. });
  21395. };
  21396. });
  21397. };
  21398. var getTextSetting = function (value) {
  21399. return Optional.from(value).filter(isString).getOrUndefined();
  21400. };
  21401. var getLinkInformation = function (editor) {
  21402. if (noTypeaheadUrls(editor)) {
  21403. return Optional.none();
  21404. }
  21405. return Optional.some({
  21406. targets: LinkTargets.find(editor.getBody()),
  21407. anchorTop: getTextSetting(getAnchorTop(editor)),
  21408. anchorBottom: getTextSetting(getAnchorBottom(editor))
  21409. });
  21410. };
  21411. var getValidationHandler = function (editor) {
  21412. return Optional.from(getFilePickerValidatorHandler(editor));
  21413. };
  21414. var UrlInputBackstage = function (editor) {
  21415. return {
  21416. getHistory: getHistory,
  21417. addToHistory: addToHistory,
  21418. getLinkInformation: function () {
  21419. return getLinkInformation(editor);
  21420. },
  21421. getValidationHandler: function () {
  21422. return getValidationHandler(editor);
  21423. },
  21424. getUrlPicker: function (filetype) {
  21425. return getUrlPicker(editor, filetype);
  21426. }
  21427. };
  21428. };
  21429. var init$8 = function (sink, editor, lazyAnchorbar) {
  21430. var contextMenuState = Cell(false);
  21431. var toolbar = HeaderBackstage(editor);
  21432. var backstage = {
  21433. shared: {
  21434. providers: {
  21435. icons: function () {
  21436. return editor.ui.registry.getAll().icons;
  21437. },
  21438. menuItems: function () {
  21439. return editor.ui.registry.getAll().menuItems;
  21440. },
  21441. translate: global$6.translate,
  21442. isReadOnly: function () {
  21443. return editor.mode.isReadOnly();
  21444. }
  21445. },
  21446. interpreter: function (s) {
  21447. return interpretWithoutForm(s, backstage);
  21448. },
  21449. anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  21450. header: toolbar,
  21451. getSink: function () {
  21452. return Result.value(sink);
  21453. }
  21454. },
  21455. urlinput: UrlInputBackstage(editor),
  21456. styleselect: init$7(editor),
  21457. colorinput: ColorInputBackstage(editor),
  21458. dialog: DialogBackstage(editor),
  21459. isContextMenuOpen: function () {
  21460. return contextMenuState.get();
  21461. },
  21462. setContextMenuState: function (state) {
  21463. return contextMenuState.set(state);
  21464. }
  21465. };
  21466. return backstage;
  21467. };
  21468. var expandable$1 = constant(function (element, available) {
  21469. setMax$1(element, Math.floor(available));
  21470. });
  21471. var showContextToolbarEvent = 'contexttoolbar-show';
  21472. var hideContextToolbarEvent = 'contexttoolbar-hide';
  21473. var schema$k = constant([
  21474. strict$1('dom'),
  21475. defaulted$1('shell', true),
  21476. field$1('toolbarBehaviours', [Replacing])
  21477. ]);
  21478. var enhanceGroups = function () {
  21479. return { behaviours: derive$1([Replacing.config({})]) };
  21480. };
  21481. var parts$7 = constant([optional({
  21482. name: 'groups',
  21483. overrides: enhanceGroups
  21484. })]);
  21485. var factory$9 = function (detail, components, _spec, _externals) {
  21486. var setGroups = function (toolbar, groups) {
  21487. getGroupContainer(toolbar).fold(function () {
  21488. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21489. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21490. }, function (container) {
  21491. Replacing.set(container, groups);
  21492. });
  21493. };
  21494. var getGroupContainer = function (component) {
  21495. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  21496. };
  21497. var extra = detail.shell ? {
  21498. behaviours: [Replacing.config({})],
  21499. components: []
  21500. } : {
  21501. behaviours: [],
  21502. components: components
  21503. };
  21504. return {
  21505. uid: detail.uid,
  21506. dom: detail.dom,
  21507. components: extra.components,
  21508. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  21509. apis: { setGroups: setGroups },
  21510. domModification: { attributes: { role: 'group' } }
  21511. };
  21512. };
  21513. var Toolbar = composite$1({
  21514. name: 'Toolbar',
  21515. configFields: schema$k(),
  21516. partFields: parts$7(),
  21517. factory: factory$9,
  21518. apis: {
  21519. setGroups: function (apis, toolbar, groups) {
  21520. apis.setGroups(toolbar, groups);
  21521. }
  21522. }
  21523. });
  21524. var generate$6 = function (xs, f) {
  21525. var init = {
  21526. len: 0,
  21527. list: []
  21528. };
  21529. var r = foldl(xs, function (b, a) {
  21530. var value = f(a, b.len);
  21531. return value.fold(constant(b), function (v) {
  21532. return {
  21533. len: v.finish,
  21534. list: b.list.concat([v])
  21535. };
  21536. });
  21537. }, init);
  21538. return r.list;
  21539. };
  21540. var output$1 = function (within, extra, withinWidth) {
  21541. return {
  21542. within: within,
  21543. extra: extra,
  21544. withinWidth: withinWidth
  21545. };
  21546. };
  21547. var apportion = function (units, total, len) {
  21548. var parray = generate$6(units, function (unit, current) {
  21549. var width = len(unit);
  21550. return Optional.some({
  21551. element: unit,
  21552. start: current,
  21553. finish: current + width,
  21554. width: width
  21555. });
  21556. });
  21557. var within = filter(parray, function (unit) {
  21558. return unit.finish <= total;
  21559. });
  21560. var withinWidth = foldr(within, function (acc, el) {
  21561. return acc + el.width;
  21562. }, 0);
  21563. var extra = parray.slice(within.length);
  21564. return {
  21565. within: within,
  21566. extra: extra,
  21567. withinWidth: withinWidth
  21568. };
  21569. };
  21570. var toUnit = function (parray) {
  21571. return map(parray, function (unit) {
  21572. return unit.element;
  21573. });
  21574. };
  21575. var fitLast = function (within, extra, withinWidth) {
  21576. var fits = toUnit(within.concat(extra));
  21577. return output$1(fits, [], withinWidth);
  21578. };
  21579. var overflow = function (within, extra, overflower, withinWidth) {
  21580. var fits = toUnit(within).concat([overflower]);
  21581. return output$1(fits, toUnit(extra), withinWidth);
  21582. };
  21583. var fitAll = function (within, extra, withinWidth) {
  21584. return output$1(toUnit(within), [], withinWidth);
  21585. };
  21586. var tryFit = function (total, units, len) {
  21587. var divide = apportion(units, total, len);
  21588. return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
  21589. };
  21590. var partition$3 = function (total, units, len, overflower) {
  21591. var divide = tryFit(total, units, len).getOrThunk(function () {
  21592. return apportion(units, total - len(overflower), len);
  21593. });
  21594. var within = divide.within;
  21595. var extra = divide.extra;
  21596. var withinWidth = divide.withinWidth;
  21597. if (extra.length === 1 && extra[0].width <= len(overflower)) {
  21598. return fitLast(within, extra, withinWidth);
  21599. } else if (extra.length >= 1) {
  21600. return overflow(within, extra, overflower, withinWidth);
  21601. } else {
  21602. return fitAll(within, extra, withinWidth);
  21603. }
  21604. };
  21605. var setGroups = function (toolbar, storedGroups) {
  21606. var bGroups = map(storedGroups, function (g) {
  21607. return premade$1(g);
  21608. });
  21609. Toolbar.setGroups(toolbar, bGroups);
  21610. };
  21611. var findFocusedComp = function (comps) {
  21612. return findMap(comps, function (comp) {
  21613. return search(comp.element).bind(function (focusedElm) {
  21614. return comp.getSystem().getByDom(focusedElm).toOptional();
  21615. });
  21616. });
  21617. };
  21618. var refresh = function (toolbar, detail, setOverflow) {
  21619. var primary = getPartOrDie(toolbar, detail, 'primary');
  21620. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  21621. set$2(primary.element, 'visibility', 'hidden');
  21622. var groups = detail.builtGroups.get().concat([overflowGroup]);
  21623. var focusedComp = findFocusedComp(groups);
  21624. setOverflow([]);
  21625. setGroups(primary, groups);
  21626. var availableWidth = get$7(primary.element);
  21627. var overflows = partition$3(availableWidth, detail.builtGroups.get(), function (comp) {
  21628. return get$7(comp.element);
  21629. }, overflowGroup);
  21630. if (overflows.extra.length === 0) {
  21631. Replacing.remove(primary, overflowGroup);
  21632. setOverflow([]);
  21633. } else {
  21634. setGroups(primary, overflows.within);
  21635. setOverflow(overflows.extra);
  21636. }
  21637. remove$6(primary.element, 'visibility');
  21638. reflow(primary.element);
  21639. focusedComp.each(Focusing.focus);
  21640. };
  21641. var schema$l = constant([
  21642. field$1('splitToolbarBehaviours', [Coupling]),
  21643. state$1('builtGroups', function () {
  21644. return Cell([]);
  21645. })
  21646. ]);
  21647. var schema$m = constant([
  21648. markers(['overflowToggledClass']),
  21649. optionFunction('getOverflowBounds'),
  21650. strict$1('lazySink'),
  21651. state$1('overflowGroups', function () {
  21652. return Cell([]);
  21653. })
  21654. ].concat(schema$l()));
  21655. var parts$8 = constant([
  21656. required({
  21657. factory: Toolbar,
  21658. schema: schema$k(),
  21659. name: 'primary'
  21660. }),
  21661. external$1({
  21662. schema: schema$k(),
  21663. name: 'overflow'
  21664. }),
  21665. external$1({ name: 'overflow-button' }),
  21666. external$1({ name: 'overflow-group' })
  21667. ]);
  21668. var schema$n = constant([
  21669. markers(['toggledClass']),
  21670. strict$1('lazySink'),
  21671. strictFunction('fetch'),
  21672. optionFunction('getBounds'),
  21673. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  21674. schema$1()
  21675. ]);
  21676. var parts$9 = constant([
  21677. external$1({
  21678. name: 'button',
  21679. overrides: function (detail) {
  21680. return {
  21681. dom: { attributes: { 'aria-haspopup': 'true' } },
  21682. buttonBehaviours: derive$1([Toggling.config({
  21683. toggleClass: detail.markers.toggledClass,
  21684. aria: { mode: 'expanded' },
  21685. toggleOnExecute: false
  21686. })])
  21687. };
  21688. }
  21689. }),
  21690. external$1({
  21691. factory: Toolbar,
  21692. schema: schema$k(),
  21693. name: 'toolbar',
  21694. overrides: function (detail) {
  21695. return {
  21696. toolbarBehaviours: derive$1([Keying.config({
  21697. mode: 'cyclic',
  21698. onEscape: function (comp) {
  21699. getPart(comp, detail, 'button').each(Focusing.focus);
  21700. return Optional.none();
  21701. }
  21702. })])
  21703. };
  21704. }
  21705. })
  21706. ]);
  21707. var toggle$2 = function (button, externals) {
  21708. var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  21709. if (Sandboxing.isOpen(toolbarSandbox)) {
  21710. Sandboxing.close(toolbarSandbox);
  21711. } else {
  21712. Sandboxing.open(toolbarSandbox, externals.toolbar());
  21713. }
  21714. };
  21715. var position$2 = function (button, toolbar, detail, layouts) {
  21716. var bounds = detail.getBounds.map(function (bounder) {
  21717. return bounder();
  21718. });
  21719. var sink = detail.lazySink(button).getOrDie();
  21720. Positioning.positionWithinBounds(sink, {
  21721. anchor: 'hotspot',
  21722. hotspot: button,
  21723. layouts: layouts,
  21724. overrides: { maxWidthFunction: expandable$1() }
  21725. }, toolbar, bounds);
  21726. };
  21727. var setGroups$1 = function (button, toolbar, detail, layouts, groups) {
  21728. Toolbar.setGroups(toolbar, groups);
  21729. position$2(button, toolbar, detail, layouts);
  21730. Toggling.on(button);
  21731. };
  21732. var makeSandbox$1 = function (button, spec, detail) {
  21733. var ariaOwner = manager();
  21734. var onOpen = function (sandbox, toolbar) {
  21735. detail.fetch().get(function (groups) {
  21736. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21737. ariaOwner.link(button.element);
  21738. Keying.focusIn(toolbar);
  21739. });
  21740. };
  21741. var onClose = function () {
  21742. Toggling.off(button);
  21743. Focusing.focus(button);
  21744. ariaOwner.unlink(button.element);
  21745. };
  21746. return {
  21747. dom: {
  21748. tag: 'div',
  21749. attributes: { id: ariaOwner.id }
  21750. },
  21751. behaviours: derive$1([
  21752. Keying.config({
  21753. mode: 'special',
  21754. onEscape: function (comp) {
  21755. Sandboxing.close(comp);
  21756. return Optional.some(true);
  21757. }
  21758. }),
  21759. Sandboxing.config({
  21760. onOpen: onOpen,
  21761. onClose: onClose,
  21762. isPartOf: function (container, data, queryElem) {
  21763. return isPartOf(data, queryElem) || isPartOf(button, queryElem);
  21764. },
  21765. getAttachPoint: function () {
  21766. return detail.lazySink(button).getOrDie();
  21767. }
  21768. }),
  21769. Receiving.config({
  21770. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
  21771. return { fireEventInstead: { event: fe.event } };
  21772. }).getOr({})))), receivingChannel$1({
  21773. doReposition: function () {
  21774. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21775. position$2(button, toolbar, detail, spec.layouts);
  21776. });
  21777. }
  21778. }))
  21779. })
  21780. ])
  21781. };
  21782. };
  21783. var factory$a = function (detail, components, spec, externals) {
  21784. return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  21785. action: function (button) {
  21786. toggle$2(button, externals);
  21787. },
  21788. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  21789. others: {
  21790. toolbarSandbox: function (button) {
  21791. return makeSandbox$1(button, spec, detail);
  21792. }
  21793. }
  21794. })])
  21795. }))), {
  21796. apis: {
  21797. setGroups: function (button, groups) {
  21798. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21799. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21800. });
  21801. },
  21802. reposition: function (button) {
  21803. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21804. position$2(button, toolbar, detail, spec.layouts);
  21805. });
  21806. },
  21807. toggle: function (button) {
  21808. toggle$2(button, externals);
  21809. },
  21810. getToolbar: function (button) {
  21811. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  21812. },
  21813. isOpen: function (button) {
  21814. return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
  21815. }
  21816. }
  21817. });
  21818. };
  21819. var FloatingToolbarButton = composite$1({
  21820. name: 'FloatingToolbarButton',
  21821. factory: factory$a,
  21822. configFields: schema$n(),
  21823. partFields: parts$9(),
  21824. apis: {
  21825. setGroups: function (apis, button, groups) {
  21826. apis.setGroups(button, groups);
  21827. },
  21828. reposition: function (apis, button) {
  21829. apis.reposition(button);
  21830. },
  21831. toggle: function (apis, button) {
  21832. apis.toggle(button);
  21833. },
  21834. getToolbar: function (apis, button) {
  21835. return apis.getToolbar(button);
  21836. },
  21837. isOpen: function (apis, button) {
  21838. return apis.isOpen(button);
  21839. }
  21840. }
  21841. });
  21842. var schema$o = constant([
  21843. strict$1('items'),
  21844. markers(['itemSelector']),
  21845. field$1('tgroupBehaviours', [Keying])
  21846. ]);
  21847. var parts$a = constant([group({
  21848. name: 'items',
  21849. unit: 'item'
  21850. })]);
  21851. var factory$b = function (detail, components, _spec, _externals) {
  21852. return {
  21853. uid: detail.uid,
  21854. dom: detail.dom,
  21855. components: components,
  21856. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  21857. mode: 'flow',
  21858. selector: detail.markers.itemSelector
  21859. })]),
  21860. domModification: { attributes: { role: 'toolbar' } }
  21861. };
  21862. };
  21863. var ToolbarGroup = composite$1({
  21864. name: 'ToolbarGroup',
  21865. configFields: schema$o(),
  21866. partFields: parts$a(),
  21867. factory: factory$b
  21868. });
  21869. var buildGroups = function (comps) {
  21870. return map(comps, function (g) {
  21871. return premade$1(g);
  21872. });
  21873. };
  21874. var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  21875. refresh(toolbar, detail, function (overflowGroups) {
  21876. detail.overflowGroups.set(overflowGroups);
  21877. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21878. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  21879. });
  21880. });
  21881. };
  21882. var factory$c = function (detail, components, spec, externals) {
  21883. var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  21884. fetch: function () {
  21885. return Future.nu(function (resolve) {
  21886. resolve(buildGroups(detail.overflowGroups.get()));
  21887. });
  21888. },
  21889. layouts: {
  21890. onLtr: function () {
  21891. return [
  21892. southwest$1,
  21893. southeast$1
  21894. ];
  21895. },
  21896. onRtl: function () {
  21897. return [
  21898. southeast$1,
  21899. southwest$1
  21900. ];
  21901. },
  21902. onBottomLtr: function () {
  21903. return [
  21904. northwest$1,
  21905. northeast$1
  21906. ];
  21907. },
  21908. onBottomRtl: function () {
  21909. return [
  21910. northeast$1,
  21911. northwest$1
  21912. ];
  21913. }
  21914. },
  21915. getBounds: spec.getOverflowBounds,
  21916. lazySink: detail.lazySink,
  21917. fireDismissalEventInstead: {},
  21918. markers: { toggledClass: detail.markers.overflowToggledClass },
  21919. parts: {
  21920. button: externals['overflow-button'](),
  21921. toolbar: externals.overflow()
  21922. }
  21923. }));
  21924. return {
  21925. uid: detail.uid,
  21926. dom: detail.dom,
  21927. components: components,
  21928. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  21929. others: {
  21930. overflowGroup: function () {
  21931. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  21932. }
  21933. }
  21934. })]),
  21935. apis: {
  21936. setGroups: function (toolbar, groups) {
  21937. detail.builtGroups.set(map(groups, toolbar.getSystem().build));
  21938. refresh$1(toolbar, memFloatingToolbarButton, detail);
  21939. },
  21940. refresh: function (toolbar) {
  21941. return refresh$1(toolbar, memFloatingToolbarButton, detail);
  21942. },
  21943. toggle: function (toolbar) {
  21944. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21945. FloatingToolbarButton.toggle(floatingToolbarButton);
  21946. });
  21947. },
  21948. isOpen: function (toolbar) {
  21949. return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
  21950. },
  21951. reposition: function (toolbar) {
  21952. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21953. FloatingToolbarButton.reposition(floatingToolbarButton);
  21954. });
  21955. },
  21956. getOverflow: function (toolbar) {
  21957. return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
  21958. }
  21959. },
  21960. domModification: { attributes: { role: 'group' } }
  21961. };
  21962. };
  21963. var SplitFloatingToolbar = composite$1({
  21964. name: 'SplitFloatingToolbar',
  21965. configFields: schema$m(),
  21966. partFields: parts$8(),
  21967. factory: factory$c,
  21968. apis: {
  21969. setGroups: function (apis, toolbar, groups) {
  21970. apis.setGroups(toolbar, groups);
  21971. },
  21972. refresh: function (apis, toolbar) {
  21973. apis.refresh(toolbar);
  21974. },
  21975. reposition: function (apis, toolbar) {
  21976. apis.reposition(toolbar);
  21977. },
  21978. toggle: function (apis, toolbar) {
  21979. apis.toggle(toolbar);
  21980. },
  21981. isOpen: function (apis, toolbar) {
  21982. return apis.isOpen(toolbar);
  21983. },
  21984. getOverflow: function (apis, toolbar) {
  21985. return apis.getOverflow(toolbar);
  21986. }
  21987. }
  21988. });
  21989. var getAnimationRoot = function (component, slideConfig) {
  21990. return slideConfig.getAnimationRoot.fold(function () {
  21991. return component.element;
  21992. }, function (get) {
  21993. return get(component);
  21994. });
  21995. };
  21996. var getDimensionProperty = function (slideConfig) {
  21997. return slideConfig.dimension.property;
  21998. };
  21999. var getDimension = function (slideConfig, elem) {
  22000. return slideConfig.dimension.getDimension(elem);
  22001. };
  22002. var disableTransitions = function (component, slideConfig) {
  22003. var root = getAnimationRoot(component, slideConfig);
  22004. remove$5(root, [
  22005. slideConfig.shrinkingClass,
  22006. slideConfig.growingClass
  22007. ]);
  22008. };
  22009. var setShrunk = function (component, slideConfig) {
  22010. remove$4(component.element, slideConfig.openClass);
  22011. add$2(component.element, slideConfig.closedClass);
  22012. set$2(component.element, getDimensionProperty(slideConfig), '0px');
  22013. reflow(component.element);
  22014. };
  22015. var setGrown = function (component, slideConfig) {
  22016. remove$4(component.element, slideConfig.closedClass);
  22017. add$2(component.element, slideConfig.openClass);
  22018. remove$6(component.element, getDimensionProperty(slideConfig));
  22019. };
  22020. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  22021. slideState.setCollapsed();
  22022. set$2(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  22023. reflow(component.element);
  22024. disableTransitions(component, slideConfig);
  22025. setShrunk(component, slideConfig);
  22026. slideConfig.onStartShrink(component);
  22027. slideConfig.onShrunk(component);
  22028. };
  22029. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  22030. var size = calculatedSize.getOrThunk(function () {
  22031. return getDimension(slideConfig, component.element);
  22032. });
  22033. slideState.setCollapsed();
  22034. set$2(component.element, getDimensionProperty(slideConfig), size);
  22035. reflow(component.element);
  22036. var root = getAnimationRoot(component, slideConfig);
  22037. remove$4(root, slideConfig.growingClass);
  22038. add$2(root, slideConfig.shrinkingClass);
  22039. setShrunk(component, slideConfig);
  22040. slideConfig.onStartShrink(component);
  22041. };
  22042. var doStartSmartShrink = function (component, slideConfig, slideState) {
  22043. var size = getDimension(slideConfig, component.element);
  22044. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  22045. shrinker(component, slideConfig, slideState, Optional.some(size));
  22046. };
  22047. var doStartGrow = function (component, slideConfig, slideState) {
  22048. var root = getAnimationRoot(component, slideConfig);
  22049. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  22050. var beforeSize = getDimension(slideConfig, component.element);
  22051. setGrown(component, slideConfig);
  22052. var fullSize = getDimension(slideConfig, component.element);
  22053. var startPartialGrow = function () {
  22054. set$2(component.element, getDimensionProperty(slideConfig), beforeSize);
  22055. reflow(component.element);
  22056. };
  22057. var startCompleteGrow = function () {
  22058. setShrunk(component, slideConfig);
  22059. };
  22060. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  22061. setStartSize();
  22062. remove$4(root, slideConfig.shrinkingClass);
  22063. add$2(root, slideConfig.growingClass);
  22064. setGrown(component, slideConfig);
  22065. set$2(component.element, getDimensionProperty(slideConfig), fullSize);
  22066. slideState.setExpanded();
  22067. slideConfig.onStartGrow(component);
  22068. };
  22069. var refresh$2 = function (component, slideConfig, slideState) {
  22070. if (slideState.isExpanded()) {
  22071. remove$6(component.element, getDimensionProperty(slideConfig));
  22072. var fullSize = getDimension(slideConfig, component.element);
  22073. set$2(component.element, getDimensionProperty(slideConfig), fullSize);
  22074. }
  22075. };
  22076. var grow = function (component, slideConfig, slideState) {
  22077. if (!slideState.isExpanded()) {
  22078. doStartGrow(component, slideConfig, slideState);
  22079. }
  22080. };
  22081. var shrink = function (component, slideConfig, slideState) {
  22082. if (slideState.isExpanded()) {
  22083. doStartSmartShrink(component, slideConfig, slideState);
  22084. }
  22085. };
  22086. var immediateShrink = function (component, slideConfig, slideState) {
  22087. if (slideState.isExpanded()) {
  22088. doImmediateShrink(component, slideConfig, slideState, Optional.none());
  22089. }
  22090. };
  22091. var hasGrown = function (component, slideConfig, slideState) {
  22092. return slideState.isExpanded();
  22093. };
  22094. var hasShrunk = function (component, slideConfig, slideState) {
  22095. return slideState.isCollapsed();
  22096. };
  22097. var isGrowing = function (component, slideConfig, _slideState) {
  22098. var root = getAnimationRoot(component, slideConfig);
  22099. return has$2(root, slideConfig.growingClass) === true;
  22100. };
  22101. var isShrinking = function (component, slideConfig, _slideState) {
  22102. var root = getAnimationRoot(component, slideConfig);
  22103. return has$2(root, slideConfig.shrinkingClass) === true;
  22104. };
  22105. var isTransitioning = function (component, slideConfig, slideState) {
  22106. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  22107. };
  22108. var toggleGrow = function (component, slideConfig, slideState) {
  22109. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  22110. f(component, slideConfig, slideState);
  22111. };
  22112. var SlidingApis = /*#__PURE__*/Object.freeze({
  22113. __proto__: null,
  22114. refresh: refresh$2,
  22115. grow: grow,
  22116. shrink: shrink,
  22117. immediateShrink: immediateShrink,
  22118. hasGrown: hasGrown,
  22119. hasShrunk: hasShrunk,
  22120. isGrowing: isGrowing,
  22121. isShrinking: isShrinking,
  22122. isTransitioning: isTransitioning,
  22123. toggleGrow: toggleGrow,
  22124. disableTransitions: disableTransitions
  22125. });
  22126. var exhibit$6 = function (base, slideConfig, _slideState) {
  22127. var expanded = slideConfig.expanded;
  22128. return expanded ? nu$6({
  22129. classes: [slideConfig.openClass],
  22130. styles: {}
  22131. }) : nu$6({
  22132. classes: [slideConfig.closedClass],
  22133. styles: wrap$1(slideConfig.dimension.property, '0px')
  22134. });
  22135. };
  22136. var events$d = function (slideConfig, slideState) {
  22137. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  22138. var raw = simulatedEvent.event.raw;
  22139. if (raw.propertyName === slideConfig.dimension.property) {
  22140. disableTransitions(component, slideConfig);
  22141. if (slideState.isExpanded()) {
  22142. remove$6(component.element, slideConfig.dimension.property);
  22143. }
  22144. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  22145. notify(component);
  22146. }
  22147. })]);
  22148. };
  22149. var ActiveSliding = /*#__PURE__*/Object.freeze({
  22150. __proto__: null,
  22151. exhibit: exhibit$6,
  22152. events: events$d
  22153. });
  22154. var SlidingSchema = [
  22155. strict$1('closedClass'),
  22156. strict$1('openClass'),
  22157. strict$1('shrinkingClass'),
  22158. strict$1('growingClass'),
  22159. option('getAnimationRoot'),
  22160. onHandler('onShrunk'),
  22161. onHandler('onStartShrink'),
  22162. onHandler('onGrown'),
  22163. onHandler('onStartGrow'),
  22164. defaulted$1('expanded', false),
  22165. strictOf('dimension', choose$1('property', {
  22166. width: [
  22167. output('property', 'width'),
  22168. output('getDimension', function (elem) {
  22169. return get$7(elem) + 'px';
  22170. })
  22171. ],
  22172. height: [
  22173. output('property', 'height'),
  22174. output('getDimension', function (elem) {
  22175. return get$6(elem) + 'px';
  22176. })
  22177. ]
  22178. }))
  22179. ];
  22180. var init$9 = function (spec) {
  22181. var state = Cell(spec.expanded);
  22182. var readState = function () {
  22183. return 'expanded: ' + state.get();
  22184. };
  22185. return nu$5({
  22186. isExpanded: function () {
  22187. return state.get() === true;
  22188. },
  22189. isCollapsed: function () {
  22190. return state.get() === false;
  22191. },
  22192. setCollapsed: curry(state.set, false),
  22193. setExpanded: curry(state.set, true),
  22194. readState: readState
  22195. });
  22196. };
  22197. var SlidingState = /*#__PURE__*/Object.freeze({
  22198. __proto__: null,
  22199. init: init$9
  22200. });
  22201. var Sliding = create$1({
  22202. fields: SlidingSchema,
  22203. name: 'sliding',
  22204. active: ActiveSliding,
  22205. apis: SlidingApis,
  22206. state: SlidingState
  22207. });
  22208. var schema$p = constant([
  22209. markers([
  22210. 'closedClass',
  22211. 'openClass',
  22212. 'shrinkingClass',
  22213. 'growingClass',
  22214. 'overflowToggledClass'
  22215. ]),
  22216. onHandler('onOpened'),
  22217. onHandler('onClosed')
  22218. ].concat(schema$l()));
  22219. var parts$b = constant([
  22220. required({
  22221. factory: Toolbar,
  22222. schema: schema$k(),
  22223. name: 'primary'
  22224. }),
  22225. required({
  22226. factory: Toolbar,
  22227. schema: schema$k(),
  22228. name: 'overflow',
  22229. overrides: function (detail) {
  22230. return {
  22231. toolbarBehaviours: derive$1([
  22232. Sliding.config({
  22233. dimension: { property: 'height' },
  22234. closedClass: detail.markers.closedClass,
  22235. openClass: detail.markers.openClass,
  22236. shrinkingClass: detail.markers.shrinkingClass,
  22237. growingClass: detail.markers.growingClass,
  22238. onShrunk: function (comp) {
  22239. getPart(comp, detail, 'overflow-button').each(function (button) {
  22240. Toggling.off(button);
  22241. Focusing.focus(button);
  22242. });
  22243. detail.onClosed(comp);
  22244. },
  22245. onGrown: function (comp) {
  22246. Keying.focusIn(comp);
  22247. detail.onOpened(comp);
  22248. },
  22249. onStartGrow: function (comp) {
  22250. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  22251. }
  22252. }),
  22253. Keying.config({
  22254. mode: 'acyclic',
  22255. onEscape: function (comp) {
  22256. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  22257. return Optional.some(true);
  22258. }
  22259. })
  22260. ])
  22261. };
  22262. }
  22263. }),
  22264. external$1({
  22265. name: 'overflow-button',
  22266. overrides: function (detail) {
  22267. return {
  22268. buttonBehaviours: derive$1([Toggling.config({
  22269. toggleClass: detail.markers.overflowToggledClass,
  22270. aria: { mode: 'pressed' },
  22271. toggleOnExecute: false
  22272. })])
  22273. };
  22274. }
  22275. }),
  22276. external$1({ name: 'overflow-group' })
  22277. ]);
  22278. var isOpen$1 = function (toolbar, detail) {
  22279. return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
  22280. };
  22281. var toggleToolbar = function (toolbar, detail) {
  22282. getPart(toolbar, detail, 'overflow-button').bind(function () {
  22283. return getPart(toolbar, detail, 'overflow');
  22284. }).each(function (overf) {
  22285. refresh$3(toolbar, detail);
  22286. Sliding.toggleGrow(overf);
  22287. });
  22288. };
  22289. var refresh$3 = function (toolbar, detail) {
  22290. getPart(toolbar, detail, 'overflow').each(function (overflow) {
  22291. refresh(toolbar, detail, function (groups) {
  22292. var builtGroups = map(groups, function (g) {
  22293. return premade$1(g);
  22294. });
  22295. Toolbar.setGroups(overflow, builtGroups);
  22296. });
  22297. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  22298. if (Sliding.hasGrown(overflow)) {
  22299. Toggling.on(button);
  22300. }
  22301. });
  22302. Sliding.refresh(overflow);
  22303. });
  22304. };
  22305. var factory$d = function (detail, components, spec, externals) {
  22306. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  22307. var doSetGroups = function (toolbar, groups) {
  22308. var built = map(groups, toolbar.getSystem().build);
  22309. detail.builtGroups.set(built);
  22310. };
  22311. return {
  22312. uid: detail.uid,
  22313. dom: detail.dom,
  22314. components: components,
  22315. behaviours: augment(detail.splitToolbarBehaviours, [
  22316. Coupling.config({
  22317. others: {
  22318. overflowGroup: function (toolbar) {
  22319. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  22320. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  22321. action: function (_button) {
  22322. emit(toolbar, toolbarToggleEvent);
  22323. }
  22324. }))]
  22325. }));
  22326. }
  22327. }
  22328. }),
  22329. config('toolbar-toggle-events', [run(toolbarToggleEvent, function (toolbar) {
  22330. toggleToolbar(toolbar, detail);
  22331. })])
  22332. ]),
  22333. apis: {
  22334. setGroups: function (toolbar, groups) {
  22335. doSetGroups(toolbar, groups);
  22336. refresh$3(toolbar, detail);
  22337. },
  22338. refresh: function (toolbar) {
  22339. return refresh$3(toolbar, detail);
  22340. },
  22341. toggle: function (toolbar) {
  22342. return toggleToolbar(toolbar, detail);
  22343. },
  22344. isOpen: function (toolbar) {
  22345. return isOpen$1(toolbar, detail);
  22346. }
  22347. },
  22348. domModification: { attributes: { role: 'group' } }
  22349. };
  22350. };
  22351. var SplitSlidingToolbar = composite$1({
  22352. name: 'SplitSlidingToolbar',
  22353. configFields: schema$p(),
  22354. partFields: parts$b(),
  22355. factory: factory$d,
  22356. apis: {
  22357. setGroups: function (apis, toolbar, groups) {
  22358. apis.setGroups(toolbar, groups);
  22359. },
  22360. refresh: function (apis, toolbar) {
  22361. apis.refresh(toolbar);
  22362. },
  22363. toggle: function (apis, toolbar) {
  22364. apis.toggle(toolbar);
  22365. },
  22366. isOpen: function (apis, toolbar) {
  22367. return apis.isOpen(toolbar);
  22368. }
  22369. }
  22370. });
  22371. var toolbarHeightChange = constant(generate$1('toolbar-height-change'));
  22372. var renderToolbarGroupCommon = function (toolbarGroup) {
  22373. var attributes = toolbarGroup.title.fold(function () {
  22374. return {};
  22375. }, function (title) {
  22376. return { attributes: { title: title } };
  22377. });
  22378. return {
  22379. dom: __assign({
  22380. tag: 'div',
  22381. classes: ['tox-toolbar__group']
  22382. }, attributes),
  22383. components: [ToolbarGroup.parts.items({})],
  22384. items: toolbarGroup.items,
  22385. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  22386. tgroupBehaviours: derive$1([
  22387. Tabstopping.config({}),
  22388. Focusing.config({})
  22389. ])
  22390. };
  22391. };
  22392. var renderToolbarGroup = function (toolbarGroup) {
  22393. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  22394. };
  22395. var getToolbarbehaviours = function (toolbarSpec, modeName) {
  22396. var onAttached = runOnAttached(function (component) {
  22397. var groups = map(toolbarSpec.initGroups, renderToolbarGroup);
  22398. Toolbar.setGroups(component, groups);
  22399. });
  22400. return derive$1([
  22401. DisablingConfigs.toolbarButton(toolbarSpec.providers.isReadOnly),
  22402. receivingConfig(),
  22403. Keying.config({
  22404. mode: modeName,
  22405. onEscape: toolbarSpec.onEscape,
  22406. selector: '.tox-toolbar__group'
  22407. }),
  22408. config('toolbar-events', [onAttached])
  22409. ]);
  22410. };
  22411. var renderMoreToolbarCommon = function (toolbarSpec) {
  22412. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22413. return {
  22414. uid: toolbarSpec.uid,
  22415. dom: {
  22416. tag: 'div',
  22417. classes: ['tox-toolbar-overlord']
  22418. },
  22419. parts: {
  22420. 'overflow-group': renderToolbarGroupCommon({
  22421. title: Optional.none(),
  22422. items: []
  22423. }),
  22424. 'overflow-button': renderIconButtonSpec({
  22425. name: 'more',
  22426. icon: Optional.some('more-drawer'),
  22427. disabled: false,
  22428. tooltip: Optional.some('More...'),
  22429. primary: false,
  22430. borderless: false
  22431. }, Optional.none(), toolbarSpec.providers)
  22432. },
  22433. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  22434. };
  22435. };
  22436. var renderFloatingMoreToolbar = function (toolbarSpec) {
  22437. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  22438. var overflowXOffset = 4;
  22439. var primary = SplitFloatingToolbar.parts.primary({
  22440. dom: {
  22441. tag: 'div',
  22442. classes: ['tox-toolbar__primary']
  22443. }
  22444. });
  22445. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22446. lazySink: toolbarSpec.getSink,
  22447. getOverflowBounds: function () {
  22448. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
  22449. var headerBounds = absolute$1(headerElem);
  22450. var docElem = documentElement(headerElem);
  22451. var docBounds = absolute$1(docElem);
  22452. var height = Math.max(docElem.dom.scrollHeight, docBounds.height);
  22453. return bounds$1(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  22454. },
  22455. parts: __assign(__assign({}, baseSpec.parts), {
  22456. overflow: {
  22457. dom: {
  22458. tag: 'div',
  22459. classes: ['tox-toolbar__overflow'],
  22460. attributes: toolbarSpec.attributes
  22461. }
  22462. }
  22463. }),
  22464. components: [primary],
  22465. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  22466. }));
  22467. };
  22468. var renderSlidingMoreToolbar = function (toolbarSpec) {
  22469. var primary = SplitSlidingToolbar.parts.primary({
  22470. dom: {
  22471. tag: 'div',
  22472. classes: ['tox-toolbar__primary']
  22473. }
  22474. });
  22475. var overflow = SplitSlidingToolbar.parts.overflow({
  22476. dom: {
  22477. tag: 'div',
  22478. classes: ['tox-toolbar__overflow']
  22479. }
  22480. });
  22481. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  22482. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22483. components: [
  22484. primary,
  22485. overflow
  22486. ],
  22487. markers: {
  22488. openClass: 'tox-toolbar__overflow--open',
  22489. closedClass: 'tox-toolbar__overflow--closed',
  22490. growingClass: 'tox-toolbar__overflow--growing',
  22491. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  22492. overflowToggledClass: 'tox-tbtn--enabled'
  22493. },
  22494. onOpened: function (comp) {
  22495. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  22496. },
  22497. onClosed: function (comp) {
  22498. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  22499. }
  22500. }));
  22501. };
  22502. var renderToolbar = function (toolbarSpec) {
  22503. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22504. return Toolbar.sketch({
  22505. uid: toolbarSpec.uid,
  22506. dom: {
  22507. tag: 'div',
  22508. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  22509. },
  22510. components: [Toolbar.parts.groups({})],
  22511. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  22512. });
  22513. };
  22514. var groupToolbarButtonSchema = objOf([
  22515. strictString('type'),
  22516. strictOf('items', oneOf([
  22517. arrOfObj$1([
  22518. strictString('name'),
  22519. strictArrayOf('items', string)
  22520. ]),
  22521. string
  22522. ]))
  22523. ].concat(baseToolbarButtonFields));
  22524. var createGroupToolbarButton = function (spec) {
  22525. return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  22526. };
  22527. var baseMenuButtonFields = [
  22528. optionString('text'),
  22529. optionString('tooltip'),
  22530. optionString('icon'),
  22531. strictFunction('fetch'),
  22532. defaultedFunction('onSetup', function () {
  22533. return noop;
  22534. })
  22535. ];
  22536. var MenuButtonSchema = objOf(__spreadArrays([strictString('type')], baseMenuButtonFields));
  22537. var createMenuButton = function (spec) {
  22538. return asRaw('menubutton', MenuButtonSchema, spec);
  22539. };
  22540. var splitButtonSchema = objOf([
  22541. strictString('type'),
  22542. optionString('tooltip'),
  22543. optionString('icon'),
  22544. optionString('text'),
  22545. optionFunction('select'),
  22546. strictFunction('fetch'),
  22547. defaultedFunction('onSetup', function () {
  22548. return noop;
  22549. }),
  22550. defaultedStringEnum('presets', 'normal', [
  22551. 'normal',
  22552. 'color',
  22553. 'listpreview'
  22554. ]),
  22555. defaulted$1('columns', 1),
  22556. strictFunction('onAction'),
  22557. strictFunction('onItemAction')
  22558. ]);
  22559. var createSplitButton = function (spec) {
  22560. return asRaw('SplitButton', splitButtonSchema, spec);
  22561. };
  22562. var events$e = function (reflectingConfig, reflectingState) {
  22563. var update = function (component, data) {
  22564. reflectingConfig.updateState.each(function (updateState) {
  22565. var newState = updateState(component, data);
  22566. reflectingState.set(newState);
  22567. });
  22568. reflectingConfig.renderComponents.each(function (renderComponents) {
  22569. var newComponents = renderComponents(data, reflectingState.get());
  22570. var newChildren = map(newComponents, component.getSystem().build);
  22571. replaceChildren(component, newChildren);
  22572. });
  22573. };
  22574. return derive([
  22575. run(receive(), function (component, message) {
  22576. var receivingData = message;
  22577. if (!receivingData.universal) {
  22578. var channel = reflectingConfig.channel;
  22579. if (contains(receivingData.channels, channel)) {
  22580. update(component, receivingData.data);
  22581. }
  22582. }
  22583. }),
  22584. runOnAttached(function (comp, _se) {
  22585. reflectingConfig.initialData.each(function (rawData) {
  22586. update(comp, rawData);
  22587. });
  22588. })
  22589. ]);
  22590. };
  22591. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  22592. __proto__: null,
  22593. events: events$e
  22594. });
  22595. var getState$2 = function (component, replaceConfig, reflectState) {
  22596. return reflectState;
  22597. };
  22598. var ReflectingApis = /*#__PURE__*/Object.freeze({
  22599. __proto__: null,
  22600. getState: getState$2
  22601. });
  22602. var ReflectingSchema = [
  22603. strict$1('channel'),
  22604. option('renderComponents'),
  22605. option('updateState'),
  22606. option('initialData')
  22607. ];
  22608. var init$a = function () {
  22609. var cell = Cell(Optional.none());
  22610. var set = function (optS) {
  22611. return cell.set(optS);
  22612. };
  22613. var clear = function () {
  22614. return cell.set(Optional.none());
  22615. };
  22616. var get = function () {
  22617. return cell.get();
  22618. };
  22619. var readState = function () {
  22620. return cell.get().fold(function () {
  22621. return 'none';
  22622. }, function (x) {
  22623. return x;
  22624. });
  22625. };
  22626. return {
  22627. readState: readState,
  22628. get: get,
  22629. set: set,
  22630. clear: clear
  22631. };
  22632. };
  22633. var ReflectingState = /*#__PURE__*/Object.freeze({
  22634. __proto__: null,
  22635. init: init$a
  22636. });
  22637. var Reflecting = create$1({
  22638. fields: ReflectingSchema,
  22639. name: 'reflecting',
  22640. active: ActiveReflecting,
  22641. apis: ReflectingApis,
  22642. state: ReflectingState
  22643. });
  22644. var schema$q = constant([
  22645. strict$1('toggleClass'),
  22646. strict$1('fetch'),
  22647. onStrictHandler('onExecute'),
  22648. defaulted$1('getHotspot', Optional.some),
  22649. defaulted$1('getAnchorOverrides', constant({})),
  22650. schema$1(),
  22651. onStrictHandler('onItemExecute'),
  22652. option('lazySink'),
  22653. strict$1('dom'),
  22654. onHandler('onOpen'),
  22655. field$1('splitDropdownBehaviours', [
  22656. Coupling,
  22657. Keying,
  22658. Focusing
  22659. ]),
  22660. defaulted$1('matchWidth', false),
  22661. defaulted$1('useMinWidth', false),
  22662. defaulted$1('eventOrder', {}),
  22663. option('role')
  22664. ].concat(sandboxFields()));
  22665. var arrowPart = required({
  22666. factory: Button,
  22667. schema: [strict$1('dom')],
  22668. name: 'arrow',
  22669. defaults: function () {
  22670. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22671. },
  22672. overrides: function (detail) {
  22673. return {
  22674. dom: {
  22675. tag: 'span',
  22676. attributes: { role: 'presentation' }
  22677. },
  22678. action: function (arrow) {
  22679. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  22680. },
  22681. buttonBehaviours: derive$1([Toggling.config({
  22682. toggleOnExecute: false,
  22683. toggleClass: detail.toggleClass
  22684. })])
  22685. };
  22686. }
  22687. });
  22688. var buttonPart = required({
  22689. factory: Button,
  22690. schema: [strict$1('dom')],
  22691. name: 'button',
  22692. defaults: function () {
  22693. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22694. },
  22695. overrides: function (detail) {
  22696. return {
  22697. dom: {
  22698. tag: 'span',
  22699. attributes: { role: 'presentation' }
  22700. },
  22701. action: function (btn) {
  22702. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22703. detail.onExecute(splitDropdown, btn);
  22704. });
  22705. }
  22706. };
  22707. }
  22708. });
  22709. var parts$c = constant([
  22710. arrowPart,
  22711. buttonPart,
  22712. optional({
  22713. factory: {
  22714. sketch: function (spec) {
  22715. return {
  22716. uid: spec.uid,
  22717. dom: {
  22718. tag: 'span',
  22719. styles: { display: 'none' },
  22720. attributes: { 'aria-hidden': 'true' },
  22721. innerHtml: spec.text
  22722. }
  22723. };
  22724. }
  22725. },
  22726. schema: [strict$1('text')],
  22727. name: 'aria-descriptor'
  22728. }),
  22729. external$1({
  22730. schema: [tieredMenuMarkers()],
  22731. name: 'menu',
  22732. defaults: function (detail) {
  22733. return {
  22734. onExecute: function (tmenu, item) {
  22735. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22736. detail.onItemExecute(splitDropdown, tmenu, item);
  22737. });
  22738. }
  22739. };
  22740. }
  22741. }),
  22742. partType()
  22743. ]);
  22744. var factory$e = function (detail, components, spec, externals) {
  22745. var _a;
  22746. var switchToMenu = function (sandbox) {
  22747. Composing.getCurrent(sandbox).each(function (current) {
  22748. Highlighting.highlightFirst(current);
  22749. Keying.focusIn(current);
  22750. });
  22751. };
  22752. var action = function (component) {
  22753. var onOpenSync = switchToMenu;
  22754. togglePopup(detail, function (x) {
  22755. return x;
  22756. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22757. };
  22758. var openMenu = function (comp) {
  22759. action(comp);
  22760. return Optional.some(true);
  22761. };
  22762. var executeOnButton = function (comp) {
  22763. var button = getPartOrDie(comp, detail, 'button');
  22764. emitExecute(button);
  22765. return Optional.some(true);
  22766. };
  22767. var buttonEvents = __assign(__assign({}, derive([runOnAttached(function (component, _simulatedEvent) {
  22768. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  22769. ariaDescriptor.each(function (descriptor) {
  22770. var descriptorId = generate$1('aria');
  22771. set$1(descriptor.element, 'id', descriptorId);
  22772. set$1(component.element, 'aria-describedby', descriptorId);
  22773. });
  22774. })])), events$7(Optional.some(action)));
  22775. var apis = {
  22776. repositionMenus: function (comp) {
  22777. if (Toggling.isOn(comp)) {
  22778. repositionMenus(comp);
  22779. }
  22780. }
  22781. };
  22782. return {
  22783. uid: detail.uid,
  22784. dom: detail.dom,
  22785. components: components,
  22786. apis: apis,
  22787. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
  22788. 'disabling',
  22789. 'toggling',
  22790. 'alloy.base.behaviour'
  22791. ], _a)),
  22792. events: buttonEvents,
  22793. behaviours: augment(detail.splitDropdownBehaviours, [
  22794. Coupling.config({
  22795. others: {
  22796. sandbox: function (hotspot) {
  22797. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  22798. var extras = {
  22799. onOpen: function () {
  22800. Toggling.on(arrow);
  22801. Toggling.on(hotspot);
  22802. },
  22803. onClose: function () {
  22804. Toggling.off(arrow);
  22805. Toggling.off(hotspot);
  22806. }
  22807. };
  22808. return makeSandbox(detail, hotspot, extras);
  22809. }
  22810. }
  22811. }),
  22812. Keying.config({
  22813. mode: 'special',
  22814. onSpace: executeOnButton,
  22815. onEnter: executeOnButton,
  22816. onDown: openMenu
  22817. }),
  22818. Focusing.config({}),
  22819. Toggling.config({
  22820. toggleOnExecute: false,
  22821. aria: { mode: 'expanded' }
  22822. })
  22823. ]),
  22824. domModification: {
  22825. attributes: {
  22826. 'role': detail.role.getOr('button'),
  22827. 'aria-haspopup': true
  22828. }
  22829. }
  22830. };
  22831. };
  22832. var SplitDropdown = composite$1({
  22833. name: 'SplitDropdown',
  22834. configFields: schema$q(),
  22835. partFields: parts$c(),
  22836. factory: factory$e,
  22837. apis: {
  22838. repositionMenus: function (apis, comp) {
  22839. return apis.repositionMenus(comp);
  22840. }
  22841. }
  22842. });
  22843. var getButtonApi = function (component) {
  22844. return {
  22845. isDisabled: function () {
  22846. return Disabling.isDisabled(component);
  22847. },
  22848. setDisabled: function (state) {
  22849. return Disabling.set(component, state);
  22850. }
  22851. };
  22852. };
  22853. var getToggleApi = function (component) {
  22854. return {
  22855. setActive: function (state) {
  22856. Toggling.set(component, state);
  22857. },
  22858. isActive: function () {
  22859. return Toggling.isOn(component);
  22860. },
  22861. isDisabled: function () {
  22862. return Disabling.isDisabled(component);
  22863. },
  22864. setDisabled: function (state) {
  22865. return Disabling.set(component, state);
  22866. }
  22867. };
  22868. };
  22869. var getTooltipAttributes = function (tooltip, providersBackstage) {
  22870. return tooltip.map(function (tooltip) {
  22871. return {
  22872. 'aria-label': providersBackstage.translate(tooltip),
  22873. 'title': providersBackstage.translate(tooltip)
  22874. };
  22875. }).getOr({});
  22876. };
  22877. var focusButtonEvent = generate$1('focus-button');
  22878. var rtlIcon$1 = [
  22879. 'checklist',
  22880. 'ordered-list'
  22881. ];
  22882. var rtlTransform$1 = [
  22883. 'indent',
  22884. 'outdent',
  22885. 'table-insert-column-after',
  22886. 'table-insert-column-before',
  22887. 'unordered-list'
  22888. ];
  22889. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  22890. var _d;
  22891. var getIconName = function (iconName) {
  22892. return global$6.isRtl() && contains(rtlIcon$1, iconName) ? iconName + '-rtl' : iconName;
  22893. };
  22894. var needsRtlClass = global$6.isRtl() && icon.exists(function (name) {
  22895. return contains(rtlTransform$1, name);
  22896. });
  22897. return {
  22898. dom: {
  22899. tag: 'button',
  22900. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []).concat(needsRtlClass ? ['tox-tbtn__icon-rtl'] : []),
  22901. attributes: getTooltipAttributes(tooltip, providersBackstage)
  22902. },
  22903. components: componentRenderPipeline([
  22904. icon.map(function (iconName) {
  22905. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22906. }),
  22907. text.map(function (text) {
  22908. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22909. })
  22910. ]),
  22911. eventOrder: (_d = {}, _d[mousedown()] = [
  22912. 'focusing',
  22913. 'alloy.base.behaviour',
  22914. 'common-button-display-events'
  22915. ], _d),
  22916. buttonBehaviours: derive$1([
  22917. DisablingConfigs.toolbarButton(providersBackstage.isReadOnly),
  22918. receivingConfig(),
  22919. config('common-button-display-events', [run(mousedown(), function (button, se) {
  22920. se.event.prevent();
  22921. emit(button, focusButtonEvent);
  22922. })])
  22923. ].concat(receiver.map(function (r) {
  22924. return Reflecting.config({
  22925. channel: r,
  22926. initialData: {
  22927. icon: icon,
  22928. text: text
  22929. },
  22930. renderComponents: function (data, _state) {
  22931. return componentRenderPipeline([
  22932. data.icon.map(function (iconName) {
  22933. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22934. }),
  22935. data.text.map(function (text) {
  22936. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22937. })
  22938. ]);
  22939. }
  22940. });
  22941. }).toArray()).concat(behaviours.getOr([])))
  22942. };
  22943. };
  22944. var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  22945. var sharedBackstage = backstage.shared;
  22946. return FloatingToolbarButton.sketch({
  22947. lazySink: sharedBackstage.getSink,
  22948. fetch: function () {
  22949. return Future.nu(function (resolve) {
  22950. resolve(map(identifyButtons(spec.items), renderToolbarGroup));
  22951. });
  22952. },
  22953. markers: { toggledClass: 'tox-tbtn--enabled' },
  22954. parts: {
  22955. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
  22956. toolbar: {
  22957. dom: {
  22958. tag: 'div',
  22959. classes: ['tox-toolbar__overflow'],
  22960. attributes: attributes
  22961. }
  22962. }
  22963. }
  22964. });
  22965. };
  22966. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  22967. var editorOffCell = Cell(noop);
  22968. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
  22969. return Button.sketch({
  22970. dom: structure.dom,
  22971. components: structure.components,
  22972. eventOrder: toolbarButtonEventOrder,
  22973. buttonBehaviours: derive$1([
  22974. config('toolbar-button-events', [
  22975. onToolbarButtonExecute({
  22976. onAction: spec.onAction,
  22977. getApi: specialisation.getApi
  22978. }),
  22979. onControlAttached(specialisation, editorOffCell),
  22980. onControlDetached(specialisation, editorOffCell)
  22981. ]),
  22982. DisablingConfigs.toolbarButton(function () {
  22983. return spec.disabled || providersBackstage.isReadOnly();
  22984. }),
  22985. receivingConfig()
  22986. ].concat(specialisation.toolbarButtonBehaviours))
  22987. });
  22988. };
  22989. var renderToolbarButton = function (spec, providersBackstage) {
  22990. return renderToolbarButtonWith(spec, providersBackstage, []);
  22991. };
  22992. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  22993. return renderCommonToolbarButton(spec, {
  22994. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  22995. getApi: getButtonApi,
  22996. onSetup: spec.onSetup
  22997. }, providersBackstage);
  22998. };
  22999. var renderToolbarToggleButton = function (spec, providersBackstage) {
  23000. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  23001. };
  23002. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  23003. return deepMerge(renderCommonToolbarButton(spec, {
  23004. toolbarButtonBehaviours: [
  23005. Replacing.config({}),
  23006. Toggling.config({
  23007. toggleClass: 'tox-tbtn--enabled',
  23008. aria: { mode: 'pressed' },
  23009. toggleOnExecute: false
  23010. })
  23011. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  23012. getApi: getToggleApi,
  23013. onSetup: spec.onSetup
  23014. }, providersBackstage));
  23015. };
  23016. var fetchChoices = function (getApi, spec, providersBackstage) {
  23017. return function (comp) {
  23018. return Future.nu(function (callback) {
  23019. return spec.fetch(callback);
  23020. }).map(function (items) {
  23021. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  23022. spec.onItemAction(getApi(comp), value);
  23023. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(function () {
  23024. return false;
  23025. }), providersBackstage), {
  23026. movement: deriveMenuMovement(spec.columns, spec.presets),
  23027. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  23028. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
  23029. var numRows = _d.numRows, numColumns = _d.numColumns;
  23030. Keying.setGridSize(comp, numRows, numColumns);
  23031. });
  23032. })])
  23033. })));
  23034. });
  23035. };
  23036. };
  23037. var renderSplitButton = function (spec, sharedBackstage) {
  23038. var _d;
  23039. var displayChannel = generate$1('channel-update-split-dropdown-display');
  23040. var getApi = function (comp) {
  23041. return {
  23042. isDisabled: function () {
  23043. return Disabling.isDisabled(comp);
  23044. },
  23045. setDisabled: function (state) {
  23046. return Disabling.set(comp, state);
  23047. },
  23048. setIconFill: function (id, value) {
  23049. descendant$1(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  23050. set$1(underlinePath, 'fill', value);
  23051. });
  23052. },
  23053. setIconStroke: function (id, value) {
  23054. descendant$1(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  23055. set$1(underlinePath, 'stroke', value);
  23056. });
  23057. },
  23058. setActive: function (state) {
  23059. set$1(comp.element, 'aria-pressed', state);
  23060. descendant$1(comp.element, 'span').each(function (button) {
  23061. comp.getSystem().getByDom(button).each(function (buttonComp) {
  23062. return Toggling.set(buttonComp, state);
  23063. });
  23064. });
  23065. },
  23066. isActive: function () {
  23067. return descendant$1(comp.element, 'span').exists(function (button) {
  23068. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  23069. });
  23070. }
  23071. };
  23072. };
  23073. var editorOffCell = Cell(noop);
  23074. var specialisation = {
  23075. getApi: getApi,
  23076. onSetup: spec.onSetup
  23077. };
  23078. return SplitDropdown.sketch({
  23079. dom: {
  23080. tag: 'div',
  23081. classes: ['tox-split-button'],
  23082. attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  23083. },
  23084. onExecute: function (button) {
  23085. spec.onAction(getApi(button));
  23086. },
  23087. onItemExecute: function (_a, _b, _c) {
  23088. },
  23089. splitDropdownBehaviours: derive$1([
  23090. DisablingConfigs.splitButton(sharedBackstage.providers.isReadOnly),
  23091. receivingConfig(),
  23092. config('split-dropdown-events', [
  23093. run(focusButtonEvent, Focusing.focus),
  23094. onControlAttached(specialisation, editorOffCell),
  23095. onControlDetached(specialisation, editorOffCell)
  23096. ]),
  23097. Unselecting.config({})
  23098. ]),
  23099. eventOrder: (_d = {}, _d[attachedToDom()] = [
  23100. 'alloy.base.behaviour',
  23101. 'split-dropdown-events'
  23102. ], _d),
  23103. toggleClass: 'tox-tbtn--enabled',
  23104. lazySink: sharedBackstage.getSink,
  23105. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  23106. parts: { menu: part(false, spec.columns, spec.presets) },
  23107. components: [
  23108. SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
  23109. toggleClass: 'tox-tbtn--enabled',
  23110. toggleOnExecute: false
  23111. })]), sharedBackstage.providers)),
  23112. SplitDropdown.parts.arrow({
  23113. dom: {
  23114. tag: 'button',
  23115. classes: [
  23116. 'tox-tbtn',
  23117. 'tox-split-button__chevron'
  23118. ],
  23119. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  23120. },
  23121. buttonBehaviours: derive$1([
  23122. DisablingConfigs.splitButton(sharedBackstage.providers.isReadOnly),
  23123. receivingConfig()
  23124. ])
  23125. }),
  23126. SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  23127. ]
  23128. });
  23129. };
  23130. var getFormApi = function (input) {
  23131. return {
  23132. hide: function () {
  23133. return emit(input, sandboxClose());
  23134. },
  23135. getValue: function () {
  23136. return Representing.getValue(input);
  23137. }
  23138. };
  23139. };
  23140. var runOnExecute$1 = function (memInput, original) {
  23141. return run(internalToolbarButtonExecute, function (comp, se) {
  23142. var input = memInput.get(comp);
  23143. var formApi = getFormApi(input);
  23144. original.onAction(formApi, se.event.buttonApi);
  23145. });
  23146. };
  23147. var renderContextButton = function (memInput, button, extras) {
  23148. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  23149. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  23150. type: 'button',
  23151. onAction: function () {
  23152. }
  23153. })));
  23154. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  23155. };
  23156. var renderContextToggleButton = function (memInput, button, extras) {
  23157. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  23158. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  23159. type: 'togglebutton',
  23160. onAction: function () {
  23161. }
  23162. })));
  23163. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  23164. };
  23165. var generateOne$1 = function (memInput, button, providersBackstage) {
  23166. var extras = { backstage: { shared: { providers: providersBackstage } } };
  23167. if (button.type === 'contextformtogglebutton') {
  23168. return renderContextToggleButton(memInput, button, extras);
  23169. } else {
  23170. return renderContextButton(memInput, button, extras);
  23171. }
  23172. };
  23173. var generate$7 = function (memInput, buttons, providersBackstage) {
  23174. var mementos = map(buttons, function (button) {
  23175. return record(generateOne$1(memInput, button, providersBackstage));
  23176. });
  23177. var asSpecs = function () {
  23178. return map(mementos, function (mem) {
  23179. return mem.asSpec();
  23180. });
  23181. };
  23182. var findPrimary = function (compInSystem) {
  23183. return findMap(buttons, function (button, i) {
  23184. if (button.primary) {
  23185. return Optional.from(mementos[i]).bind(function (mem) {
  23186. return mem.getOpt(compInSystem);
  23187. }).filter(not(Disabling.isDisabled));
  23188. } else {
  23189. return Optional.none();
  23190. }
  23191. });
  23192. };
  23193. return {
  23194. asSpecs: asSpecs,
  23195. findPrimary: findPrimary
  23196. };
  23197. };
  23198. var buildInitGroups = function (ctx, providers) {
  23199. var inputAttributes = ctx.label.fold(function () {
  23200. return {};
  23201. }, function (label) {
  23202. return { 'aria-label': label };
  23203. });
  23204. var memInput = record(Input.sketch({
  23205. inputClasses: [
  23206. 'tox-toolbar-textfield',
  23207. 'tox-toolbar-nav-js'
  23208. ],
  23209. data: ctx.initValue(),
  23210. inputAttributes: inputAttributes,
  23211. selectOnFocus: true,
  23212. inputBehaviours: derive$1([Keying.config({
  23213. mode: 'special',
  23214. onEnter: function (input) {
  23215. return commands.findPrimary(input).map(function (primary) {
  23216. emitExecute(primary);
  23217. return true;
  23218. });
  23219. },
  23220. onLeft: function (comp, se) {
  23221. se.cut();
  23222. return Optional.none();
  23223. },
  23224. onRight: function (comp, se) {
  23225. se.cut();
  23226. return Optional.none();
  23227. }
  23228. })])
  23229. }));
  23230. var commands = generate$7(memInput, ctx.commands, providers);
  23231. return [
  23232. {
  23233. title: Optional.none(),
  23234. items: [memInput.asSpec()]
  23235. },
  23236. {
  23237. title: Optional.none(),
  23238. items: commands.asSpecs()
  23239. }
  23240. ];
  23241. };
  23242. var renderContextForm = function (toolbarType, ctx, providers) {
  23243. return renderToolbar({
  23244. type: toolbarType,
  23245. uid: generate$1('context-toolbar'),
  23246. initGroups: buildInitGroups(ctx, providers),
  23247. onEscape: Optional.none,
  23248. cyclicKeying: true,
  23249. providers: providers
  23250. });
  23251. };
  23252. var ContextForm = {
  23253. renderContextForm: renderContextForm,
  23254. buildInitGroups: buildInitGroups
  23255. };
  23256. var getHorizontalBounds = function (contentAreaBox, viewportBounds) {
  23257. var x = Math.max(viewportBounds.x, contentAreaBox.x);
  23258. var contentBoxWidth = contentAreaBox.right - x;
  23259. var maxViewportWidth = viewportBounds.width - (x - viewportBounds.x);
  23260. var width = Math.min(contentBoxWidth, maxViewportWidth);
  23261. return {
  23262. x: x,
  23263. width: width
  23264. };
  23265. };
  23266. var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop) {
  23267. var container = SugarElement.fromDom(editor.getContainer());
  23268. var header = descendant$1(container, '.tox-editor-header').getOr(container);
  23269. var headerBox = box(header);
  23270. var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  23271. var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  23272. if (editor.inline && isToolbarAbove) {
  23273. return {
  23274. y: Math.max(headerBox.bottom, viewportBounds.y),
  23275. bottom: viewportBounds.bottom
  23276. };
  23277. }
  23278. if (editor.inline && !isToolbarAbove) {
  23279. return {
  23280. y: viewportBounds.y,
  23281. bottom: Math.min(headerBox.y, viewportBounds.bottom)
  23282. };
  23283. }
  23284. var containerBounds = box(container);
  23285. if (isToolbarAbove) {
  23286. return {
  23287. y: Math.max(headerBox.bottom, viewportBounds.y),
  23288. bottom: Math.min(containerBounds.bottom, viewportBounds.bottom)
  23289. };
  23290. }
  23291. return {
  23292. y: Math.max(containerBounds.y, viewportBounds.y),
  23293. bottom: Math.min(headerBox.y, viewportBounds.bottom)
  23294. };
  23295. };
  23296. var getContextToolbarBounds = function (editor, sharedBackstage) {
  23297. var viewportBounds = getBounds(window);
  23298. var contentAreaBox = box(SugarElement.fromDom(editor.getContentAreaContainer()));
  23299. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  23300. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  23301. if (editor.inline && !toolbarOrMenubarEnabled) {
  23302. return bounds$1(x, viewportBounds.y, width, viewportBounds.height);
  23303. } else {
  23304. var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  23305. var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop), y = _b.y, bottom = _b.bottom;
  23306. return bounds$1(x, y, width, bottom - y);
  23307. }
  23308. };
  23309. var matchTargetWith = function (elem, candidates) {
  23310. var ctxs = filter(candidates, function (toolbarApi) {
  23311. return toolbarApi.predicate(elem.dom);
  23312. });
  23313. var _a = partition(ctxs, function (t) {
  23314. return t.type === 'contexttoolbar';
  23315. }), pass = _a.pass, fail = _a.fail;
  23316. return {
  23317. contextToolbars: pass,
  23318. contextForms: fail
  23319. };
  23320. };
  23321. var filterByPositionForStartNode = function (toolbars) {
  23322. if (toolbars.length <= 1) {
  23323. return toolbars;
  23324. } else {
  23325. var doesPositionExist = function (value) {
  23326. return exists(toolbars, function (t) {
  23327. return t.position === value;
  23328. });
  23329. };
  23330. var filterToolbarsByPosition = function (value) {
  23331. return filter(toolbars, function (t) {
  23332. return t.position === value;
  23333. });
  23334. };
  23335. var hasSelectionToolbars = doesPositionExist('selection');
  23336. var hasNodeToolbars = doesPositionExist('node');
  23337. if (hasSelectionToolbars || hasNodeToolbars) {
  23338. if (hasNodeToolbars && hasSelectionToolbars) {
  23339. var nodeToolbars = filterToolbarsByPosition('node');
  23340. var selectionToolbars = map(filterToolbarsByPosition('selection'), function (t) {
  23341. return __assign(__assign({}, t), { position: 'node' });
  23342. });
  23343. return nodeToolbars.concat(selectionToolbars);
  23344. } else {
  23345. return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  23346. }
  23347. } else {
  23348. return filterToolbarsByPosition('line');
  23349. }
  23350. }
  23351. };
  23352. var filterByPositionForAncestorNode = function (toolbars) {
  23353. if (toolbars.length <= 1) {
  23354. return toolbars;
  23355. } else {
  23356. var findPosition_1 = function (value) {
  23357. return find(toolbars, function (t) {
  23358. return t.position === value;
  23359. });
  23360. };
  23361. var basePosition = findPosition_1('selection').orThunk(function () {
  23362. return findPosition_1('node');
  23363. }).orThunk(function () {
  23364. return findPosition_1('line');
  23365. }).map(function (t) {
  23366. return t.position;
  23367. });
  23368. return basePosition.fold(function () {
  23369. return [];
  23370. }, function (pos) {
  23371. return filter(toolbars, function (t) {
  23372. return t.position === pos;
  23373. });
  23374. });
  23375. }
  23376. };
  23377. var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
  23378. var nodeMatches = matchTargetWith(elem, nodeCandidates);
  23379. if (nodeMatches.contextForms.length > 0) {
  23380. return Optional.some({
  23381. elem: elem,
  23382. toolbars: [nodeMatches.contextForms[0]]
  23383. });
  23384. } else {
  23385. var editorMatches = matchTargetWith(elem, editorCandidates);
  23386. if (editorMatches.contextForms.length > 0) {
  23387. return Optional.some({
  23388. elem: elem,
  23389. toolbars: [editorMatches.contextForms[0]]
  23390. });
  23391. } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  23392. var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  23393. return Optional.some({
  23394. elem: elem,
  23395. toolbars: toolbars
  23396. });
  23397. } else {
  23398. return Optional.none();
  23399. }
  23400. }
  23401. };
  23402. var matchAncestor = function (isRoot, startNode, scopes) {
  23403. if (isRoot(startNode)) {
  23404. return Optional.none();
  23405. } else {
  23406. return ancestor(startNode, function (ancestorElem) {
  23407. var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
  23408. var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  23409. return toolbars.length > 0 ? Optional.some({
  23410. elem: ancestorElem,
  23411. toolbars: toolbars
  23412. }) : Optional.none();
  23413. }, isRoot);
  23414. }
  23415. };
  23416. var lookup$1 = function (scopes, editor) {
  23417. var rootElem = SugarElement.fromDom(editor.getBody());
  23418. var isRoot = function (elem) {
  23419. return eq$1(elem, rootElem);
  23420. };
  23421. var isOutsideRoot = function (startNode) {
  23422. return !isRoot(startNode) && !contains$2(rootElem, startNode);
  23423. };
  23424. var startNode = SugarElement.fromDom(editor.selection.getNode());
  23425. if (isOutsideRoot(startNode)) {
  23426. return Optional.none();
  23427. }
  23428. return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
  23429. return matchAncestor(isRoot, startNode, scopes);
  23430. });
  23431. };
  23432. var categorise = function (contextToolbars, navigate) {
  23433. var forms = {};
  23434. var inNodeScope = [];
  23435. var inEditorScope = [];
  23436. var formNavigators = {};
  23437. var lookupTable = {};
  23438. var registerForm = function (key, toolbarSpec) {
  23439. var contextForm = getOrDie(createContextForm(toolbarSpec));
  23440. forms[key] = contextForm;
  23441. contextForm.launch.map(function (launch) {
  23442. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), {
  23443. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  23444. onAction: function () {
  23445. navigate(contextForm);
  23446. }
  23447. });
  23448. });
  23449. if (contextForm.scope === 'editor') {
  23450. inEditorScope.push(contextForm);
  23451. } else {
  23452. inNodeScope.push(contextForm);
  23453. }
  23454. lookupTable[key] = contextForm;
  23455. };
  23456. var registerToolbar = function (key, toolbarSpec) {
  23457. createContextToolbar(toolbarSpec).each(function (contextToolbar) {
  23458. if (toolbarSpec.scope === 'editor') {
  23459. inEditorScope.push(contextToolbar);
  23460. } else {
  23461. inNodeScope.push(contextToolbar);
  23462. }
  23463. lookupTable[key] = contextToolbar;
  23464. });
  23465. };
  23466. var keys$1 = keys(contextToolbars);
  23467. each(keys$1, function (key) {
  23468. var toolbarApi = contextToolbars[key];
  23469. if (toolbarApi.type === 'contextform') {
  23470. registerForm(key, toolbarApi);
  23471. } else if (toolbarApi.type === 'contexttoolbar') {
  23472. registerToolbar(key, toolbarApi);
  23473. }
  23474. });
  23475. return {
  23476. forms: forms,
  23477. inNodeScope: inNodeScope,
  23478. inEditorScope: inEditorScope,
  23479. lookupTable: lookupTable,
  23480. formNavigators: formNavigators
  23481. };
  23482. };
  23483. var forwardSlideEvent = generate$1('forward-slide');
  23484. var backSlideEvent = generate$1('backward-slide');
  23485. var changeSlideEvent = generate$1('change-slide-event');
  23486. var resizingClass = 'tox-pop--resizing';
  23487. var renderContextToolbar = function (spec) {
  23488. var stack = Cell([]);
  23489. return InlineView.sketch({
  23490. dom: {
  23491. tag: 'div',
  23492. classes: ['tox-pop']
  23493. },
  23494. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  23495. onShow: function (comp) {
  23496. stack.set([]);
  23497. InlineView.getContent(comp).each(function (c) {
  23498. remove$6(c.element, 'visibility');
  23499. });
  23500. remove$4(comp.element, resizingClass);
  23501. remove$6(comp.element, 'width');
  23502. },
  23503. inlineBehaviours: derive$1([
  23504. config('context-toolbar-events', [
  23505. runOnSource(transitionend(), function (comp, _se) {
  23506. remove$4(comp.element, resizingClass);
  23507. remove$6(comp.element, 'width');
  23508. }),
  23509. run(changeSlideEvent, function (comp, se) {
  23510. remove$6(comp.element, 'width');
  23511. var currentWidth = get$7(comp.element);
  23512. InlineView.setContent(comp, se.event.contents);
  23513. add$2(comp.element, resizingClass);
  23514. var newWidth = get$7(comp.element);
  23515. set$2(comp.element, 'width', currentWidth + 'px');
  23516. InlineView.getContent(comp).each(function (newContents) {
  23517. se.event.focus.bind(function (f) {
  23518. focus$1(f);
  23519. return search(comp.element);
  23520. }).orThunk(function () {
  23521. Keying.focusIn(newContents);
  23522. return active();
  23523. });
  23524. });
  23525. global$2.setTimeout(function () {
  23526. set$2(comp.element, 'width', newWidth + 'px');
  23527. }, 0);
  23528. }),
  23529. run(forwardSlideEvent, function (comp, se) {
  23530. InlineView.getContent(comp).each(function (oldContents) {
  23531. stack.set(stack.get().concat([{
  23532. bar: oldContents,
  23533. focus: active()
  23534. }]));
  23535. });
  23536. emitWith(comp, changeSlideEvent, {
  23537. contents: se.event.forwardContents,
  23538. focus: Optional.none()
  23539. });
  23540. }),
  23541. run(backSlideEvent, function (comp, _se) {
  23542. last(stack.get()).each(function (last) {
  23543. stack.set(stack.get().slice(0, stack.get().length - 1));
  23544. emitWith(comp, changeSlideEvent, {
  23545. contents: premade$1(last.bar),
  23546. focus: last.focus
  23547. });
  23548. });
  23549. })
  23550. ]),
  23551. Keying.config({
  23552. mode: 'special',
  23553. onEscape: function (comp) {
  23554. return last(stack.get()).fold(function () {
  23555. return spec.onEscape();
  23556. }, function (_) {
  23557. emit(comp, backSlideEvent);
  23558. return Optional.some(true);
  23559. });
  23560. }
  23561. })
  23562. ]),
  23563. lazySink: function () {
  23564. return Result.value(spec.sink);
  23565. }
  23566. });
  23567. };
  23568. var generateSelectItems = function (_editor, backstage, spec) {
  23569. var generateItem = function (rawItem, response, disabled, value) {
  23570. var translatedText = backstage.shared.providers.translate(rawItem.title);
  23571. if (rawItem.type === 'separator') {
  23572. return Optional.some({
  23573. type: 'separator',
  23574. text: translatedText
  23575. });
  23576. } else if (rawItem.type === 'submenu') {
  23577. var items = bind(rawItem.getStyleItems(), function (si) {
  23578. return validate(si, response, value);
  23579. });
  23580. if (response === 0 && items.length <= 0) {
  23581. return Optional.none();
  23582. } else {
  23583. return Optional.some({
  23584. type: 'nestedmenuitem',
  23585. text: translatedText,
  23586. disabled: items.length <= 0,
  23587. getSubmenuItems: function () {
  23588. return bind(rawItem.getStyleItems(), function (si) {
  23589. return validate(si, response, value);
  23590. });
  23591. }
  23592. });
  23593. }
  23594. } else {
  23595. return Optional.some(__assign({
  23596. type: 'togglemenuitem',
  23597. text: translatedText,
  23598. icon: rawItem.icon,
  23599. active: rawItem.isSelected(value),
  23600. disabled: disabled,
  23601. onAction: spec.onAction(rawItem)
  23602. }, rawItem.getStylePreview().fold(function () {
  23603. return {};
  23604. }, function (preview) {
  23605. return { meta: { style: preview } };
  23606. })));
  23607. }
  23608. };
  23609. var validate = function (item, response, value) {
  23610. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  23611. if (response === 0) {
  23612. return invalid ? [] : generateItem(item, response, false, value).toArray();
  23613. } else {
  23614. return generateItem(item, response, invalid, value).toArray();
  23615. }
  23616. };
  23617. var validateItems = function (preItems) {
  23618. var value = spec.getCurrentValue();
  23619. var response = spec.shouldHide ? 0 : 1;
  23620. return bind(preItems, function (item) {
  23621. return validate(item, response, value);
  23622. });
  23623. };
  23624. var getFetch = function (backstage, getStyleItems) {
  23625. return function (comp, callback) {
  23626. var preItems = getStyleItems();
  23627. var items = validateItems(preItems);
  23628. var menu = build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  23629. callback(menu);
  23630. };
  23631. };
  23632. return {
  23633. validateItems: validateItems,
  23634. getFetch: getFetch
  23635. };
  23636. };
  23637. var createMenuItems = function (editor, backstage, spec) {
  23638. var dataset = spec.dataset;
  23639. var getStyleItems = dataset.type === 'basic' ? function () {
  23640. return map(dataset.data, function (d) {
  23641. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  23642. });
  23643. } : dataset.getData;
  23644. return {
  23645. items: generateSelectItems(editor, backstage, spec),
  23646. getStyleItems: getStyleItems
  23647. };
  23648. };
  23649. var createSelectButton = function (editor, backstage, spec) {
  23650. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  23651. var getApi = function (comp) {
  23652. return {
  23653. getComponent: function () {
  23654. return comp;
  23655. }
  23656. };
  23657. };
  23658. var onSetup = function (api) {
  23659. spec.setInitialValue.each(function (f) {
  23660. return f(api.getComponent());
  23661. });
  23662. return spec.nodeChangeHandler.map(function (f) {
  23663. var handler = f(api.getComponent());
  23664. editor.on('NodeChange', handler);
  23665. return function () {
  23666. editor.off('NodeChange', handler);
  23667. };
  23668. }).getOr(noop);
  23669. };
  23670. return renderCommonDropdown({
  23671. text: spec.icon.isSome() ? Optional.none() : Optional.some(''),
  23672. icon: spec.icon,
  23673. tooltip: Optional.from(spec.tooltip),
  23674. role: Optional.none(),
  23675. fetch: items.getFetch(backstage, getStyleItems),
  23676. onSetup: onSetup,
  23677. getApi: getApi,
  23678. columns: 1,
  23679. presets: 'normal',
  23680. classes: spec.icon.isSome() ? [] : ['bespoke'],
  23681. dropdownBehaviours: []
  23682. }, 'tox-tbtn', backstage.shared);
  23683. };
  23684. var process = function (rawFormats) {
  23685. return map(rawFormats, function (item) {
  23686. var title = item, format = item;
  23687. var values = item.split('=');
  23688. if (values.length > 1) {
  23689. title = values[0];
  23690. format = values[1];
  23691. }
  23692. return {
  23693. title: title,
  23694. format: format
  23695. };
  23696. });
  23697. };
  23698. var buildBasicStaticDataset = function (data) {
  23699. return {
  23700. type: 'basic',
  23701. data: data
  23702. };
  23703. };
  23704. var Delimiter;
  23705. (function (Delimiter) {
  23706. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  23707. Delimiter[Delimiter['Space'] = 1] = 'Space';
  23708. }(Delimiter || (Delimiter = {})));
  23709. var split = function (rawFormats, delimiter) {
  23710. if (delimiter === Delimiter.SemiColon) {
  23711. return rawFormats.replace(/;$/, '').split(';');
  23712. } else {
  23713. return rawFormats.split(' ');
  23714. }
  23715. };
  23716. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  23717. var rawFormats = editor.getParam(settingName, defaults, 'string');
  23718. var data = process(split(rawFormats, delimiter));
  23719. return {
  23720. type: 'basic',
  23721. data: data
  23722. };
  23723. };
  23724. var alignMenuItems = [
  23725. {
  23726. title: 'Left',
  23727. icon: 'align-left',
  23728. format: 'alignleft',
  23729. command: 'JustifyLeft'
  23730. },
  23731. {
  23732. title: 'Center',
  23733. icon: 'align-center',
  23734. format: 'aligncenter',
  23735. command: 'JustifyCenter'
  23736. },
  23737. {
  23738. title: 'Right',
  23739. icon: 'align-right',
  23740. format: 'alignright',
  23741. command: 'JustifyRight'
  23742. },
  23743. {
  23744. title: 'Justify',
  23745. icon: 'align-justify',
  23746. format: 'alignjustify',
  23747. command: 'JustifyFull'
  23748. }
  23749. ];
  23750. var getSpec = function (editor) {
  23751. var getMatchingValue = function () {
  23752. return find(alignMenuItems, function (item) {
  23753. return editor.formatter.match(item.format);
  23754. });
  23755. };
  23756. var isSelectedFor = function (format) {
  23757. return function () {
  23758. return editor.formatter.match(format);
  23759. };
  23760. };
  23761. var getPreviewFor = function (_format) {
  23762. return function () {
  23763. return Optional.none();
  23764. };
  23765. };
  23766. var updateSelectMenuIcon = function (comp) {
  23767. var match = getMatchingValue();
  23768. var alignment = match.fold(function () {
  23769. return 'left';
  23770. }, function (item) {
  23771. return item.title.toLowerCase();
  23772. });
  23773. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  23774. };
  23775. var nodeChangeHandler = Optional.some(function (comp) {
  23776. return function () {
  23777. return updateSelectMenuIcon(comp);
  23778. };
  23779. });
  23780. var setInitialValue = Optional.some(function (comp) {
  23781. return updateSelectMenuIcon(comp);
  23782. });
  23783. var dataset = buildBasicStaticDataset(alignMenuItems);
  23784. var onAction = function (rawItem) {
  23785. return function () {
  23786. return find(alignMenuItems, function (item) {
  23787. return item.format === rawItem.format;
  23788. }).each(function (item) {
  23789. return editor.execCommand(item.command);
  23790. });
  23791. };
  23792. };
  23793. return {
  23794. tooltip: 'Align',
  23795. icon: Optional.some('align-left'),
  23796. isSelectedFor: isSelectedFor,
  23797. getCurrentValue: Optional.none,
  23798. getPreviewFor: getPreviewFor,
  23799. onAction: onAction,
  23800. setInitialValue: setInitialValue,
  23801. nodeChangeHandler: nodeChangeHandler,
  23802. dataset: dataset,
  23803. shouldHide: false,
  23804. isInvalid: function (item) {
  23805. return !editor.formatter.canApply(item.format);
  23806. }
  23807. };
  23808. };
  23809. var createAlignSelect = function (editor, backstage) {
  23810. return createSelectButton(editor, backstage, getSpec(editor));
  23811. };
  23812. var alignSelectMenu = function (editor, backstage) {
  23813. var menuItems = createMenuItems(editor, backstage, getSpec(editor));
  23814. editor.ui.registry.addNestedMenuItem('align', {
  23815. text: backstage.shared.providers.translate('Align'),
  23816. getSubmenuItems: function () {
  23817. return menuItems.items.validateItems(menuItems.getStyleItems());
  23818. }
  23819. });
  23820. };
  23821. var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
  23822. var systemStackFonts = [
  23823. '-apple-system',
  23824. 'Segoe UI',
  23825. 'Roboto',
  23826. 'Helvetica Neue',
  23827. 'sans-serif'
  23828. ];
  23829. var splitFonts = function (fontFamily) {
  23830. var fonts = fontFamily.split(/\s*,\s*/);
  23831. return map(fonts, function (font) {
  23832. return font.replace(/^['"]+|['"]+$/g, '');
  23833. });
  23834. };
  23835. var isSystemFontStack = function (fontFamily) {
  23836. var matchesSystemStack = function () {
  23837. var fonts = splitFonts(fontFamily.toLowerCase());
  23838. return forall(systemStackFonts, function (font) {
  23839. return fonts.indexOf(font.toLowerCase()) > -1;
  23840. });
  23841. };
  23842. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  23843. };
  23844. var getSpec$1 = function (editor) {
  23845. var getMatchingValue = function () {
  23846. var getFirstFont = function (fontFamily) {
  23847. return fontFamily ? splitFonts(fontFamily)[0] : '';
  23848. };
  23849. var fontFamily = editor.queryCommandValue('FontName');
  23850. var items = dataset.data;
  23851. var font = fontFamily ? fontFamily.toLowerCase() : '';
  23852. var matchOpt = find(items, function (item) {
  23853. var format = item.format;
  23854. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  23855. }).orThunk(function () {
  23856. if (isSystemFontStack(font)) {
  23857. return Optional.from({
  23858. title: 'System Font',
  23859. format: font
  23860. });
  23861. } else {
  23862. return Optional.none();
  23863. }
  23864. });
  23865. return {
  23866. matchOpt: matchOpt,
  23867. font: fontFamily
  23868. };
  23869. };
  23870. var isSelectedFor = function (item) {
  23871. return function (valueOpt) {
  23872. return valueOpt.exists(function (value) {
  23873. return value.format === item;
  23874. });
  23875. };
  23876. };
  23877. var getCurrentValue = function () {
  23878. var matchOpt = getMatchingValue().matchOpt;
  23879. return matchOpt;
  23880. };
  23881. var getPreviewFor = function (item) {
  23882. return function () {
  23883. return Optional.some({
  23884. tag: 'div',
  23885. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  23886. });
  23887. };
  23888. };
  23889. var onAction = function (rawItem) {
  23890. return function () {
  23891. editor.undoManager.transact(function () {
  23892. editor.focus();
  23893. editor.execCommand('FontName', false, rawItem.format);
  23894. });
  23895. };
  23896. };
  23897. var updateSelectMenuText = function (comp) {
  23898. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  23899. var text = matchOpt.fold(function () {
  23900. return font;
  23901. }, function (item) {
  23902. return item.title;
  23903. });
  23904. emitWith(comp, updateMenuText, { text: text });
  23905. };
  23906. var nodeChangeHandler = Optional.some(function (comp) {
  23907. return function () {
  23908. return updateSelectMenuText(comp);
  23909. };
  23910. });
  23911. var setInitialValue = Optional.some(function (comp) {
  23912. return updateSelectMenuText(comp);
  23913. });
  23914. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  23915. return {
  23916. tooltip: 'Fonts',
  23917. icon: Optional.none(),
  23918. isSelectedFor: isSelectedFor,
  23919. getCurrentValue: getCurrentValue,
  23920. getPreviewFor: getPreviewFor,
  23921. onAction: onAction,
  23922. setInitialValue: setInitialValue,
  23923. nodeChangeHandler: nodeChangeHandler,
  23924. dataset: dataset,
  23925. shouldHide: false,
  23926. isInvalid: function () {
  23927. return false;
  23928. }
  23929. };
  23930. };
  23931. var createFontSelect = function (editor, backstage) {
  23932. return createSelectButton(editor, backstage, getSpec$1(editor));
  23933. };
  23934. var fontSelectMenu = function (editor, backstage) {
  23935. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  23936. editor.ui.registry.addNestedMenuItem('fontformats', {
  23937. text: backstage.shared.providers.translate('Fonts'),
  23938. getSubmenuItems: function () {
  23939. return menuItems.items.validateItems(menuItems.getStyleItems());
  23940. }
  23941. });
  23942. };
  23943. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  23944. var legacyFontSizes = {
  23945. '8pt': '1',
  23946. '10pt': '2',
  23947. '12pt': '3',
  23948. '14pt': '4',
  23949. '18pt': '5',
  23950. '24pt': '6',
  23951. '36pt': '7'
  23952. };
  23953. var round$1 = function (number, precision) {
  23954. var factor = Math.pow(10, precision);
  23955. return Math.round(number * factor) / factor;
  23956. };
  23957. var toPt = function (fontSize, precision) {
  23958. if (/[0-9.]+px$/.test(fontSize)) {
  23959. return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  23960. }
  23961. return fontSize;
  23962. };
  23963. var toLegacy = function (fontSize) {
  23964. return get(legacyFontSizes, fontSize).getOr('');
  23965. };
  23966. var getSpec$2 = function (editor) {
  23967. var getMatchingValue = function () {
  23968. var matchOpt = Optional.none();
  23969. var items = dataset.data;
  23970. var fontSize = editor.queryCommandValue('FontSize');
  23971. if (fontSize) {
  23972. var _loop_1 = function (precision) {
  23973. var pt = toPt(fontSize, precision);
  23974. var legacy = toLegacy(pt);
  23975. matchOpt = find(items, function (item) {
  23976. return item.format === fontSize || item.format === pt || item.format === legacy;
  23977. });
  23978. };
  23979. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  23980. _loop_1(precision);
  23981. }
  23982. }
  23983. return {
  23984. matchOpt: matchOpt,
  23985. size: fontSize
  23986. };
  23987. };
  23988. var isSelectedFor = function (item) {
  23989. return function (valueOpt) {
  23990. return valueOpt.exists(function (value) {
  23991. return value.format === item;
  23992. });
  23993. };
  23994. };
  23995. var getCurrentValue = function () {
  23996. var matchOpt = getMatchingValue().matchOpt;
  23997. return matchOpt;
  23998. };
  23999. var getPreviewFor = constant(Optional.none);
  24000. var onAction = function (rawItem) {
  24001. return function () {
  24002. editor.undoManager.transact(function () {
  24003. editor.focus();
  24004. editor.execCommand('FontSize', false, rawItem.format);
  24005. });
  24006. };
  24007. };
  24008. var updateSelectMenuText = function (comp) {
  24009. var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  24010. var text = matchOpt.fold(function () {
  24011. return size;
  24012. }, function (match) {
  24013. return match.title;
  24014. });
  24015. emitWith(comp, updateMenuText, { text: text });
  24016. };
  24017. var nodeChangeHandler = Optional.some(function (comp) {
  24018. return function () {
  24019. return updateSelectMenuText(comp);
  24020. };
  24021. });
  24022. var setInitialValue = Optional.some(function (comp) {
  24023. return updateSelectMenuText(comp);
  24024. });
  24025. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  24026. return {
  24027. tooltip: 'Font sizes',
  24028. icon: Optional.none(),
  24029. isSelectedFor: isSelectedFor,
  24030. getPreviewFor: getPreviewFor,
  24031. getCurrentValue: getCurrentValue,
  24032. onAction: onAction,
  24033. setInitialValue: setInitialValue,
  24034. nodeChangeHandler: nodeChangeHandler,
  24035. dataset: dataset,
  24036. shouldHide: false,
  24037. isInvalid: function () {
  24038. return false;
  24039. }
  24040. };
  24041. };
  24042. var createFontsizeSelect = function (editor, backstage) {
  24043. return createSelectButton(editor, backstage, getSpec$2(editor));
  24044. };
  24045. var fontsizeSelectMenu = function (editor, backstage) {
  24046. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  24047. editor.ui.registry.addNestedMenuItem('fontsizes', {
  24048. text: 'Font sizes',
  24049. getSubmenuItems: function () {
  24050. return menuItems.items.validateItems(menuItems.getStyleItems());
  24051. }
  24052. });
  24053. };
  24054. var findNearest = function (editor, getStyles, parents) {
  24055. var styles = getStyles();
  24056. return findMap(parents, function (parent) {
  24057. return find(styles, function (fmt) {
  24058. return editor.formatter.matchNode(parent, fmt.format);
  24059. });
  24060. }).orThunk(function () {
  24061. if (editor.formatter.match('p')) {
  24062. return Optional.some({
  24063. title: 'Paragraph',
  24064. format: 'p'
  24065. });
  24066. }
  24067. return Optional.none();
  24068. });
  24069. };
  24070. var getCurrentSelectionParents = function (editor) {
  24071. var currentNode = editor.selection.getStart(true) || editor.getBody();
  24072. return editor.dom.getParents(currentNode, function () {
  24073. return true;
  24074. }, editor.getBody());
  24075. };
  24076. var revocable = function (doRevoke) {
  24077. var subject = Cell(Optional.none());
  24078. var revoke = function () {
  24079. return subject.get().each(doRevoke);
  24080. };
  24081. var clear = function () {
  24082. revoke();
  24083. subject.set(Optional.none());
  24084. };
  24085. var isSet = function () {
  24086. return subject.get().isSome();
  24087. };
  24088. var set = function (s) {
  24089. revoke();
  24090. subject.set(Optional.some(s));
  24091. };
  24092. return {
  24093. clear: clear,
  24094. isSet: isSet,
  24095. set: set
  24096. };
  24097. };
  24098. var destroyable = function () {
  24099. return revocable(function (s) {
  24100. return s.destroy();
  24101. });
  24102. };
  24103. var unbindable = function () {
  24104. return revocable(function (s) {
  24105. return s.unbind();
  24106. });
  24107. };
  24108. var value$3 = function () {
  24109. var subject = Cell(Optional.none());
  24110. var clear = function () {
  24111. return subject.set(Optional.none());
  24112. };
  24113. var set = function (s) {
  24114. return subject.set(Optional.some(s));
  24115. };
  24116. var isSet = function () {
  24117. return subject.get().isSome();
  24118. };
  24119. var on = function (f) {
  24120. return subject.get().each(f);
  24121. };
  24122. return {
  24123. clear: clear,
  24124. set: set,
  24125. isSet: isSet,
  24126. on: on
  24127. };
  24128. };
  24129. var onSetupFormatToggle = function (editor, name) {
  24130. return function (api) {
  24131. var boundCallback = unbindable();
  24132. var init = function () {
  24133. api.setActive(editor.formatter.match(name));
  24134. var binding = editor.formatter.formatChanged(name, api.setActive);
  24135. boundCallback.set(binding);
  24136. };
  24137. editor.initialized ? init() : editor.on('init', init);
  24138. return boundCallback.clear;
  24139. };
  24140. };
  24141. var onActionToggleFormat = function (editor) {
  24142. return function (rawItem) {
  24143. return function () {
  24144. editor.undoManager.transact(function () {
  24145. editor.focus();
  24146. editor.execCommand('mceToggleFormat', false, rawItem.format);
  24147. });
  24148. };
  24149. };
  24150. };
  24151. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  24152. var getSpec$3 = function (editor) {
  24153. var getMatchingValue = function (nodeChangeEvent) {
  24154. return findNearest(editor, function () {
  24155. return dataset.data;
  24156. }, nodeChangeEvent);
  24157. };
  24158. var isSelectedFor = function (format) {
  24159. return function () {
  24160. return editor.formatter.match(format);
  24161. };
  24162. };
  24163. var getPreviewFor = function (format) {
  24164. return function () {
  24165. var fmt = editor.formatter.get(format);
  24166. return Optional.some({
  24167. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  24168. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  24169. });
  24170. };
  24171. };
  24172. var updateSelectMenuText = function (parents, comp) {
  24173. var detectedFormat = getMatchingValue(parents);
  24174. var text = detectedFormat.fold(function () {
  24175. return 'Paragraph';
  24176. }, function (fmt) {
  24177. return fmt.title;
  24178. });
  24179. emitWith(comp, updateMenuText, { text: text });
  24180. };
  24181. var nodeChangeHandler = Optional.some(function (comp) {
  24182. return function (e) {
  24183. return updateSelectMenuText(e.parents, comp);
  24184. };
  24185. });
  24186. var setInitialValue = Optional.some(function (comp) {
  24187. var parents = getCurrentSelectionParents(editor);
  24188. updateSelectMenuText(parents, comp);
  24189. });
  24190. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  24191. return {
  24192. tooltip: 'Blocks',
  24193. icon: Optional.none(),
  24194. isSelectedFor: isSelectedFor,
  24195. getCurrentValue: Optional.none,
  24196. getPreviewFor: getPreviewFor,
  24197. onAction: onActionToggleFormat(editor),
  24198. setInitialValue: setInitialValue,
  24199. nodeChangeHandler: nodeChangeHandler,
  24200. dataset: dataset,
  24201. shouldHide: false,
  24202. isInvalid: function (item) {
  24203. return !editor.formatter.canApply(item.format);
  24204. }
  24205. };
  24206. };
  24207. var createFormatSelect = function (editor, backstage) {
  24208. return createSelectButton(editor, backstage, getSpec$3(editor));
  24209. };
  24210. var formatSelectMenu = function (editor, backstage) {
  24211. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  24212. editor.ui.registry.addNestedMenuItem('blockformats', {
  24213. text: 'Blocks',
  24214. getSubmenuItems: function () {
  24215. return menuItems.items.validateItems(menuItems.getStyleItems());
  24216. }
  24217. });
  24218. };
  24219. var getSpec$4 = function (editor, dataset) {
  24220. var isSelectedFor = function (format) {
  24221. return function () {
  24222. return editor.formatter.match(format);
  24223. };
  24224. };
  24225. var getPreviewFor = function (format) {
  24226. return function () {
  24227. var fmt = editor.formatter.get(format);
  24228. return fmt !== undefined ? Optional.some({
  24229. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  24230. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  24231. }) : Optional.none();
  24232. };
  24233. };
  24234. var updateSelectMenuText = function (parents, comp) {
  24235. var getFormatItems = function (fmt) {
  24236. var subs = fmt.items;
  24237. return subs !== undefined && subs.length > 0 ? bind(subs, getFormatItems) : [{
  24238. title: fmt.title,
  24239. format: fmt.format
  24240. }];
  24241. };
  24242. var flattenedItems = bind(getStyleFormats(editor), getFormatItems);
  24243. var detectedFormat = findNearest(editor, function () {
  24244. return flattenedItems;
  24245. }, parents);
  24246. var text = detectedFormat.fold(function () {
  24247. return 'Paragraph';
  24248. }, function (fmt) {
  24249. return fmt.title;
  24250. });
  24251. emitWith(comp, updateMenuText, { text: text });
  24252. };
  24253. var nodeChangeHandler = Optional.some(function (comp) {
  24254. return function (e) {
  24255. return updateSelectMenuText(e.parents, comp);
  24256. };
  24257. });
  24258. var setInitialValue = Optional.some(function (comp) {
  24259. var parents = getCurrentSelectionParents(editor);
  24260. updateSelectMenuText(parents, comp);
  24261. });
  24262. return {
  24263. tooltip: 'Formats',
  24264. icon: Optional.none(),
  24265. isSelectedFor: isSelectedFor,
  24266. getCurrentValue: Optional.none,
  24267. getPreviewFor: getPreviewFor,
  24268. onAction: onActionToggleFormat(editor),
  24269. setInitialValue: setInitialValue,
  24270. nodeChangeHandler: nodeChangeHandler,
  24271. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  24272. isInvalid: function (item) {
  24273. return !editor.formatter.canApply(item.format);
  24274. },
  24275. dataset: dataset
  24276. };
  24277. };
  24278. var createStyleSelect = function (editor, backstage) {
  24279. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  24280. return createSelectButton(editor, backstage, getSpec$4(editor, dataset));
  24281. };
  24282. var styleSelectMenu = function (editor, backstage) {
  24283. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  24284. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor, dataset));
  24285. editor.ui.registry.addNestedMenuItem('formats', {
  24286. text: 'Formats',
  24287. getSubmenuItems: function () {
  24288. return menuItems.items.validateItems(menuItems.getStyleItems());
  24289. }
  24290. });
  24291. };
  24292. var defaultToolbar = [
  24293. {
  24294. name: 'history',
  24295. items: [
  24296. 'undo',
  24297. 'redo'
  24298. ]
  24299. },
  24300. {
  24301. name: 'styles',
  24302. items: ['styleselect']
  24303. },
  24304. {
  24305. name: 'formatting',
  24306. items: [
  24307. 'bold',
  24308. 'italic'
  24309. ]
  24310. },
  24311. {
  24312. name: 'alignment',
  24313. items: [
  24314. 'alignleft',
  24315. 'aligncenter',
  24316. 'alignright',
  24317. 'alignjustify'
  24318. ]
  24319. },
  24320. {
  24321. name: 'indentation',
  24322. items: [
  24323. 'outdent',
  24324. 'indent'
  24325. ]
  24326. },
  24327. {
  24328. name: 'permanent pen',
  24329. items: ['permanentpen']
  24330. },
  24331. {
  24332. name: 'comments',
  24333. items: ['addcomment']
  24334. }
  24335. ];
  24336. var renderFromBridge = function (bridgeBuilder, render) {
  24337. return function (spec, extras, editor) {
  24338. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  24339. return formatError(errInfo);
  24340. }).getOrDie();
  24341. return render(internal, extras, editor);
  24342. };
  24343. };
  24344. var types = {
  24345. button: renderFromBridge(createToolbarButton, function (s, extras) {
  24346. return renderToolbarButton(s, extras.backstage.shared.providers);
  24347. }),
  24348. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  24349. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  24350. }),
  24351. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  24352. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none());
  24353. }),
  24354. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  24355. return renderSplitButton(s, extras.backstage.shared);
  24356. }),
  24357. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  24358. var _a;
  24359. var buttons = editor.ui.registry.getAll().buttons;
  24360. var identify = function (toolbar) {
  24361. return identifyButtons(editor, {
  24362. buttons: buttons,
  24363. toolbar: toolbar,
  24364. allowToolbarGroups: false
  24365. }, extras, Optional.none());
  24366. };
  24367. var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  24368. switch (getToolbarMode(editor)) {
  24369. case ToolbarMode.floating:
  24370. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  24371. default:
  24372. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  24373. }
  24374. }),
  24375. styleSelectButton: function (editor, extras) {
  24376. return createStyleSelect(editor, extras.backstage);
  24377. },
  24378. fontsizeSelectButton: function (editor, extras) {
  24379. return createFontsizeSelect(editor, extras.backstage);
  24380. },
  24381. fontSelectButton: function (editor, extras) {
  24382. return createFontSelect(editor, extras.backstage);
  24383. },
  24384. formatButton: function (editor, extras) {
  24385. return createFormatSelect(editor, extras.backstage);
  24386. },
  24387. alignMenuButton: function (editor, extras) {
  24388. return createAlignSelect(editor, extras.backstage);
  24389. }
  24390. };
  24391. var extractFrom = function (spec, extras, editor) {
  24392. return get(types, spec.type).fold(function () {
  24393. console.error('skipping button defined by', spec);
  24394. return Optional.none();
  24395. }, function (render) {
  24396. return Optional.some(render(spec, extras, editor));
  24397. });
  24398. };
  24399. var bespokeButtons = {
  24400. styleselect: types.styleSelectButton,
  24401. fontsizeselect: types.fontsizeSelectButton,
  24402. fontselect: types.fontSelectButton,
  24403. formatselect: types.formatButton,
  24404. align: types.alignMenuButton
  24405. };
  24406. var removeUnusedDefaults = function (buttons) {
  24407. var filteredItemGroups = map(defaultToolbar, function (group) {
  24408. var items = filter(group.items, function (subItem) {
  24409. return has(buttons, subItem) || has(bespokeButtons, subItem);
  24410. });
  24411. return {
  24412. name: group.name,
  24413. items: items
  24414. };
  24415. });
  24416. return filter(filteredItemGroups, function (group) {
  24417. return group.items.length > 0;
  24418. });
  24419. };
  24420. var convertStringToolbar = function (strToolbar) {
  24421. var groupsStrings = strToolbar.split('|');
  24422. return map(groupsStrings, function (g) {
  24423. return { items: g.trim().split(' ') };
  24424. });
  24425. };
  24426. var isToolbarGroupSettingArray = function (toolbar) {
  24427. return isArrayOf(toolbar, function (t) {
  24428. return has(t, 'name') && has(t, 'items');
  24429. });
  24430. };
  24431. var createToolbar = function (toolbarConfig) {
  24432. var toolbar = toolbarConfig.toolbar;
  24433. var buttons = toolbarConfig.buttons;
  24434. if (toolbar === false) {
  24435. return [];
  24436. } else if (toolbar === undefined || toolbar === true) {
  24437. return removeUnusedDefaults(buttons);
  24438. } else if (isString(toolbar)) {
  24439. return convertStringToolbar(toolbar);
  24440. } else if (isToolbarGroupSettingArray(toolbar)) {
  24441. return toolbar;
  24442. } else {
  24443. console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  24444. return [];
  24445. }
  24446. };
  24447. var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  24448. return get(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  24449. return prefixes.bind(function (ps) {
  24450. return findMap(ps, function (prefix) {
  24451. return get(buttons, prefix + toolbarItem.toLowerCase());
  24452. });
  24453. });
  24454. }).fold(function () {
  24455. return get(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  24456. return r(editor, extras);
  24457. }).orThunk(function () {
  24458. return Optional.none();
  24459. });
  24460. }, function (spec) {
  24461. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  24462. console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  24463. return Optional.none();
  24464. } else {
  24465. return extractFrom(spec, extras, editor);
  24466. }
  24467. });
  24468. };
  24469. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  24470. var toolbarGroups = createToolbar(toolbarConfig);
  24471. var groups = map(toolbarGroups, function (group) {
  24472. var items = bind(group.items, function (toolbarItem) {
  24473. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  24474. });
  24475. return {
  24476. title: Optional.from(editor.translate(group.name)),
  24477. items: items
  24478. };
  24479. });
  24480. return filter(groups, function (group) {
  24481. return group.items.length > 0;
  24482. });
  24483. };
  24484. var bubbleSize = 12;
  24485. var bubbleAlignments$1 = {
  24486. valignCentre: [],
  24487. alignCentre: [],
  24488. alignLeft: ['tox-pop--align-left'],
  24489. alignRight: ['tox-pop--align-right'],
  24490. right: ['tox-pop--right'],
  24491. left: ['tox-pop--left'],
  24492. bottom: ['tox-pop--bottom'],
  24493. top: ['tox-pop--top']
  24494. };
  24495. var anchorOverrides = {
  24496. maxHeightFunction: expandable(),
  24497. maxWidthFunction: expandable$1()
  24498. };
  24499. var desktopAnchorSpecLayouts = {
  24500. onLtr: function () {
  24501. return [
  24502. north$1,
  24503. south$1,
  24504. northeast$1,
  24505. southeast$1,
  24506. northwest$1,
  24507. southwest$1,
  24508. north$3,
  24509. south$3,
  24510. northeast$3,
  24511. southeast$3,
  24512. northwest$3,
  24513. southwest$3
  24514. ];
  24515. },
  24516. onRtl: function () {
  24517. return [
  24518. north$1,
  24519. south$1,
  24520. northwest$1,
  24521. southwest$1,
  24522. northeast$1,
  24523. southeast$1,
  24524. north$3,
  24525. south$3,
  24526. northwest$3,
  24527. southwest$3,
  24528. northeast$3,
  24529. southeast$3
  24530. ];
  24531. }
  24532. };
  24533. var mobileAnchorSpecLayouts = {
  24534. onLtr: function () {
  24535. return [
  24536. south$1,
  24537. southeast$1,
  24538. southwest$1,
  24539. northeast$1,
  24540. northwest$1,
  24541. north$1,
  24542. north$3,
  24543. south$3,
  24544. northeast$3,
  24545. southeast$3,
  24546. northwest$3,
  24547. southwest$3
  24548. ];
  24549. },
  24550. onRtl: function () {
  24551. return [
  24552. south$1,
  24553. southwest$1,
  24554. southeast$1,
  24555. northwest$1,
  24556. northeast$1,
  24557. north$1,
  24558. north$3,
  24559. south$3,
  24560. northwest$3,
  24561. southwest$3,
  24562. northeast$3,
  24563. southeast$3
  24564. ];
  24565. }
  24566. };
  24567. var getAnchorLayout = function (position, isTouch) {
  24568. if (position === 'line') {
  24569. return {
  24570. bubble: nu$8(bubbleSize, 0, bubbleAlignments$1),
  24571. layouts: {
  24572. onLtr: function () {
  24573. return [east$1];
  24574. },
  24575. onRtl: function () {
  24576. return [west$1];
  24577. }
  24578. },
  24579. overrides: anchorOverrides
  24580. };
  24581. } else {
  24582. return {
  24583. bubble: nu$8(0, bubbleSize, bubbleAlignments$1),
  24584. layouts: isTouch ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts,
  24585. overrides: anchorOverrides
  24586. };
  24587. }
  24588. };
  24589. var register$4 = function (editor, registryContextToolbars, sink, extras) {
  24590. var isTouch = detect$3().deviceType.isTouch;
  24591. var contextbar = build$1(renderContextToolbar({
  24592. sink: sink,
  24593. onEscape: function () {
  24594. editor.focus();
  24595. return Optional.some(true);
  24596. }
  24597. }));
  24598. var getBounds = function () {
  24599. return getContextToolbarBounds(editor, extras.backstage.shared);
  24600. };
  24601. var isRangeOverlapping = function (aTop, aBottom, bTop, bBottom) {
  24602. return Math.max(aTop, bTop) <= Math.min(aBottom, bBottom);
  24603. };
  24604. var getLastElementVerticalBound = function () {
  24605. var nodeBounds = lastElement.get().filter(function (ele) {
  24606. return inBody(SugarElement.fromDom(ele));
  24607. }).map(function (ele) {
  24608. return ele.getBoundingClientRect();
  24609. }).getOrThunk(function () {
  24610. return editor.selection.getRng().getBoundingClientRect();
  24611. });
  24612. var diffTop = editor.inline ? get$8().top : absolute$1(SugarElement.fromDom(editor.getBody())).y;
  24613. return {
  24614. y: nodeBounds.top + diffTop,
  24615. bottom: nodeBounds.bottom + diffTop
  24616. };
  24617. };
  24618. var shouldContextToolbarHide = function () {
  24619. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24620. return true;
  24621. }
  24622. var lastElementBounds = getLastElementVerticalBound();
  24623. var contextToolbarBounds = getBounds();
  24624. return !isRangeOverlapping(lastElementBounds.y, lastElementBounds.bottom, contextToolbarBounds.y, contextToolbarBounds.bottom);
  24625. };
  24626. var forceHide = function () {
  24627. InlineView.hide(contextbar);
  24628. };
  24629. var hideOrRepositionIfNecessary = function () {
  24630. lastAnchor.get().each(function (anchor) {
  24631. var contextBarEle = contextbar.element;
  24632. remove$6(contextBarEle, 'display');
  24633. if (shouldContextToolbarHide()) {
  24634. set$2(contextBarEle, 'display', 'none');
  24635. } else {
  24636. Positioning.positionWithinBounds(sink, anchor, contextbar, Optional.some(getBounds()));
  24637. }
  24638. });
  24639. };
  24640. var lastAnchor = Cell(Optional.none());
  24641. var lastElement = Cell(Optional.none());
  24642. var timer = Cell(null);
  24643. var wrapInPopDialog = function (toolbarSpec) {
  24644. return {
  24645. dom: {
  24646. tag: 'div',
  24647. classes: ['tox-pop__dialog']
  24648. },
  24649. components: [toolbarSpec],
  24650. behaviours: derive$1([
  24651. Keying.config({ mode: 'acyclic' }),
  24652. config('pop-dialog-wrap-events', [
  24653. runOnAttached(function (comp) {
  24654. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  24655. return Keying.focusIn(comp);
  24656. });
  24657. }),
  24658. runOnDetached(function (_comp) {
  24659. editor.shortcuts.remove('ctrl+F9');
  24660. })
  24661. ])
  24662. ])
  24663. };
  24664. };
  24665. var getScopes = cached(function () {
  24666. return categorise(registryContextToolbars, function (toolbarApi) {
  24667. var alloySpec = buildToolbar([toolbarApi]);
  24668. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  24669. });
  24670. });
  24671. var buildContextToolbarGroups = function (allButtons, ctx) {
  24672. return identifyButtons(editor, {
  24673. buttons: allButtons,
  24674. toolbar: ctx.items,
  24675. allowToolbarGroups: false
  24676. }, extras, Optional.some(['form:']));
  24677. };
  24678. var buildContextMenuGroups = function (ctx, providers) {
  24679. return ContextForm.buildInitGroups(ctx, providers);
  24680. };
  24681. var buildToolbar = function (toolbars) {
  24682. var buttons = editor.ui.registry.getAll().buttons;
  24683. var scopes = getScopes();
  24684. var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  24685. var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  24686. var initGroups = flatten(map(toolbars, function (ctx) {
  24687. return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextMenuGroups(ctx, extras.backstage.shared.providers);
  24688. }));
  24689. return renderToolbar({
  24690. type: toolbarType,
  24691. uid: generate$1('context-toolbar'),
  24692. initGroups: initGroups,
  24693. onEscape: Optional.none,
  24694. cyclicKeying: true,
  24695. providers: extras.backstage.shared.providers
  24696. });
  24697. };
  24698. editor.on(showContextToolbarEvent, function (e) {
  24699. var scopes = getScopes();
  24700. get(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  24701. launchContext([ctx], e.target === editor ? Optional.none() : Optional.some(e));
  24702. InlineView.getContent(contextbar).each(Keying.focusIn);
  24703. });
  24704. });
  24705. var getAnchor = function (position, element) {
  24706. var anchorage = position === 'node' ? extras.backstage.shared.anchors.node(element) : extras.backstage.shared.anchors.cursor();
  24707. return deepMerge(anchorage, getAnchorLayout(position, isTouch()));
  24708. };
  24709. var launchContext = function (toolbarApi, elem) {
  24710. clearTimer();
  24711. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24712. return;
  24713. }
  24714. var toolbarSpec = buildToolbar(toolbarApi);
  24715. var sElem = elem.map(SugarElement.fromDom);
  24716. var anchor = getAnchor(toolbarApi[0].position, sElem);
  24717. lastAnchor.set(Optional.some(anchor));
  24718. lastElement.set(elem);
  24719. var contextBarEle = contextbar.element;
  24720. remove$6(contextBarEle, 'display');
  24721. InlineView.showWithinBounds(contextbar, anchor, wrapInPopDialog(toolbarSpec), function () {
  24722. return Optional.some(getBounds());
  24723. });
  24724. if (shouldContextToolbarHide()) {
  24725. set$2(contextBarEle, 'display', 'none');
  24726. }
  24727. };
  24728. var launchContextToolbar = function () {
  24729. if (!editor.hasFocus()) {
  24730. return;
  24731. }
  24732. var scopes = getScopes();
  24733. lookup$1(scopes, editor).fold(function () {
  24734. lastAnchor.set(Optional.none());
  24735. InlineView.hide(contextbar);
  24736. }, function (info) {
  24737. launchContext(info.toolbars, Optional.some(info.elem.dom));
  24738. });
  24739. };
  24740. var clearTimer = function () {
  24741. var current = timer.get();
  24742. if (current !== null) {
  24743. global$2.clearTimeout(current);
  24744. timer.set(null);
  24745. }
  24746. };
  24747. var resetTimer = function (t) {
  24748. clearTimer();
  24749. timer.set(t);
  24750. };
  24751. editor.on('init', function () {
  24752. editor.on(hideContextToolbarEvent, forceHide);
  24753. editor.on('ScrollContent ScrollWindow longpress', hideOrRepositionIfNecessary);
  24754. editor.on('click keyup focus SetContent ObjectResized ResizeEditor', function () {
  24755. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24756. });
  24757. editor.on('focusout', function (_e) {
  24758. global$2.setEditorTimeout(editor, function () {
  24759. if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
  24760. lastAnchor.set(Optional.none());
  24761. InlineView.hide(contextbar);
  24762. }
  24763. }, 0);
  24764. });
  24765. editor.on('SwitchMode', function () {
  24766. if (editor.mode.isReadOnly()) {
  24767. lastAnchor.set(Optional.none());
  24768. InlineView.hide(contextbar);
  24769. }
  24770. });
  24771. editor.on('NodeChange', function (_e) {
  24772. search(contextbar.element).fold(function () {
  24773. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24774. }, function (_) {
  24775. });
  24776. });
  24777. });
  24778. };
  24779. var setup$3 = function (editor, mothership, uiMothership) {
  24780. var broadcastEvent = function (name, evt) {
  24781. each([
  24782. mothership,
  24783. uiMothership
  24784. ], function (ship) {
  24785. ship.broadcastEvent(name, evt);
  24786. });
  24787. };
  24788. var broadcastOn = function (channel, message) {
  24789. each([
  24790. mothership,
  24791. uiMothership
  24792. ], function (ship) {
  24793. ship.broadcastOn([channel], message);
  24794. });
  24795. };
  24796. var fireDismissPopups = function (evt) {
  24797. return broadcastOn(dismissPopups(), { target: evt.target });
  24798. };
  24799. var onTouchstart = bind$3(SugarElement.fromDom(document), 'touchstart', fireDismissPopups);
  24800. var onTouchmove = bind$3(SugarElement.fromDom(document), 'touchmove', function (evt) {
  24801. return broadcastEvent(documentTouchmove(), evt);
  24802. });
  24803. var onTouchend = bind$3(SugarElement.fromDom(document), 'touchend', function (evt) {
  24804. return broadcastEvent(documentTouchend(), evt);
  24805. });
  24806. var onMousedown = bind$3(SugarElement.fromDom(document), 'mousedown', fireDismissPopups);
  24807. var onMouseup = bind$3(SugarElement.fromDom(document), 'mouseup', function (evt) {
  24808. if (evt.raw.button === 0) {
  24809. broadcastOn(mouseReleased(), { target: evt.target });
  24810. }
  24811. });
  24812. var onContentClick = function (raw) {
  24813. return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
  24814. };
  24815. var onContentMouseup = function (raw) {
  24816. if (raw.button === 0) {
  24817. broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
  24818. }
  24819. };
  24820. var onWindowScroll = function (evt) {
  24821. return broadcastEvent(windowScroll(), fromRawEvent$1(evt));
  24822. };
  24823. var onWindowResize = function (evt) {
  24824. broadcastOn(repositionPopups(), {});
  24825. broadcastEvent(windowResize(), fromRawEvent$1(evt));
  24826. };
  24827. var onEditorResize = function () {
  24828. return broadcastOn(repositionPopups(), {});
  24829. };
  24830. editor.on('PostRender', function () {
  24831. editor.on('click', onContentClick);
  24832. editor.on('tap', onContentClick);
  24833. editor.on('mouseup', onContentMouseup);
  24834. editor.on('ScrollWindow', onWindowScroll);
  24835. editor.on('ResizeWindow', onWindowResize);
  24836. editor.on('ResizeEditor', onEditorResize);
  24837. });
  24838. editor.on('remove', function () {
  24839. editor.off('click', onContentClick);
  24840. editor.off('tap', onContentClick);
  24841. editor.off('mouseup', onContentMouseup);
  24842. editor.off('ScrollWindow', onWindowScroll);
  24843. editor.off('ResizeWindow', onWindowResize);
  24844. editor.off('ResizeEditor', onEditorResize);
  24845. onMousedown.unbind();
  24846. onTouchstart.unbind();
  24847. onTouchmove.unbind();
  24848. onTouchend.unbind();
  24849. onMouseup.unbind();
  24850. });
  24851. editor.on('detach', function () {
  24852. detachSystem(mothership);
  24853. detachSystem(uiMothership);
  24854. mothership.destroy();
  24855. uiMothership.destroy();
  24856. });
  24857. };
  24858. var parts$d = AlloyParts;
  24859. var partType$1 = PartType;
  24860. var schema$r = constant([
  24861. defaulted$1('shell', false),
  24862. strict$1('makeItem'),
  24863. defaulted$1('setupItem', noop),
  24864. SketchBehaviours.field('listBehaviours', [Replacing])
  24865. ]);
  24866. var customListDetail = function () {
  24867. return { behaviours: derive$1([Replacing.config({})]) };
  24868. };
  24869. var itemsPart = optional({
  24870. name: 'items',
  24871. overrides: customListDetail
  24872. });
  24873. var parts$e = constant([itemsPart]);
  24874. var name$2 = constant('CustomList');
  24875. var factory$f = function (detail, components, _spec, _external) {
  24876. var setItems = function (list, items) {
  24877. getListContainer(list).fold(function () {
  24878. console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  24879. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  24880. }, function (container) {
  24881. var itemComps = Replacing.contents(container);
  24882. var numListsRequired = items.length;
  24883. var numListsToAdd = numListsRequired - itemComps.length;
  24884. var itemsToAdd = numListsToAdd > 0 ? range(numListsToAdd, function () {
  24885. return detail.makeItem();
  24886. }) : [];
  24887. var itemsToRemove = itemComps.slice(numListsRequired);
  24888. each(itemsToRemove, function (item) {
  24889. return Replacing.remove(container, item);
  24890. });
  24891. each(itemsToAdd, function (item) {
  24892. return Replacing.append(container, item);
  24893. });
  24894. var builtLists = Replacing.contents(container);
  24895. each(builtLists, function (item, i) {
  24896. detail.setupItem(list, item, items[i], i);
  24897. });
  24898. });
  24899. };
  24900. var extra = detail.shell ? {
  24901. behaviours: [Replacing.config({})],
  24902. components: []
  24903. } : {
  24904. behaviours: [],
  24905. components: components
  24906. };
  24907. var getListContainer = function (component) {
  24908. return detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
  24909. };
  24910. return {
  24911. uid: detail.uid,
  24912. dom: detail.dom,
  24913. components: extra.components,
  24914. behaviours: augment(detail.listBehaviours, extra.behaviours),
  24915. apis: { setItems: setItems }
  24916. };
  24917. };
  24918. var CustomList = composite$1({
  24919. name: name$2(),
  24920. configFields: schema$r(),
  24921. partFields: parts$e(),
  24922. factory: factory$f,
  24923. apis: {
  24924. setItems: function (apis, list, items) {
  24925. apis.setItems(list, items);
  24926. }
  24927. }
  24928. });
  24929. var setup$4 = noop;
  24930. var isDocked = never;
  24931. var getBehaviours$2 = constant([]);
  24932. var StaticHeader = /*#__PURE__*/Object.freeze({
  24933. __proto__: null,
  24934. setup: setup$4,
  24935. isDocked: isDocked,
  24936. getBehaviours: getBehaviours$2
  24937. });
  24938. var getOffsetParent = function (element) {
  24939. var isFixed = getRaw(element, 'position').is('fixed');
  24940. var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
  24941. return offsetParent$1.orThunk(function () {
  24942. var marker = SugarElement.fromTag('span');
  24943. return parent(element).bind(function (parent) {
  24944. append(parent, marker);
  24945. var offsetParent$1 = offsetParent(marker);
  24946. remove(marker);
  24947. return offsetParent$1;
  24948. });
  24949. });
  24950. };
  24951. var getOrigin = function (element) {
  24952. return getOffsetParent(element).map(absolute).getOrThunk(function () {
  24953. return SugarPosition(0, 0);
  24954. });
  24955. };
  24956. var morphAdt = Adt.generate([
  24957. { static: [] },
  24958. { absolute: ['positionCss'] },
  24959. { fixed: ['positionCss'] }
  24960. ]);
  24961. var appear = function (component, contextualInfo) {
  24962. var elem = component.element;
  24963. add$2(elem, contextualInfo.transitionClass);
  24964. remove$4(elem, contextualInfo.fadeOutClass);
  24965. add$2(elem, contextualInfo.fadeInClass);
  24966. contextualInfo.onShow(component);
  24967. };
  24968. var disappear = function (component, contextualInfo) {
  24969. var elem = component.element;
  24970. add$2(elem, contextualInfo.transitionClass);
  24971. remove$4(elem, contextualInfo.fadeInClass);
  24972. add$2(elem, contextualInfo.fadeOutClass);
  24973. contextualInfo.onHide(component);
  24974. };
  24975. var isPartiallyVisible = function (box, viewport) {
  24976. return box.y < viewport.bottom && box.bottom > viewport.y;
  24977. };
  24978. var isTopCompletelyVisible = function (box, viewport) {
  24979. return box.y >= viewport.y;
  24980. };
  24981. var isBottomCompletelyVisible = function (box, viewport) {
  24982. return box.bottom <= viewport.bottom;
  24983. };
  24984. var isVisibleForModes = function (modes, box, viewport) {
  24985. return forall(modes, function (mode) {
  24986. switch (mode) {
  24987. case 'bottom':
  24988. return isBottomCompletelyVisible(box, viewport);
  24989. case 'top':
  24990. return isTopCompletelyVisible(box, viewport);
  24991. }
  24992. });
  24993. };
  24994. var getPrior = function (elem, state) {
  24995. return state.getInitialPosition().map(function (pos) {
  24996. return bounds$1(pos.bounds.x, pos.bounds.y, get$7(elem), get$6(elem));
  24997. });
  24998. };
  24999. var storePrior = function (elem, box, state) {
  25000. state.setInitialPosition(Optional.some({
  25001. style: getAllRaw(elem),
  25002. position: get$4(elem, 'position') || 'static',
  25003. bounds: box
  25004. }));
  25005. };
  25006. var revertToOriginal = function (elem, box$1, state) {
  25007. return state.getInitialPosition().bind(function (position) {
  25008. state.setInitialPosition(Optional.none());
  25009. switch (position.position) {
  25010. case 'static':
  25011. return Optional.some(morphAdt.static());
  25012. case 'absolute':
  25013. var offsetBox_1 = getOffsetParent(elem).map(box).getOrThunk(function () {
  25014. return box(body());
  25015. });
  25016. return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get(position.style, 'left').map(function (_left) {
  25017. return box$1.x - offsetBox_1.x;
  25018. }), get(position.style, 'top').map(function (_top) {
  25019. return box$1.y - offsetBox_1.y;
  25020. }), get(position.style, 'right').map(function (_right) {
  25021. return offsetBox_1.right - box$1.right;
  25022. }), get(position.style, 'bottom').map(function (_bottom) {
  25023. return offsetBox_1.bottom - box$1.bottom;
  25024. }))));
  25025. default:
  25026. return Optional.none();
  25027. }
  25028. });
  25029. };
  25030. var morphToOriginal = function (elem, viewport, state) {
  25031. return getPrior(elem, state).filter(function (box) {
  25032. return isVisibleForModes(state.getModes(), box, viewport);
  25033. }).bind(function (box) {
  25034. return revertToOriginal(elem, box, state);
  25035. });
  25036. };
  25037. var morphToFixed = function (elem, viewport, state) {
  25038. var box$1 = box(elem);
  25039. if (!isVisibleForModes(state.getModes(), box$1, viewport)) {
  25040. storePrior(elem, box$1, state);
  25041. var winBox = win();
  25042. var left = box$1.x - winBox.x;
  25043. var top_1 = viewport.y - winBox.y;
  25044. var bottom = winBox.bottom - viewport.bottom;
  25045. var isTop = box$1.y <= viewport.y;
  25046. return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none())));
  25047. } else {
  25048. return Optional.none();
  25049. }
  25050. };
  25051. var getMorph = function (component, viewport, state) {
  25052. var elem = component.element;
  25053. var isDocked = getRaw(elem, 'position').is('fixed');
  25054. return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  25055. };
  25056. var getMorphToOriginal = function (component, state) {
  25057. var elem = component.element;
  25058. return getPrior(elem, state).bind(function (box) {
  25059. return revertToOriginal(elem, box, state);
  25060. });
  25061. };
  25062. var morphToStatic = function (component, config) {
  25063. each([
  25064. 'left',
  25065. 'right',
  25066. 'top',
  25067. 'bottom',
  25068. 'position'
  25069. ], function (prop) {
  25070. return remove$6(component.element, prop);
  25071. });
  25072. config.onUndocked(component);
  25073. };
  25074. var morphToCoord = function (component, config, position) {
  25075. applyPositionCss(component.element, position);
  25076. var method = position.position === 'fixed' ? config.onDocked : config.onUndocked;
  25077. method(component);
  25078. };
  25079. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  25080. if (morphToDocked === void 0) {
  25081. morphToDocked = false;
  25082. }
  25083. config.contextual.each(function (contextInfo) {
  25084. contextInfo.lazyContext(component).each(function (box) {
  25085. var isVisible = isPartiallyVisible(box, viewport);
  25086. if (isVisible !== state.isVisible()) {
  25087. state.setVisible(isVisible);
  25088. if (morphToDocked && !isVisible) {
  25089. add$3(component.element, [contextInfo.fadeOutClass]);
  25090. contextInfo.onHide(component);
  25091. } else {
  25092. var method = isVisible ? appear : disappear;
  25093. method(component, contextInfo);
  25094. }
  25095. }
  25096. });
  25097. });
  25098. };
  25099. var refreshInternal = function (component, config, state) {
  25100. var viewport = config.lazyViewport(component);
  25101. var isDocked = state.isDocked();
  25102. if (isDocked) {
  25103. updateVisibility(component, config, state, viewport);
  25104. }
  25105. getMorph(component, viewport, state).each(function (morph) {
  25106. state.setDocked(!isDocked);
  25107. morph.fold(function () {
  25108. return morphToStatic(component, config);
  25109. }, function (position) {
  25110. return morphToCoord(component, config, position);
  25111. }, function (position) {
  25112. updateVisibility(component, config, state, viewport, true);
  25113. morphToCoord(component, config, position);
  25114. });
  25115. });
  25116. };
  25117. var resetInternal = function (component, config, state) {
  25118. var elem = component.element;
  25119. state.setDocked(false);
  25120. getMorphToOriginal(component, state).each(function (morph) {
  25121. morph.fold(function () {
  25122. return morphToStatic(component, config);
  25123. }, function (position) {
  25124. return morphToCoord(component, config, position);
  25125. }, noop);
  25126. });
  25127. state.setVisible(true);
  25128. config.contextual.each(function (contextInfo) {
  25129. remove$5(elem, [
  25130. contextInfo.fadeInClass,
  25131. contextInfo.fadeOutClass,
  25132. contextInfo.transitionClass
  25133. ]);
  25134. contextInfo.onShow(component);
  25135. });
  25136. refresh$4(component, config, state);
  25137. };
  25138. var refresh$4 = function (component, config, state) {
  25139. if (component.getSystem().isConnected()) {
  25140. refreshInternal(component, config, state);
  25141. }
  25142. };
  25143. var reset = function (component, config, state) {
  25144. if (state.isDocked()) {
  25145. resetInternal(component, config, state);
  25146. }
  25147. };
  25148. var isDocked$1 = function (component, config, state) {
  25149. return state.isDocked();
  25150. };
  25151. var setModes = function (component, config, state, modes) {
  25152. return state.setModes(modes);
  25153. };
  25154. var getModes = function (component, config, state) {
  25155. return state.getModes();
  25156. };
  25157. var DockingApis = /*#__PURE__*/Object.freeze({
  25158. __proto__: null,
  25159. refresh: refresh$4,
  25160. reset: reset,
  25161. isDocked: isDocked$1,
  25162. getModes: getModes,
  25163. setModes: setModes
  25164. });
  25165. var events$f = function (dockInfo, dockState) {
  25166. return derive([
  25167. runOnSource(transitionend(), function (component, simulatedEvent) {
  25168. dockInfo.contextual.each(function (contextInfo) {
  25169. if (has$2(component.element, contextInfo.transitionClass)) {
  25170. remove$5(component.element, [
  25171. contextInfo.transitionClass,
  25172. contextInfo.fadeInClass
  25173. ]);
  25174. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  25175. notify(component);
  25176. }
  25177. simulatedEvent.stop();
  25178. });
  25179. }),
  25180. run(windowScroll(), function (component, _) {
  25181. refresh$4(component, dockInfo, dockState);
  25182. }),
  25183. run(windowResize(), function (component, _) {
  25184. reset(component, dockInfo, dockState);
  25185. })
  25186. ]);
  25187. };
  25188. var ActiveDocking = /*#__PURE__*/Object.freeze({
  25189. __proto__: null,
  25190. events: events$f
  25191. });
  25192. var DockingSchema = [
  25193. optionObjOf('contextual', [
  25194. strictString('fadeInClass'),
  25195. strictString('fadeOutClass'),
  25196. strictString('transitionClass'),
  25197. strictFunction('lazyContext'),
  25198. onHandler('onShow'),
  25199. onHandler('onShown'),
  25200. onHandler('onHide'),
  25201. onHandler('onHidden')
  25202. ]),
  25203. defaultedFunction('lazyViewport', win),
  25204. defaultedArrayOf('modes', [
  25205. 'top',
  25206. 'bottom'
  25207. ], string),
  25208. onHandler('onDocked'),
  25209. onHandler('onUndocked')
  25210. ];
  25211. var init$b = function (spec) {
  25212. var docked = Cell(false);
  25213. var visible = Cell(true);
  25214. var initialBounds = Cell(Optional.none());
  25215. var modes = Cell(spec.modes);
  25216. var readState = function () {
  25217. return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
  25218. };
  25219. return nu$5({
  25220. isDocked: docked.get,
  25221. setDocked: docked.set,
  25222. getInitialPosition: initialBounds.get,
  25223. setInitialPosition: initialBounds.set,
  25224. isVisible: visible.get,
  25225. setVisible: visible.set,
  25226. getModes: modes.get,
  25227. setModes: modes.set,
  25228. readState: readState
  25229. });
  25230. };
  25231. var DockingState = /*#__PURE__*/Object.freeze({
  25232. __proto__: null,
  25233. init: init$b
  25234. });
  25235. var Docking = create$1({
  25236. fields: DockingSchema,
  25237. name: 'docking',
  25238. active: ActiveDocking,
  25239. apis: DockingApis,
  25240. state: DockingState
  25241. });
  25242. var visibility = {
  25243. fadeInClass: 'tox-editor-dock-fadein',
  25244. fadeOutClass: 'tox-editor-dock-fadeout',
  25245. transitionClass: 'tox-editor-dock-transition'
  25246. };
  25247. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  25248. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  25249. var scrollFromBehindHeader = function (e, containerHeader) {
  25250. var doc = owner(containerHeader);
  25251. var viewHeight = doc.dom.defaultView.innerHeight;
  25252. var scrollPos = get$8(doc);
  25253. var markerElement = SugarElement.fromDom(e.elm);
  25254. var markerPos = absolute$1(markerElement);
  25255. var markerHeight = get$6(markerElement);
  25256. var markerTop = markerPos.y;
  25257. var markerBottom = markerTop + markerHeight;
  25258. var editorHeaderPos = absolute(containerHeader);
  25259. var editorHeaderHeight = get$6(containerHeader);
  25260. var editorHeaderTop = editorHeaderPos.top;
  25261. var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  25262. var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
  25263. var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
  25264. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  25265. to(scrollPos.left, markerTop - editorHeaderHeight, doc);
  25266. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  25267. var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  25268. to(scrollPos.left, y, doc);
  25269. }
  25270. };
  25271. var isDockedMode = function (header, mode) {
  25272. return contains(Docking.getModes(header), mode);
  25273. };
  25274. var updateIframeContentFlow = function (header) {
  25275. var getOccupiedHeight = function (elm) {
  25276. return getOuter$1(elm) + (parseInt(get$4(elm, 'margin-top'), 10) || 0) + (parseInt(get$4(elm, 'margin-bottom'), 10) || 0);
  25277. };
  25278. var elm = header.element;
  25279. parent(elm).each(function (parentElem) {
  25280. var padding = 'padding-' + Docking.getModes(header)[0];
  25281. if (Docking.isDocked(header)) {
  25282. var parentWidth = get$7(parentElem);
  25283. set$2(elm, 'width', parentWidth + 'px');
  25284. set$2(parentElem, padding, getOccupiedHeight(elm) + 'px');
  25285. } else {
  25286. remove$6(elm, 'width');
  25287. remove$6(parentElem, padding);
  25288. }
  25289. });
  25290. };
  25291. var updateSinkVisibility = function (sinkElem, visible) {
  25292. if (visible) {
  25293. remove$4(sinkElem, visibility.fadeOutClass);
  25294. add$3(sinkElem, [
  25295. visibility.transitionClass,
  25296. visibility.fadeInClass
  25297. ]);
  25298. } else {
  25299. remove$4(sinkElem, visibility.fadeInClass);
  25300. add$3(sinkElem, [
  25301. visibility.fadeOutClass,
  25302. visibility.transitionClass
  25303. ]);
  25304. }
  25305. };
  25306. var updateEditorClasses = function (editor, docked) {
  25307. var editorContainer = SugarElement.fromDom(editor.getContainer());
  25308. if (docked) {
  25309. add$2(editorContainer, editorStickyOnClass);
  25310. remove$4(editorContainer, editorStickyOffClass);
  25311. } else {
  25312. add$2(editorContainer, editorStickyOffClass);
  25313. remove$4(editorContainer, editorStickyOnClass);
  25314. }
  25315. };
  25316. var restoreFocus = function (headerElem, focusedElem) {
  25317. var ownerDoc = owner(focusedElem);
  25318. active(ownerDoc).filter(function (activeElm) {
  25319. return !eq$1(focusedElem, activeElm);
  25320. }).filter(function (activeElm) {
  25321. return eq$1(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains$2(headerElem, activeElm);
  25322. }).each(function () {
  25323. return focus$1(focusedElem);
  25324. });
  25325. };
  25326. var findFocusedElem = function (rootElm, lazySink) {
  25327. return search(rootElm).orThunk(function () {
  25328. return lazySink().toOptional().bind(function (sink) {
  25329. return search(sink.element);
  25330. });
  25331. });
  25332. };
  25333. var setup$5 = function (editor, sharedBackstage, lazyHeader) {
  25334. if (!editor.inline) {
  25335. if (!sharedBackstage.header.isPositionedAtTop()) {
  25336. editor.on('ResizeEditor', function () {
  25337. lazyHeader().each(Docking.reset);
  25338. });
  25339. }
  25340. editor.on('ResizeWindow ResizeEditor', function () {
  25341. lazyHeader().each(updateIframeContentFlow);
  25342. });
  25343. editor.on('SkinLoaded', function () {
  25344. lazyHeader().each(function (comp) {
  25345. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  25346. });
  25347. });
  25348. editor.on('FullscreenStateChanged', function () {
  25349. lazyHeader().each(Docking.reset);
  25350. });
  25351. }
  25352. editor.on('AfterScrollIntoView', function (e) {
  25353. lazyHeader().each(function (header) {
  25354. Docking.refresh(header);
  25355. var headerElem = header.element;
  25356. if (isVisible(headerElem)) {
  25357. scrollFromBehindHeader(e, headerElem);
  25358. }
  25359. });
  25360. });
  25361. editor.on('PostRender', function () {
  25362. updateEditorClasses(editor, false);
  25363. });
  25364. };
  25365. var isDocked$2 = function (lazyHeader) {
  25366. return lazyHeader().map(Docking.isDocked).getOr(false);
  25367. };
  25368. var getIframeBehaviours = function () {
  25369. var _a;
  25370. return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
  25371. };
  25372. var getBehaviours$3 = function (editor, sharedBackstage) {
  25373. var focusedElm = Cell(Optional.none());
  25374. var lazySink = sharedBackstage.getSink;
  25375. var runOnSinkElement = function (f) {
  25376. lazySink().each(function (sink) {
  25377. return f(sink.element);
  25378. });
  25379. };
  25380. var onDockingSwitch = function (comp) {
  25381. if (!editor.inline) {
  25382. updateIframeContentFlow(comp);
  25383. }
  25384. updateEditorClasses(editor, Docking.isDocked(comp));
  25385. comp.getSystem().broadcastOn([repositionPopups()], {});
  25386. lazySink().each(function (sink) {
  25387. return sink.getSystem().broadcastOn([repositionPopups()], {});
  25388. });
  25389. };
  25390. var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  25391. return __spreadArrays([
  25392. Focusing.config({}),
  25393. Docking.config({
  25394. contextual: __assign({
  25395. lazyContext: function (comp) {
  25396. var headerHeight = getOuter$1(comp.element);
  25397. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  25398. var box$1 = box(SugarElement.fromDom(container));
  25399. var boxHeight = box$1.height - headerHeight;
  25400. var topBound = box$1.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  25401. return Optional.some(bounds$1(box$1.x, topBound, box$1.width, boxHeight));
  25402. },
  25403. onShow: function () {
  25404. runOnSinkElement(function (elem) {
  25405. return updateSinkVisibility(elem, true);
  25406. });
  25407. },
  25408. onShown: function (comp) {
  25409. runOnSinkElement(function (elem) {
  25410. return remove$5(elem, [
  25411. visibility.transitionClass,
  25412. visibility.fadeInClass
  25413. ]);
  25414. });
  25415. focusedElm.get().each(function (elem) {
  25416. restoreFocus(comp.element, elem);
  25417. focusedElm.set(Optional.none());
  25418. });
  25419. },
  25420. onHide: function (comp) {
  25421. focusedElm.set(findFocusedElem(comp.element, lazySink));
  25422. runOnSinkElement(function (elem) {
  25423. return updateSinkVisibility(elem, false);
  25424. });
  25425. },
  25426. onHidden: function () {
  25427. runOnSinkElement(function (elem) {
  25428. return remove$5(elem, [visibility.transitionClass]);
  25429. });
  25430. }
  25431. }, visibility),
  25432. modes: [sharedBackstage.header.getDockingMode()],
  25433. onDocked: onDockingSwitch,
  25434. onUndocked: onDockingSwitch
  25435. })
  25436. ], additionalBehaviours);
  25437. };
  25438. var StickyHeader = /*#__PURE__*/Object.freeze({
  25439. __proto__: null,
  25440. setup: setup$5,
  25441. isDocked: isDocked$2,
  25442. getBehaviours: getBehaviours$3
  25443. });
  25444. var renderHeader = function (spec) {
  25445. var editor = spec.editor;
  25446. var getBehaviours = spec.sticky ? getBehaviours$3 : getBehaviours$2;
  25447. return {
  25448. uid: spec.uid,
  25449. dom: spec.dom,
  25450. components: spec.components,
  25451. behaviours: derive$1(getBehaviours(editor, spec.sharedBackstage))
  25452. };
  25453. };
  25454. var factory$g = function (detail, spec) {
  25455. var setMenus = function (comp, menus) {
  25456. var newMenus = map(menus, function (m) {
  25457. var buttonSpec = {
  25458. type: 'menubutton',
  25459. text: m.text,
  25460. fetch: function (callback) {
  25461. callback(m.getItems());
  25462. }
  25463. };
  25464. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  25465. return formatError(errInfo);
  25466. }).getOrDie();
  25467. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
  25468. });
  25469. Replacing.set(comp, newMenus);
  25470. };
  25471. var apis = {
  25472. focus: Keying.focusIn,
  25473. setMenus: setMenus
  25474. };
  25475. return {
  25476. uid: detail.uid,
  25477. dom: detail.dom,
  25478. components: [],
  25479. behaviours: derive$1([
  25480. Replacing.config({}),
  25481. config('menubar-events', [
  25482. runOnAttached(function (component) {
  25483. detail.onSetup(component);
  25484. }),
  25485. run(mouseover(), function (comp, se) {
  25486. descendant$1(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) {
  25487. closest$3(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) {
  25488. if (!eq$1(activeButton, hoveredButton)) {
  25489. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  25490. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  25491. Dropdown.expand(hoveredComp);
  25492. Dropdown.close(activeComp);
  25493. Focusing.focus(hoveredComp);
  25494. });
  25495. });
  25496. }
  25497. });
  25498. });
  25499. }),
  25500. run(focusShifted(), function (comp, se) {
  25501. se.event.prevFocus.bind(function (prev) {
  25502. return comp.getSystem().getByDom(prev).toOptional();
  25503. }).each(function (prev) {
  25504. se.event.newFocus.bind(function (nu) {
  25505. return comp.getSystem().getByDom(nu).toOptional();
  25506. }).each(function (nu) {
  25507. if (Dropdown.isOpen(prev)) {
  25508. Dropdown.expand(nu);
  25509. Dropdown.close(prev);
  25510. }
  25511. });
  25512. });
  25513. })
  25514. ]),
  25515. Keying.config({
  25516. mode: 'flow',
  25517. selector: '.' + 'tox-mbtn',
  25518. onEscape: function (comp) {
  25519. detail.onEscape(comp);
  25520. return Optional.some(true);
  25521. }
  25522. }),
  25523. Tabstopping.config({})
  25524. ]),
  25525. apis: apis,
  25526. domModification: { attributes: { role: 'menubar' } }
  25527. };
  25528. };
  25529. var SilverMenubar = single$2({
  25530. factory: factory$g,
  25531. name: 'silver.Menubar',
  25532. configFields: [
  25533. strict$1('dom'),
  25534. strict$1('uid'),
  25535. strict$1('onEscape'),
  25536. strict$1('backstage'),
  25537. defaulted$1('onSetup', noop)
  25538. ],
  25539. apis: {
  25540. focus: function (apis, comp) {
  25541. apis.focus(comp);
  25542. },
  25543. setMenus: function (apis, comp, menus) {
  25544. apis.setMenus(comp, menus);
  25545. }
  25546. }
  25547. });
  25548. var owner$4 = 'container';
  25549. var schema$s = [field$1('slotBehaviours', [])];
  25550. var getPartName$1 = function (name) {
  25551. return '<alloy.field.' + name + '>';
  25552. };
  25553. var sketch$2 = function (sSpec) {
  25554. var parts = function () {
  25555. var record = [];
  25556. var slot = function (name, config) {
  25557. record.push(name);
  25558. return generateOne(owner$4, getPartName$1(name), config);
  25559. };
  25560. return {
  25561. slot: slot,
  25562. record: function () {
  25563. return record;
  25564. }
  25565. };
  25566. }();
  25567. var spec = sSpec(parts);
  25568. var partNames = parts.record();
  25569. var fieldParts = map(partNames, function (n) {
  25570. return required({
  25571. name: n,
  25572. pname: getPartName$1(n)
  25573. });
  25574. });
  25575. return composite(owner$4, schema$s, fieldParts, make$7, spec);
  25576. };
  25577. var make$7 = function (detail, components) {
  25578. var getSlotNames = function (_) {
  25579. return getAllPartNames(detail);
  25580. };
  25581. var getSlot = function (container, key) {
  25582. return getPart(container, detail, key);
  25583. };
  25584. var onSlot = function (f, def) {
  25585. return function (container, key) {
  25586. return getPart(container, detail, key).map(function (slot) {
  25587. return f(slot, key);
  25588. }).getOr(def);
  25589. };
  25590. };
  25591. var onSlots = function (f) {
  25592. return function (container, keys) {
  25593. each(keys, function (key) {
  25594. return f(container, key);
  25595. });
  25596. };
  25597. };
  25598. var doShowing = function (comp, _key) {
  25599. return get$2(comp.element, 'aria-hidden') !== 'true';
  25600. };
  25601. var doShow = function (comp, key) {
  25602. if (!doShowing(comp)) {
  25603. var element = comp.element;
  25604. remove$6(element, 'display');
  25605. remove$1(element, 'aria-hidden');
  25606. emitWith(comp, slotVisibility(), {
  25607. name: key,
  25608. visible: true
  25609. });
  25610. }
  25611. };
  25612. var doHide = function (comp, key) {
  25613. if (doShowing(comp)) {
  25614. var element = comp.element;
  25615. set$2(element, 'display', 'none');
  25616. set$1(element, 'aria-hidden', 'true');
  25617. emitWith(comp, slotVisibility(), {
  25618. name: key,
  25619. visible: false
  25620. });
  25621. }
  25622. };
  25623. var isShowing = onSlot(doShowing, false);
  25624. var hideSlot = onSlot(doHide);
  25625. var hideSlots = onSlots(hideSlot);
  25626. var hideAllSlots = function (container) {
  25627. return hideSlots(container, getSlotNames());
  25628. };
  25629. var showSlot = onSlot(doShow);
  25630. var apis = {
  25631. getSlotNames: getSlotNames,
  25632. getSlot: getSlot,
  25633. isShowing: isShowing,
  25634. hideSlot: hideSlot,
  25635. hideAllSlots: hideAllSlots,
  25636. showSlot: showSlot
  25637. };
  25638. return {
  25639. uid: detail.uid,
  25640. dom: detail.dom,
  25641. components: components,
  25642. behaviours: get$c(detail.slotBehaviours),
  25643. apis: apis
  25644. };
  25645. };
  25646. var slotApis = map$2({
  25647. getSlotNames: function (apis, c) {
  25648. return apis.getSlotNames(c);
  25649. },
  25650. getSlot: function (apis, c, key) {
  25651. return apis.getSlot(c, key);
  25652. },
  25653. isShowing: function (apis, c, key) {
  25654. return apis.isShowing(c, key);
  25655. },
  25656. hideSlot: function (apis, c, key) {
  25657. return apis.hideSlot(c, key);
  25658. },
  25659. hideAllSlots: function (apis, c) {
  25660. return apis.hideAllSlots(c);
  25661. },
  25662. showSlot: function (apis, c, key) {
  25663. return apis.showSlot(c, key);
  25664. }
  25665. }, function (value) {
  25666. return makeApi(value);
  25667. });
  25668. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch$2 });
  25669. var sidebarSchema = objOf([
  25670. optionString('icon'),
  25671. optionString('tooltip'),
  25672. defaultedFunction('onShow', noop),
  25673. defaultedFunction('onHide', noop),
  25674. defaultedFunction('onSetup', function () {
  25675. return noop;
  25676. })
  25677. ]);
  25678. var createSidebar = function (spec) {
  25679. return asRaw('sidebar', sidebarSchema, spec);
  25680. };
  25681. var setup$6 = function (editor) {
  25682. var sidebars = editor.ui.registry.getAll().sidebars;
  25683. each(keys(sidebars), function (name) {
  25684. var spec = sidebars[name];
  25685. var isActive = function () {
  25686. return Optional.from(editor.queryCommandValue('ToggleSidebar')).is(name);
  25687. };
  25688. editor.ui.registry.addToggleButton(name, {
  25689. icon: spec.icon,
  25690. tooltip: spec.tooltip,
  25691. onAction: function (buttonApi) {
  25692. editor.execCommand('ToggleSidebar', false, name);
  25693. buttonApi.setActive(isActive());
  25694. },
  25695. onSetup: function (buttonApi) {
  25696. var handleToggle = function () {
  25697. return buttonApi.setActive(isActive());
  25698. };
  25699. editor.on('ToggleSidebar', handleToggle);
  25700. return function () {
  25701. editor.off('ToggleSidebar', handleToggle);
  25702. };
  25703. }
  25704. });
  25705. });
  25706. };
  25707. var getApi = function (comp) {
  25708. return {
  25709. element: function () {
  25710. return comp.element.dom;
  25711. }
  25712. };
  25713. };
  25714. var makePanels = function (parts, panelConfigs) {
  25715. var specs = map(keys(panelConfigs), function (name) {
  25716. var spec = panelConfigs[name];
  25717. var bridged = getOrDie(createSidebar(spec));
  25718. return {
  25719. name: name,
  25720. getApi: getApi,
  25721. onSetup: bridged.onSetup,
  25722. onShow: bridged.onShow,
  25723. onHide: bridged.onHide
  25724. };
  25725. });
  25726. return map(specs, function (spec) {
  25727. var editorOffCell = Cell(noop);
  25728. return parts.slot(spec.name, {
  25729. dom: {
  25730. tag: 'div',
  25731. classes: ['tox-sidebar__pane']
  25732. },
  25733. behaviours: SimpleBehaviours.unnamedEvents([
  25734. onControlAttached(spec, editorOffCell),
  25735. onControlDetached(spec, editorOffCell),
  25736. run(slotVisibility(), function (sidepanel, se) {
  25737. var data = se.event;
  25738. var optSidePanelSpec = find(specs, function (config) {
  25739. return config.name === data.name;
  25740. });
  25741. optSidePanelSpec.each(function (sidePanelSpec) {
  25742. var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  25743. handler(sidePanelSpec.getApi(sidepanel));
  25744. });
  25745. })
  25746. ])
  25747. });
  25748. });
  25749. };
  25750. var makeSidebar = function (panelConfigs) {
  25751. return SlotContainer.sketch(function (parts) {
  25752. return {
  25753. dom: {
  25754. tag: 'div',
  25755. classes: ['tox-sidebar__pane-container']
  25756. },
  25757. components: makePanels(parts, panelConfigs),
  25758. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  25759. return SlotContainer.hideAllSlots(slotContainer);
  25760. })])
  25761. };
  25762. });
  25763. };
  25764. var setSidebar = function (sidebar, panelConfigs) {
  25765. var optSlider = Composing.getCurrent(sidebar);
  25766. optSlider.each(function (slider) {
  25767. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  25768. });
  25769. };
  25770. var toggleSidebar = function (sidebar, name) {
  25771. var optSlider = Composing.getCurrent(sidebar);
  25772. optSlider.each(function (slider) {
  25773. var optSlotContainer = Composing.getCurrent(slider);
  25774. optSlotContainer.each(function (slotContainer) {
  25775. if (Sliding.hasGrown(slider)) {
  25776. if (SlotContainer.isShowing(slotContainer, name)) {
  25777. Sliding.shrink(slider);
  25778. } else {
  25779. SlotContainer.hideAllSlots(slotContainer);
  25780. SlotContainer.showSlot(slotContainer, name);
  25781. }
  25782. } else {
  25783. SlotContainer.hideAllSlots(slotContainer);
  25784. SlotContainer.showSlot(slotContainer, name);
  25785. Sliding.grow(slider);
  25786. }
  25787. });
  25788. });
  25789. };
  25790. var whichSidebar = function (sidebar) {
  25791. var optSlider = Composing.getCurrent(sidebar);
  25792. return optSlider.bind(function (slider) {
  25793. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  25794. if (sidebarOpen) {
  25795. var optSlotContainer = Composing.getCurrent(slider);
  25796. return optSlotContainer.bind(function (slotContainer) {
  25797. return find(SlotContainer.getSlotNames(slotContainer), function (name) {
  25798. return SlotContainer.isShowing(slotContainer, name);
  25799. });
  25800. });
  25801. } else {
  25802. return Optional.none();
  25803. }
  25804. });
  25805. };
  25806. var fixSize = generate$1('FixSizeEvent');
  25807. var autoSize = generate$1('AutoSizeEvent');
  25808. var renderSidebar = function (spec) {
  25809. return {
  25810. uid: spec.uid,
  25811. dom: {
  25812. tag: 'div',
  25813. classes: ['tox-sidebar'],
  25814. attributes: { role: 'complementary' }
  25815. },
  25816. components: [{
  25817. dom: {
  25818. tag: 'div',
  25819. classes: ['tox-sidebar__slider']
  25820. },
  25821. components: [],
  25822. behaviours: derive$1([
  25823. Tabstopping.config({}),
  25824. Focusing.config({}),
  25825. Sliding.config({
  25826. dimension: { property: 'width' },
  25827. closedClass: 'tox-sidebar--sliding-closed',
  25828. openClass: 'tox-sidebar--sliding-open',
  25829. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  25830. growingClass: 'tox-sidebar--sliding-growing',
  25831. onShrunk: function (slider) {
  25832. var optSlotContainer = Composing.getCurrent(slider);
  25833. optSlotContainer.each(SlotContainer.hideAllSlots);
  25834. emit(slider, autoSize);
  25835. },
  25836. onGrown: function (slider) {
  25837. emit(slider, autoSize);
  25838. },
  25839. onStartGrow: function (slider) {
  25840. emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
  25841. },
  25842. onStartShrink: function (slider) {
  25843. emitWith(slider, fixSize, { width: get$7(slider.element) + 'px' });
  25844. }
  25845. }),
  25846. Replacing.config({}),
  25847. Composing.config({
  25848. find: function (comp) {
  25849. var children = Replacing.contents(comp);
  25850. return head(children);
  25851. }
  25852. })
  25853. ])
  25854. }],
  25855. behaviours: derive$1([
  25856. ComposingConfigs.childAt(0),
  25857. config('sidebar-sliding-events', [
  25858. run(fixSize, function (comp, se) {
  25859. set$2(comp.element, 'width', se.event.width);
  25860. }),
  25861. run(autoSize, function (comp, _se) {
  25862. remove$6(comp.element, 'width');
  25863. })
  25864. ])
  25865. ])
  25866. };
  25867. };
  25868. var getAttrs = function (elem) {
  25869. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  25870. return foldl(attributes, function (b, attr) {
  25871. var _a;
  25872. if (attr.name === 'class') {
  25873. return b;
  25874. } else {
  25875. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  25876. }
  25877. }, {});
  25878. };
  25879. var getClasses = function (elem) {
  25880. return Array.prototype.slice.call(elem.dom.classList, 0);
  25881. };
  25882. var fromHtml$2 = function (html) {
  25883. var elem = SugarElement.fromHtml(html);
  25884. var children$1 = children(elem);
  25885. var attrs = getAttrs(elem);
  25886. var classes = getClasses(elem);
  25887. var contents = children$1.length === 0 ? {} : { innerHtml: get$1(elem) };
  25888. return __assign({
  25889. tag: name(elem),
  25890. classes: classes,
  25891. attributes: attrs
  25892. }, contents);
  25893. };
  25894. var renderSpinner = function (providerBackstage) {
  25895. return {
  25896. dom: {
  25897. tag: 'div',
  25898. attributes: { 'aria-label': providerBackstage.translate('Loading...') },
  25899. classes: ['tox-throbber__busy-spinner']
  25900. },
  25901. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }],
  25902. behaviours: derive$1([
  25903. Keying.config({
  25904. mode: 'special',
  25905. onTab: function () {
  25906. return Optional.some(true);
  25907. },
  25908. onShiftTab: function () {
  25909. return Optional.some(true);
  25910. }
  25911. }),
  25912. Focusing.config({})
  25913. ])
  25914. };
  25915. };
  25916. var toggleThrobber = function (comp, state, providerBackstage) {
  25917. var element = comp.element;
  25918. if (state === true) {
  25919. Replacing.set(comp, [renderSpinner(providerBackstage)]);
  25920. remove$6(element, 'display');
  25921. remove$1(element, 'aria-hidden');
  25922. } else {
  25923. Replacing.set(comp, []);
  25924. set$2(element, 'display', 'none');
  25925. set$1(element, 'aria-hidden', 'true');
  25926. }
  25927. };
  25928. var renderThrobber = function (spec) {
  25929. return {
  25930. uid: spec.uid,
  25931. dom: {
  25932. tag: 'div',
  25933. attributes: { 'aria-hidden': 'true' },
  25934. classes: ['tox-throbber'],
  25935. styles: { display: 'none' }
  25936. },
  25937. behaviours: derive$1([Replacing.config({})]),
  25938. components: []
  25939. };
  25940. };
  25941. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  25942. var throbberState = Cell(false);
  25943. var timer = Cell(Optional.none());
  25944. var toggle = function (state) {
  25945. if (state !== throbberState.get()) {
  25946. toggleThrobber(lazyThrobber(), state, sharedBackstage.providers);
  25947. throbberState.set(state);
  25948. }
  25949. };
  25950. editor.on('ProgressState', function (e) {
  25951. timer.get().each(global$2.clearTimeout);
  25952. if (isNumber(e.time)) {
  25953. var timerId = global$2.setEditorTimeout(editor, function () {
  25954. return toggle(e.state);
  25955. }, e.time);
  25956. timer.set(Optional.some(timerId));
  25957. } else {
  25958. toggle(e.state);
  25959. timer.set(Optional.none());
  25960. }
  25961. });
  25962. };
  25963. var factory$h = function (detail, components, _spec) {
  25964. var apis = {
  25965. getSocket: function (comp) {
  25966. return parts$d.getPart(comp, detail, 'socket');
  25967. },
  25968. setSidebar: function (comp, panelConfigs) {
  25969. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25970. return setSidebar(sidebar, panelConfigs);
  25971. });
  25972. },
  25973. toggleSidebar: function (comp, name) {
  25974. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25975. return toggleSidebar(sidebar, name);
  25976. });
  25977. },
  25978. whichSidebar: function (comp) {
  25979. return parts$d.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  25980. },
  25981. getHeader: function (comp) {
  25982. return parts$d.getPart(comp, detail, 'header');
  25983. },
  25984. getToolbar: function (comp) {
  25985. return parts$d.getPart(comp, detail, 'toolbar');
  25986. },
  25987. setToolbar: function (comp, groups) {
  25988. parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  25989. toolbar.getApis().setGroups(toolbar, groups);
  25990. });
  25991. },
  25992. setToolbars: function (comp, toolbars) {
  25993. parts$d.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  25994. CustomList.setItems(mToolbar, toolbars);
  25995. });
  25996. },
  25997. refreshToolbar: function (comp) {
  25998. var toolbar = parts$d.getPart(comp, detail, 'toolbar');
  25999. toolbar.each(function (toolbar) {
  26000. return toolbar.getApis().refresh(toolbar);
  26001. });
  26002. },
  26003. toggleToolbarDrawer: function (comp) {
  26004. parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  26005. mapFrom(toolbar.getApis().toggle, function (toggle) {
  26006. return toggle(toolbar);
  26007. });
  26008. });
  26009. },
  26010. isToolbarDrawerToggled: function (comp) {
  26011. return parts$d.getPart(comp, detail, 'toolbar').bind(function (toolbar) {
  26012. return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) {
  26013. return isOpen(toolbar);
  26014. });
  26015. }).getOr(false);
  26016. },
  26017. getThrobber: function (comp) {
  26018. return parts$d.getPart(comp, detail, 'throbber');
  26019. },
  26020. focusToolbar: function (comp) {
  26021. var optToolbar = parts$d.getPart(comp, detail, 'toolbar').orThunk(function () {
  26022. return parts$d.getPart(comp, detail, 'multiple-toolbar');
  26023. });
  26024. optToolbar.each(function (toolbar) {
  26025. Keying.focusIn(toolbar);
  26026. });
  26027. },
  26028. setMenubar: function (comp, menus) {
  26029. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  26030. SilverMenubar.setMenus(menubar, menus);
  26031. });
  26032. },
  26033. focusMenubar: function (comp) {
  26034. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  26035. SilverMenubar.focus(menubar);
  26036. });
  26037. }
  26038. };
  26039. return {
  26040. uid: detail.uid,
  26041. dom: detail.dom,
  26042. components: components,
  26043. apis: apis,
  26044. behaviours: detail.behaviours
  26045. };
  26046. };
  26047. var partMenubar = partType$1.optional({
  26048. factory: SilverMenubar,
  26049. name: 'menubar',
  26050. schema: [strict$1('backstage')]
  26051. });
  26052. var toolbarFactory = function (spec) {
  26053. if (spec.type === ToolbarMode.sliding) {
  26054. return renderSlidingMoreToolbar;
  26055. } else if (spec.type === ToolbarMode.floating) {
  26056. return renderFloatingMoreToolbar;
  26057. } else {
  26058. return renderToolbar;
  26059. }
  26060. };
  26061. var partMultipleToolbar = partType$1.optional({
  26062. factory: {
  26063. sketch: function (spec) {
  26064. return CustomList.sketch({
  26065. uid: spec.uid,
  26066. dom: spec.dom,
  26067. listBehaviours: derive$1([Keying.config({
  26068. mode: 'acyclic',
  26069. selector: '.tox-toolbar'
  26070. })]),
  26071. makeItem: function () {
  26072. return renderToolbar({
  26073. type: spec.type,
  26074. uid: generate$1('multiple-toolbar-item'),
  26075. cyclicKeying: false,
  26076. initGroups: [],
  26077. providers: spec.providers,
  26078. onEscape: function () {
  26079. spec.onEscape();
  26080. return Optional.some(true);
  26081. }
  26082. });
  26083. },
  26084. setupItem: function (_mToolbar, tc, data, _index) {
  26085. Toolbar.setGroups(tc, data);
  26086. },
  26087. shell: true
  26088. });
  26089. }
  26090. },
  26091. name: 'multiple-toolbar',
  26092. schema: [
  26093. strict$1('dom'),
  26094. strict$1('onEscape')
  26095. ]
  26096. });
  26097. var partToolbar = partType$1.optional({
  26098. factory: {
  26099. sketch: function (spec) {
  26100. var renderer = toolbarFactory(spec);
  26101. var toolbarSpec = {
  26102. type: spec.type,
  26103. uid: spec.uid,
  26104. onEscape: function () {
  26105. spec.onEscape();
  26106. return Optional.some(true);
  26107. },
  26108. cyclicKeying: false,
  26109. initGroups: [],
  26110. getSink: spec.getSink,
  26111. providers: spec.providers,
  26112. moreDrawerData: {
  26113. lazyToolbar: spec.lazyToolbar,
  26114. lazyMoreButton: spec.lazyMoreButton,
  26115. lazyHeader: spec.lazyHeader
  26116. },
  26117. attributes: spec.attributes
  26118. };
  26119. return renderer(toolbarSpec);
  26120. }
  26121. },
  26122. name: 'toolbar',
  26123. schema: [
  26124. strict$1('dom'),
  26125. strict$1('onEscape'),
  26126. strict$1('getSink')
  26127. ]
  26128. });
  26129. var partHeader = partType$1.optional({
  26130. factory: { sketch: renderHeader },
  26131. name: 'header',
  26132. schema: [strict$1('dom')]
  26133. });
  26134. var partSocket = partType$1.optional({
  26135. name: 'socket',
  26136. schema: [strict$1('dom')]
  26137. });
  26138. var partSidebar = partType$1.optional({
  26139. factory: { sketch: renderSidebar },
  26140. name: 'sidebar',
  26141. schema: [strict$1('dom')]
  26142. });
  26143. var partThrobber = partType$1.optional({
  26144. factory: { sketch: renderThrobber },
  26145. name: 'throbber',
  26146. schema: [strict$1('dom')]
  26147. });
  26148. var OuterContainer = composite$1({
  26149. name: 'OuterContainer',
  26150. factory: factory$h,
  26151. configFields: [
  26152. strict$1('dom'),
  26153. strict$1('behaviours')
  26154. ],
  26155. partFields: [
  26156. partHeader,
  26157. partMenubar,
  26158. partToolbar,
  26159. partMultipleToolbar,
  26160. partSocket,
  26161. partSidebar,
  26162. partThrobber
  26163. ],
  26164. apis: {
  26165. getSocket: function (apis, comp) {
  26166. return apis.getSocket(comp);
  26167. },
  26168. setSidebar: function (apis, comp, panelConfigs) {
  26169. apis.setSidebar(comp, panelConfigs);
  26170. },
  26171. toggleSidebar: function (apis, comp, name) {
  26172. apis.toggleSidebar(comp, name);
  26173. },
  26174. whichSidebar: function (apis, comp) {
  26175. return apis.whichSidebar(comp);
  26176. },
  26177. getHeader: function (apis, comp) {
  26178. return apis.getHeader(comp);
  26179. },
  26180. getToolbar: function (apis, comp) {
  26181. return apis.getToolbar(comp);
  26182. },
  26183. setToolbar: function (apis, comp, grps) {
  26184. var groups = map(grps, function (grp) {
  26185. return renderToolbarGroup(grp);
  26186. });
  26187. apis.setToolbar(comp, groups);
  26188. },
  26189. setToolbars: function (apis, comp, ts) {
  26190. var renderedToolbars = map(ts, function (g) {
  26191. return map(g, renderToolbarGroup);
  26192. });
  26193. apis.setToolbars(comp, renderedToolbars);
  26194. },
  26195. refreshToolbar: function (apis, comp) {
  26196. return apis.refreshToolbar(comp);
  26197. },
  26198. toggleToolbarDrawer: function (apis, comp) {
  26199. apis.toggleToolbarDrawer(comp);
  26200. },
  26201. isToolbarDrawerToggled: function (apis, comp) {
  26202. return apis.isToolbarDrawerToggled(comp);
  26203. },
  26204. getThrobber: function (apis, comp) {
  26205. return apis.getThrobber(comp);
  26206. },
  26207. setMenubar: function (apis, comp, menus) {
  26208. apis.setMenubar(comp, menus);
  26209. },
  26210. focusMenubar: function (apis, comp) {
  26211. apis.focusMenubar(comp);
  26212. },
  26213. focusToolbar: function (apis, comp) {
  26214. apis.focusToolbar(comp);
  26215. }
  26216. }
  26217. });
  26218. var defaultMenubar = 'file edit view insert format tools table help';
  26219. var defaultMenus = {
  26220. file: {
  26221. title: 'File',
  26222. items: 'newdocument restoredraft | preview | export print | deleteallconversations'
  26223. },
  26224. edit: {
  26225. title: 'Edit',
  26226. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  26227. },
  26228. view: {
  26229. title: 'View',
  26230. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  26231. },
  26232. insert: {
  26233. title: 'Insert',
  26234. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  26235. },
  26236. format: {
  26237. title: 'Format',
  26238. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat'
  26239. },
  26240. tools: {
  26241. title: 'Tools',
  26242. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  26243. },
  26244. table: {
  26245. title: 'Table',
  26246. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  26247. },
  26248. help: {
  26249. title: 'Help',
  26250. items: 'help'
  26251. }
  26252. };
  26253. var make$8 = function (menu, registry, editor) {
  26254. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  26255. return {
  26256. text: menu.title,
  26257. getItems: function () {
  26258. return bind(menu.items, function (i) {
  26259. var itemName = i.toLowerCase();
  26260. if (itemName.trim().length === 0) {
  26261. return [];
  26262. } else if (exists(removedMenuItems, function (removedMenuItem) {
  26263. return removedMenuItem === itemName;
  26264. })) {
  26265. return [];
  26266. } else if (itemName === 'separator' || itemName === '|') {
  26267. return [{ type: 'separator' }];
  26268. } else if (registry.menuItems[itemName]) {
  26269. return [registry.menuItems[itemName]];
  26270. } else {
  26271. return [];
  26272. }
  26273. });
  26274. }
  26275. };
  26276. };
  26277. var parseItemsString = function (items) {
  26278. if (typeof items === 'string') {
  26279. return items.split(' ');
  26280. }
  26281. return items;
  26282. };
  26283. var identifyMenus = function (editor, registry) {
  26284. var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  26285. var userDefinedMenus = keys(registry.menus).length > 0;
  26286. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  26287. var validMenus = filter(menubar, function (menuName) {
  26288. return userDefinedMenus ? registry.menus.hasOwnProperty(menuName) && registry.menus[menuName].hasOwnProperty('items') || defaultMenus.hasOwnProperty(menuName) : defaultMenus.hasOwnProperty(menuName);
  26289. });
  26290. var menus = map(validMenus, function (menuName) {
  26291. var menuData = rawMenuData[menuName];
  26292. return make$8({
  26293. title: menuData.title,
  26294. items: parseItemsString(menuData.items)
  26295. }, registry, editor);
  26296. });
  26297. return filter(menus, function (menu) {
  26298. var isNotSeparator = function (item) {
  26299. return item.type !== 'separator';
  26300. };
  26301. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  26302. });
  26303. };
  26304. var fireSkinLoaded$1 = function (editor) {
  26305. var done = function () {
  26306. editor._skinLoaded = true;
  26307. fireSkinLoaded(editor);
  26308. };
  26309. return function () {
  26310. if (editor.initialized) {
  26311. done();
  26312. } else {
  26313. editor.on('init', done);
  26314. }
  26315. };
  26316. };
  26317. var fireSkinLoadError$1 = function (editor, err) {
  26318. return function () {
  26319. return fireSkinLoadError(editor, { message: err });
  26320. };
  26321. };
  26322. var loadSkin = function (isInline, editor) {
  26323. var skinUrl = getSkinUrl(editor);
  26324. var skinUiCss;
  26325. if (skinUrl) {
  26326. skinUiCss = skinUrl + '/skin.min.css';
  26327. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  26328. }
  26329. if (isSkinDisabled(editor) === false && skinUiCss) {
  26330. var styleSheetLoader_1 = editor.ui.styleSheetLoader;
  26331. styleSheetLoader_1.load(skinUiCss, fireSkinLoaded$1(editor), fireSkinLoadError$1(editor, 'Skin could not be loaded'));
  26332. editor.on('remove', function () {
  26333. return styleSheetLoader_1.unload(skinUiCss);
  26334. });
  26335. } else {
  26336. fireSkinLoaded$1(editor)();
  26337. }
  26338. };
  26339. var iframe = curry(loadSkin, false);
  26340. var inline = curry(loadSkin, true);
  26341. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  26342. var comp = uiComponents.outerContainer;
  26343. var toolbarConfig = rawUiConfig.toolbar;
  26344. var toolbarButtonsConfig = rawUiConfig.buttons;
  26345. if (isArrayOf(toolbarConfig, isString)) {
  26346. var toolbars = toolbarConfig.map(function (t) {
  26347. var config = {
  26348. toolbar: t,
  26349. buttons: toolbarButtonsConfig,
  26350. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  26351. };
  26352. return identifyButtons(editor, config, { backstage: backstage }, Optional.none());
  26353. });
  26354. OuterContainer.setToolbars(comp, toolbars);
  26355. } else {
  26356. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none()));
  26357. }
  26358. };
  26359. var DOM = global$5.DOM;
  26360. var detection = detect$3();
  26361. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  26362. var setupEvents = function (editor, uiComponents) {
  26363. var contentWindow = editor.getWin();
  26364. var initialDocEle = editor.getDoc().documentElement;
  26365. var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  26366. var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  26367. var resizeWindow = function () {
  26368. var outer = lastWindowDimensions.get();
  26369. if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
  26370. lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  26371. fireResizeContent(editor);
  26372. }
  26373. };
  26374. var resizeDocument = function () {
  26375. var docEle = editor.getDoc().documentElement;
  26376. var inner = lastDocumentDimensions.get();
  26377. if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
  26378. lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
  26379. fireResizeContent(editor);
  26380. }
  26381. };
  26382. var scroll = function (e) {
  26383. return fireScrollContent(editor, e);
  26384. };
  26385. DOM.bind(contentWindow, 'resize', resizeWindow);
  26386. DOM.bind(contentWindow, 'scroll', scroll);
  26387. var elementLoad = capture$1(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
  26388. var mothership = uiComponents.uiMothership.element;
  26389. editor.on('hide', function () {
  26390. set$2(mothership, 'display', 'none');
  26391. });
  26392. editor.on('show', function () {
  26393. remove$6(mothership, 'display');
  26394. });
  26395. editor.on('NodeChange', resizeDocument);
  26396. editor.on('remove', function () {
  26397. elementLoad.unbind();
  26398. DOM.unbind(contentWindow, 'resize', resizeWindow);
  26399. DOM.unbind(contentWindow, 'scroll', scroll);
  26400. });
  26401. };
  26402. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26403. var lastToolbarWidth = Cell(0);
  26404. var outerContainer = uiComponents.outerContainer;
  26405. iframe(editor);
  26406. var eTargetNode = SugarElement.fromDom(args.targetNode);
  26407. var uiRoot = getContentContainer(getRootNode(eTargetNode));
  26408. attachSystemAfter(eTargetNode, uiComponents.mothership);
  26409. attachSystem(uiRoot, uiComponents.uiMothership);
  26410. editor.on('PostRender', function () {
  26411. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26412. lastToolbarWidth.set(editor.getWin().innerWidth);
  26413. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26414. OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
  26415. setupEvents(editor, uiComponents);
  26416. });
  26417. var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
  26418. if (isiOS12) {
  26419. setAll$1(socket.element, {
  26420. 'overflow': 'scroll',
  26421. '-webkit-overflow-scrolling': 'touch'
  26422. });
  26423. var limit = first(function () {
  26424. editor.fire('ScrollContent');
  26425. }, 20);
  26426. bind$3(socket.element, 'scroll', limit.throttle);
  26427. }
  26428. setupReadonlyModeSwitch(editor, uiComponents);
  26429. editor.addCommand('ToggleSidebar', function (_ui, value) {
  26430. OuterContainer.toggleSidebar(outerContainer, value);
  26431. editor.fire('ToggleSidebar');
  26432. });
  26433. editor.addQueryValueHandler('ToggleSidebar', function () {
  26434. return OuterContainer.whichSidebar(outerContainer);
  26435. });
  26436. var toolbarMode = getToolbarMode(editor);
  26437. var refreshDrawer = function () {
  26438. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  26439. };
  26440. if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  26441. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  26442. var width = editor.getWin().innerWidth;
  26443. if (width !== lastToolbarWidth.get()) {
  26444. refreshDrawer();
  26445. lastToolbarWidth.set(width);
  26446. }
  26447. });
  26448. }
  26449. return {
  26450. iframeContainer: socket.element.dom,
  26451. editorContainer: outerContainer.element.dom
  26452. };
  26453. };
  26454. var Iframe = /*#__PURE__*/Object.freeze({
  26455. __proto__: null,
  26456. render: render
  26457. });
  26458. var parseToInt = function (val) {
  26459. var re = /^[0-9\.]+(|px)$/i;
  26460. if (re.test('' + val)) {
  26461. return Optional.some(parseInt('' + val, 10));
  26462. }
  26463. return Optional.none();
  26464. };
  26465. var numToPx = function (val) {
  26466. return isNumber(val) ? val + 'px' : val;
  26467. };
  26468. var calcCappedSize = function (size, minSize, maxSize) {
  26469. var minOverride = minSize.filter(function (min) {
  26470. return size < min;
  26471. });
  26472. var maxOverride = maxSize.filter(function (max) {
  26473. return size > max;
  26474. });
  26475. return minOverride.or(maxOverride).getOr(size);
  26476. };
  26477. var getHeight$1 = function (editor) {
  26478. var baseHeight = getHeightSetting(editor);
  26479. var minHeight = getMinHeightSetting(editor);
  26480. var maxHeight = getMaxHeightSetting(editor);
  26481. return parseToInt(baseHeight).map(function (height) {
  26482. return calcCappedSize(height, minHeight, maxHeight);
  26483. });
  26484. };
  26485. var getHeightWithFallback = function (editor) {
  26486. var height = getHeight$1(editor);
  26487. return height.getOr(getHeightSetting(editor));
  26488. };
  26489. var getWidth$1 = function (editor) {
  26490. var baseWidth = getWidthSetting(editor);
  26491. var minWidth = getMinWidthSetting(editor);
  26492. var maxWidth = getMaxWidthSetting(editor);
  26493. return parseToInt(baseWidth).map(function (width) {
  26494. return calcCappedSize(width, minWidth, maxWidth);
  26495. });
  26496. };
  26497. var getWidthWithFallback = function (editor) {
  26498. var width = getWidth$1(editor);
  26499. return width.getOr(getWidthSetting(editor));
  26500. };
  26501. var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
  26502. var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26503. var DOM = global$5.DOM;
  26504. var useFixedToolbarContainer = useFixedContainer(editor);
  26505. var isSticky = isStickyToolbar(editor);
  26506. var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth$1(editor));
  26507. var headerBackstage = backstage.shared.header;
  26508. var isPositionedAtTop = headerBackstage.isPositionedAtTop;
  26509. var toolbarMode = getToolbarMode(editor);
  26510. var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  26511. var visible = Cell(false);
  26512. var isVisible = function () {
  26513. return visible.get() && !editor.removed;
  26514. };
  26515. var calcToolbarOffset = function (toolbar) {
  26516. return isSplitToolbar ? toolbar.fold(function () {
  26517. return 0;
  26518. }, function (tbar) {
  26519. return tbar.components().length > 1 ? get$6(tbar.components()[1].element) : 0;
  26520. }) : 0;
  26521. };
  26522. var calcMode = function (container) {
  26523. switch (getToolbarLocation(editor)) {
  26524. case ToolbarLocation.auto:
  26525. var toolbar_1 = OuterContainer.getToolbar(outerContainer);
  26526. var offset = calcToolbarOffset(toolbar_1);
  26527. var toolbarHeight = get$6(container.element) - offset;
  26528. var targetBounds = box(targetElm);
  26529. var roomAtTop = targetBounds.y > toolbarHeight;
  26530. if (roomAtTop) {
  26531. return 'top';
  26532. } else {
  26533. var doc = documentElement(targetElm);
  26534. var docHeight = Math.max(doc.dom.scrollHeight, get$6(doc));
  26535. var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  26536. if (roomAtBottom) {
  26537. return 'bottom';
  26538. } else {
  26539. var winBounds = win();
  26540. var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  26541. return isRoomAtBottomViewport ? 'bottom' : 'top';
  26542. }
  26543. }
  26544. case ToolbarLocation.bottom:
  26545. return 'bottom';
  26546. case ToolbarLocation.top:
  26547. default:
  26548. return 'top';
  26549. }
  26550. };
  26551. var setupMode = function (mode) {
  26552. var container = floatContainer.get();
  26553. Docking.setModes(container, [mode]);
  26554. headerBackstage.setDockingMode(mode);
  26555. var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  26556. set$1(container.element, Attribute, verticalDir);
  26557. };
  26558. var updateChromeWidth = function () {
  26559. var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  26560. var bodyMargin = parseToInt(get$4(body(), 'margin-left')).getOr(0);
  26561. return get$7(body()) - absolute(targetElm).left + bodyMargin;
  26562. });
  26563. set$2(floatContainer.get().element, 'max-width', maxWidth + 'px');
  26564. };
  26565. var updateChromePosition = function () {
  26566. var toolbar = OuterContainer.getToolbar(outerContainer);
  26567. var offset = calcToolbarOffset(toolbar);
  26568. var targetBounds = box(targetElm);
  26569. var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$6(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
  26570. setAll$1(outerContainer.element, {
  26571. position: 'absolute',
  26572. top: Math.round(top) + 'px',
  26573. left: Math.round(targetBounds.x) + 'px'
  26574. });
  26575. };
  26576. var repositionPopups$1 = function () {
  26577. uiMothership.broadcastOn([repositionPopups()], {});
  26578. };
  26579. var updateChromeUi = function (resetDocking) {
  26580. if (resetDocking === void 0) {
  26581. resetDocking = false;
  26582. }
  26583. if (!isVisible()) {
  26584. return;
  26585. }
  26586. if (!useFixedToolbarContainer) {
  26587. updateChromeWidth();
  26588. }
  26589. if (isSplitToolbar) {
  26590. OuterContainer.refreshToolbar(outerContainer);
  26591. }
  26592. if (!useFixedToolbarContainer) {
  26593. updateChromePosition();
  26594. }
  26595. if (isSticky) {
  26596. var floatContainerComp = floatContainer.get();
  26597. resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  26598. }
  26599. repositionPopups$1();
  26600. };
  26601. var updateMode = function (updateUi) {
  26602. if (updateUi === void 0) {
  26603. updateUi = true;
  26604. }
  26605. if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  26606. return;
  26607. }
  26608. var currentMode = headerBackstage.getDockingMode();
  26609. var newMode = calcMode(floatContainer.get());
  26610. if (newMode !== currentMode) {
  26611. setupMode(newMode);
  26612. if (updateUi) {
  26613. updateChromeUi(true);
  26614. }
  26615. }
  26616. };
  26617. var show = function () {
  26618. visible.set(true);
  26619. set$2(outerContainer.element, 'display', 'flex');
  26620. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  26621. remove$6(uiMothership.element, 'display');
  26622. updateMode(false);
  26623. updateChromeUi();
  26624. };
  26625. var hide = function () {
  26626. visible.set(false);
  26627. if (uiComponents.outerContainer) {
  26628. set$2(outerContainer.element, 'display', 'none');
  26629. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  26630. }
  26631. set$2(uiMothership.element, 'display', 'none');
  26632. };
  26633. return {
  26634. isVisible: isVisible,
  26635. isPositionedAtTop: isPositionedAtTop,
  26636. show: show,
  26637. hide: hide,
  26638. update: updateChromeUi,
  26639. updateMode: updateMode,
  26640. repositionPopups: repositionPopups$1
  26641. };
  26642. };
  26643. var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
  26644. var bounds = box(targetElm);
  26645. return {
  26646. pos: isToolbarTop ? bounds.y : bounds.bottom,
  26647. bounds: bounds
  26648. };
  26649. };
  26650. var setupEvents$1 = function (editor, targetElm, ui, toolbarPersist) {
  26651. var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  26652. var resizeContent = function (e) {
  26653. var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
  26654. var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
  26655. var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  26656. prevPosAndBounds.set({
  26657. pos: pos,
  26658. bounds: bounds
  26659. });
  26660. if (hasResized) {
  26661. fireResizeContent(editor, e);
  26662. }
  26663. if (ui.isVisible()) {
  26664. if (prevPos !== pos) {
  26665. ui.update(true);
  26666. } else if (hasResized) {
  26667. ui.updateMode();
  26668. ui.repositionPopups();
  26669. }
  26670. }
  26671. };
  26672. if (!toolbarPersist) {
  26673. editor.on('activate', ui.show);
  26674. editor.on('deactivate', ui.hide);
  26675. }
  26676. editor.on('SkinLoaded ResizeWindow', function () {
  26677. return ui.update(true);
  26678. });
  26679. editor.on('NodeChange keydown', function (e) {
  26680. global$2.requestAnimationFrame(function () {
  26681. return resizeContent(e);
  26682. });
  26683. });
  26684. editor.on('ScrollWindow', function () {
  26685. return ui.updateMode();
  26686. });
  26687. var elementLoad = unbindable();
  26688. elementLoad.set(capture$1(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
  26689. editor.on('remove', function () {
  26690. elementLoad.clear();
  26691. });
  26692. };
  26693. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26694. var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26695. var floatContainer = Cell(null);
  26696. var targetElm = SugarElement.fromDom(args.targetNode);
  26697. var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  26698. var toolbarPersist = isToolbarPersist(editor);
  26699. inline(editor);
  26700. var render = function () {
  26701. if (floatContainer.get()) {
  26702. ui.show();
  26703. return;
  26704. }
  26705. floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  26706. var uiContainer = getUiContainer(editor);
  26707. attachSystem(uiContainer, mothership);
  26708. attachSystem(uiContainer, uiMothership);
  26709. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26710. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26711. ui.show();
  26712. setupEvents$1(editor, targetElm, ui, toolbarPersist);
  26713. editor.nodeChanged();
  26714. };
  26715. editor.on('show', render);
  26716. editor.on('hide', ui.hide);
  26717. if (!toolbarPersist) {
  26718. editor.on('focus', render);
  26719. editor.on('blur', ui.hide);
  26720. }
  26721. editor.on('init', function () {
  26722. if (editor.hasFocus() || toolbarPersist) {
  26723. render();
  26724. }
  26725. });
  26726. setupReadonlyModeSwitch(editor, uiComponents);
  26727. var api = {
  26728. show: function () {
  26729. ui.show();
  26730. },
  26731. hide: function () {
  26732. ui.hide();
  26733. }
  26734. };
  26735. return {
  26736. editorContainer: outerContainer.element.dom,
  26737. api: api
  26738. };
  26739. };
  26740. var Inline = /*#__PURE__*/Object.freeze({
  26741. __proto__: null,
  26742. render: render$1
  26743. });
  26744. var register$5 = function (editor) {
  26745. var alignToolbarButtons = [
  26746. {
  26747. name: 'alignleft',
  26748. text: 'Align left',
  26749. cmd: 'JustifyLeft',
  26750. icon: 'align-left'
  26751. },
  26752. {
  26753. name: 'aligncenter',
  26754. text: 'Align center',
  26755. cmd: 'JustifyCenter',
  26756. icon: 'align-center'
  26757. },
  26758. {
  26759. name: 'alignright',
  26760. text: 'Align right',
  26761. cmd: 'JustifyRight',
  26762. icon: 'align-right'
  26763. },
  26764. {
  26765. name: 'alignjustify',
  26766. text: 'Justify',
  26767. cmd: 'JustifyFull',
  26768. icon: 'align-justify'
  26769. }
  26770. ];
  26771. global$e.each(alignToolbarButtons, function (item) {
  26772. editor.ui.registry.addToggleButton(item.name, {
  26773. tooltip: item.text,
  26774. onAction: function () {
  26775. return editor.execCommand(item.cmd);
  26776. },
  26777. icon: item.icon,
  26778. onSetup: onSetupFormatToggle(editor, item.name)
  26779. });
  26780. });
  26781. var alignNoneToolbarButton = {
  26782. name: 'alignnone',
  26783. text: 'No alignment',
  26784. cmd: 'JustifyNone',
  26785. icon: 'align-none'
  26786. };
  26787. editor.ui.registry.addButton(alignNoneToolbarButton.name, {
  26788. tooltip: alignNoneToolbarButton.text,
  26789. onAction: function () {
  26790. return editor.execCommand(alignNoneToolbarButton.cmd);
  26791. },
  26792. icon: alignNoneToolbarButton.icon
  26793. });
  26794. };
  26795. var register$6 = function (editor, backstage) {
  26796. alignSelectMenu(editor, backstage);
  26797. fontSelectMenu(editor, backstage);
  26798. styleSelectMenu(editor, backstage);
  26799. formatSelectMenu(editor, backstage);
  26800. fontsizeSelectMenu(editor, backstage);
  26801. };
  26802. var toggleOutdentState = function (api, editor) {
  26803. api.setDisabled(!editor.queryCommandState('outdent'));
  26804. var onNodeChange = function () {
  26805. api.setDisabled(!editor.queryCommandState('outdent'));
  26806. };
  26807. editor.on('NodeChange', onNodeChange);
  26808. return function () {
  26809. return editor.off('NodeChange', onNodeChange);
  26810. };
  26811. };
  26812. var registerButtons = function (editor) {
  26813. editor.ui.registry.addButton('outdent', {
  26814. tooltip: 'Decrease indent',
  26815. icon: 'outdent',
  26816. onSetup: function (api) {
  26817. return toggleOutdentState(api, editor);
  26818. },
  26819. onAction: function () {
  26820. return editor.execCommand('outdent');
  26821. }
  26822. });
  26823. editor.ui.registry.addButton('indent', {
  26824. tooltip: 'Increase indent',
  26825. icon: 'indent',
  26826. onAction: function () {
  26827. return editor.execCommand('indent');
  26828. }
  26829. });
  26830. };
  26831. var register$7 = function (editor) {
  26832. registerButtons(editor);
  26833. };
  26834. var toggleFormat = function (editor, fmt) {
  26835. return function () {
  26836. editor.execCommand('mceToggleFormat', false, fmt);
  26837. };
  26838. };
  26839. var registerFormatButtons = function (editor) {
  26840. global$e.each([
  26841. {
  26842. name: 'bold',
  26843. text: 'Bold',
  26844. icon: 'bold'
  26845. },
  26846. {
  26847. name: 'italic',
  26848. text: 'Italic',
  26849. icon: 'italic'
  26850. },
  26851. {
  26852. name: 'underline',
  26853. text: 'Underline',
  26854. icon: 'underline'
  26855. },
  26856. {
  26857. name: 'strikethrough',
  26858. text: 'Strikethrough',
  26859. icon: 'strike-through'
  26860. },
  26861. {
  26862. name: 'subscript',
  26863. text: 'Subscript',
  26864. icon: 'subscript'
  26865. },
  26866. {
  26867. name: 'superscript',
  26868. text: 'Superscript',
  26869. icon: 'superscript'
  26870. }
  26871. ], function (btn, _idx) {
  26872. editor.ui.registry.addToggleButton(btn.name, {
  26873. tooltip: btn.text,
  26874. icon: btn.icon,
  26875. onSetup: onSetupFormatToggle(editor, btn.name),
  26876. onAction: toggleFormat(editor, btn.name)
  26877. });
  26878. });
  26879. for (var i = 1; i <= 6; i++) {
  26880. var name_1 = 'h' + i;
  26881. editor.ui.registry.addToggleButton(name_1, {
  26882. text: name_1.toUpperCase(),
  26883. tooltip: 'Heading ' + i,
  26884. onSetup: onSetupFormatToggle(editor, name_1),
  26885. onAction: toggleFormat(editor, name_1)
  26886. });
  26887. }
  26888. };
  26889. var registerCommandButtons = function (editor) {
  26890. global$e.each([
  26891. {
  26892. name: 'cut',
  26893. text: 'Cut',
  26894. action: 'Cut',
  26895. icon: 'cut'
  26896. },
  26897. {
  26898. name: 'copy',
  26899. text: 'Copy',
  26900. action: 'Copy',
  26901. icon: 'copy'
  26902. },
  26903. {
  26904. name: 'paste',
  26905. text: 'Paste',
  26906. action: 'Paste',
  26907. icon: 'paste'
  26908. },
  26909. {
  26910. name: 'help',
  26911. text: 'Help',
  26912. action: 'mceHelp',
  26913. icon: 'help'
  26914. },
  26915. {
  26916. name: 'selectall',
  26917. text: 'Select all',
  26918. action: 'SelectAll',
  26919. icon: 'select-all'
  26920. },
  26921. {
  26922. name: 'newdocument',
  26923. text: 'New document',
  26924. action: 'mceNewDocument',
  26925. icon: 'new-document'
  26926. },
  26927. {
  26928. name: 'removeformat',
  26929. text: 'Clear formatting',
  26930. action: 'RemoveFormat',
  26931. icon: 'remove-formatting'
  26932. },
  26933. {
  26934. name: 'remove',
  26935. text: 'Remove',
  26936. action: 'Delete',
  26937. icon: 'remove'
  26938. }
  26939. ], function (btn) {
  26940. editor.ui.registry.addButton(btn.name, {
  26941. tooltip: btn.text,
  26942. icon: btn.icon,
  26943. onAction: function () {
  26944. return editor.execCommand(btn.action);
  26945. }
  26946. });
  26947. });
  26948. };
  26949. var registerCommandToggleButtons = function (editor) {
  26950. global$e.each([{
  26951. name: 'blockquote',
  26952. text: 'Blockquote',
  26953. action: 'mceBlockQuote',
  26954. icon: 'quote'
  26955. }], function (btn) {
  26956. editor.ui.registry.addToggleButton(btn.name, {
  26957. tooltip: btn.text,
  26958. icon: btn.icon,
  26959. onAction: function () {
  26960. return editor.execCommand(btn.action);
  26961. },
  26962. onSetup: onSetupFormatToggle(editor, btn.name)
  26963. });
  26964. });
  26965. };
  26966. var registerButtons$1 = function (editor) {
  26967. registerFormatButtons(editor);
  26968. registerCommandButtons(editor);
  26969. registerCommandToggleButtons(editor);
  26970. };
  26971. var registerMenuItems = function (editor) {
  26972. global$e.each([
  26973. {
  26974. name: 'bold',
  26975. text: 'Bold',
  26976. action: 'Bold',
  26977. icon: 'bold',
  26978. shortcut: 'Meta+B'
  26979. },
  26980. {
  26981. name: 'italic',
  26982. text: 'Italic',
  26983. action: 'Italic',
  26984. icon: 'italic',
  26985. shortcut: 'Meta+I'
  26986. },
  26987. {
  26988. name: 'underline',
  26989. text: 'Underline',
  26990. action: 'Underline',
  26991. icon: 'underline',
  26992. shortcut: 'Meta+U'
  26993. },
  26994. {
  26995. name: 'strikethrough',
  26996. text: 'Strikethrough',
  26997. action: 'Strikethrough',
  26998. icon: 'strike-through',
  26999. shortcut: ''
  27000. },
  27001. {
  27002. name: 'subscript',
  27003. text: 'Subscript',
  27004. action: 'Subscript',
  27005. icon: 'subscript',
  27006. shortcut: ''
  27007. },
  27008. {
  27009. name: 'superscript',
  27010. text: 'Superscript',
  27011. action: 'Superscript',
  27012. icon: 'superscript',
  27013. shortcut: ''
  27014. },
  27015. {
  27016. name: 'removeformat',
  27017. text: 'Clear formatting',
  27018. action: 'RemoveFormat',
  27019. icon: 'remove-formatting',
  27020. shortcut: ''
  27021. },
  27022. {
  27023. name: 'newdocument',
  27024. text: 'New document',
  27025. action: 'mceNewDocument',
  27026. icon: 'new-document',
  27027. shortcut: ''
  27028. },
  27029. {
  27030. name: 'cut',
  27031. text: 'Cut',
  27032. action: 'Cut',
  27033. icon: 'cut',
  27034. shortcut: 'Meta+X'
  27035. },
  27036. {
  27037. name: 'copy',
  27038. text: 'Copy',
  27039. action: 'Copy',
  27040. icon: 'copy',
  27041. shortcut: 'Meta+C'
  27042. },
  27043. {
  27044. name: 'paste',
  27045. text: 'Paste',
  27046. action: 'Paste',
  27047. icon: 'paste',
  27048. shortcut: 'Meta+V'
  27049. },
  27050. {
  27051. name: 'selectall',
  27052. text: 'Select all',
  27053. action: 'SelectAll',
  27054. icon: 'select-all',
  27055. shortcut: 'Meta+A'
  27056. }
  27057. ], function (btn) {
  27058. editor.ui.registry.addMenuItem(btn.name, {
  27059. text: btn.text,
  27060. icon: btn.icon,
  27061. shortcut: btn.shortcut,
  27062. onAction: function () {
  27063. return editor.execCommand(btn.action);
  27064. }
  27065. });
  27066. });
  27067. editor.ui.registry.addMenuItem('codeformat', {
  27068. text: 'Code',
  27069. icon: 'sourcecode',
  27070. onAction: toggleFormat(editor, 'code')
  27071. });
  27072. };
  27073. var register$8 = function (editor) {
  27074. registerButtons$1(editor);
  27075. registerMenuItems(editor);
  27076. };
  27077. var toggleUndoRedoState = function (api, editor, type) {
  27078. var checkState = function () {
  27079. return editor.undoManager ? editor.undoManager[type]() : false;
  27080. };
  27081. var onUndoStateChange = function () {
  27082. api.setDisabled(editor.mode.isReadOnly() || !checkState());
  27083. };
  27084. api.setDisabled(!checkState());
  27085. editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  27086. return function () {
  27087. return editor.off('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  27088. };
  27089. };
  27090. var registerMenuItems$1 = function (editor) {
  27091. editor.ui.registry.addMenuItem('undo', {
  27092. text: 'Undo',
  27093. icon: 'undo',
  27094. shortcut: 'Meta+Z',
  27095. onSetup: function (api) {
  27096. return toggleUndoRedoState(api, editor, 'hasUndo');
  27097. },
  27098. onAction: function () {
  27099. return editor.execCommand('undo');
  27100. }
  27101. });
  27102. editor.ui.registry.addMenuItem('redo', {
  27103. text: 'Redo',
  27104. icon: 'redo',
  27105. shortcut: 'Meta+Y',
  27106. onSetup: function (api) {
  27107. return toggleUndoRedoState(api, editor, 'hasRedo');
  27108. },
  27109. onAction: function () {
  27110. return editor.execCommand('redo');
  27111. }
  27112. });
  27113. };
  27114. var registerButtons$2 = function (editor) {
  27115. editor.ui.registry.addButton('undo', {
  27116. tooltip: 'Undo',
  27117. icon: 'undo',
  27118. onSetup: function (api) {
  27119. return toggleUndoRedoState(api, editor, 'hasUndo');
  27120. },
  27121. onAction: function () {
  27122. return editor.execCommand('undo');
  27123. }
  27124. });
  27125. editor.ui.registry.addButton('redo', {
  27126. tooltip: 'Redo',
  27127. icon: 'redo',
  27128. onSetup: function (api) {
  27129. return toggleUndoRedoState(api, editor, 'hasRedo');
  27130. },
  27131. onAction: function () {
  27132. return editor.execCommand('redo');
  27133. }
  27134. });
  27135. };
  27136. var register$9 = function (editor) {
  27137. registerMenuItems$1(editor);
  27138. registerButtons$2(editor);
  27139. };
  27140. var toggleVisualAidState = function (api, editor) {
  27141. api.setActive(editor.hasVisual);
  27142. var onVisualAid = function (e) {
  27143. api.setActive(e.hasVisual);
  27144. };
  27145. editor.on('VisualAid', onVisualAid);
  27146. return function () {
  27147. return editor.off('VisualAid', onVisualAid);
  27148. };
  27149. };
  27150. var registerMenuItems$2 = function (editor) {
  27151. editor.ui.registry.addToggleMenuItem('visualaid', {
  27152. text: 'Visual aids',
  27153. onSetup: function (api) {
  27154. return toggleVisualAidState(api, editor);
  27155. },
  27156. onAction: function () {
  27157. editor.execCommand('mceToggleVisualAid');
  27158. }
  27159. });
  27160. };
  27161. var registerToolbarButton = function (editor) {
  27162. editor.ui.registry.addButton('visualaid', {
  27163. tooltip: 'Visual aids',
  27164. text: 'Visual aids',
  27165. onAction: function () {
  27166. return editor.execCommand('mceToggleVisualAid');
  27167. }
  27168. });
  27169. };
  27170. var register$a = function (editor) {
  27171. registerToolbarButton(editor);
  27172. registerMenuItems$2(editor);
  27173. };
  27174. var units = {
  27175. unsupportedLength: [
  27176. 'em',
  27177. 'ex',
  27178. 'cap',
  27179. 'ch',
  27180. 'ic',
  27181. 'rem',
  27182. 'lh',
  27183. 'rlh',
  27184. 'vw',
  27185. 'vh',
  27186. 'vi',
  27187. 'vb',
  27188. 'vmin',
  27189. 'vmax',
  27190. 'cm',
  27191. 'mm',
  27192. 'Q',
  27193. 'in',
  27194. 'pc',
  27195. 'pt',
  27196. 'px'
  27197. ],
  27198. fixed: [
  27199. 'px',
  27200. 'pt'
  27201. ],
  27202. relative: ['%'],
  27203. empty: ['']
  27204. };
  27205. var pattern = function () {
  27206. var decimalDigits = '[0-9]+';
  27207. var signedInteger = '[+-]?' + decimalDigits;
  27208. var exponentPart = '[eE]' + signedInteger;
  27209. var dot = '\\.';
  27210. var opt = function (input) {
  27211. return '(?:' + input + ')?';
  27212. };
  27213. var unsignedDecimalLiteral = [
  27214. 'Infinity',
  27215. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  27216. dot + decimalDigits + opt(exponentPart),
  27217. decimalDigits + opt(exponentPart)
  27218. ].join('|');
  27219. var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  27220. return new RegExp('^(' + float + ')(.*)$');
  27221. }();
  27222. var isUnit = function (unit, accepted) {
  27223. return exists(accepted, function (acc) {
  27224. return exists(units[acc], function (check) {
  27225. return unit === check;
  27226. });
  27227. });
  27228. };
  27229. var parse = function (input, accepted) {
  27230. var match = Optional.from(pattern.exec(input));
  27231. return match.bind(function (array) {
  27232. var value = Number(array[1]);
  27233. var unitRaw = array[2];
  27234. if (isUnit(unitRaw, accepted)) {
  27235. return Optional.some({
  27236. value: value,
  27237. unit: unitRaw
  27238. });
  27239. } else {
  27240. return Optional.none();
  27241. }
  27242. });
  27243. };
  27244. var normalise = function (input, accepted) {
  27245. return parse(input, accepted).map(function (_a) {
  27246. var value = _a.value, unit = _a.unit;
  27247. return value + unit;
  27248. });
  27249. };
  27250. var normaliseLineHeight = function (input) {
  27251. return normalise(input, [
  27252. 'fixed',
  27253. 'relative',
  27254. 'empty'
  27255. ]).getOr(input);
  27256. };
  27257. var getLineHeights = function (editor) {
  27258. var options = getLineHeightFormats(editor);
  27259. var apis = new Map();
  27260. var lastApi = destroyable();
  27261. var callback = function () {
  27262. var current = normaliseLineHeight(editor.queryCommandValue('LineHeight'));
  27263. Optional.from(apis.get(current)).fold(function () {
  27264. return lastApi.clear();
  27265. }, function (api) {
  27266. lastApi.set({
  27267. destroy: function () {
  27268. api.setActive(false);
  27269. }
  27270. });
  27271. api.setActive(true);
  27272. });
  27273. };
  27274. editor.on('nodeChange', callback);
  27275. return map(options, function (value, i) {
  27276. return {
  27277. type: 'togglemenuitem',
  27278. text: value,
  27279. onSetup: function (api) {
  27280. apis.set(normaliseLineHeight(value), api);
  27281. if (i + 1 === options.length) {
  27282. callback();
  27283. }
  27284. return function () {
  27285. if (i === 0) {
  27286. editor.off('nodeChange', callback);
  27287. lastApi.clear();
  27288. }
  27289. };
  27290. },
  27291. onAction: function () {
  27292. return editor.execCommand('LineHeight', false, value);
  27293. }
  27294. };
  27295. });
  27296. };
  27297. var registerMenuItems$3 = function (editor) {
  27298. editor.ui.registry.addNestedMenuItem('lineheight', {
  27299. type: 'nestedmenuitem',
  27300. text: 'Line height',
  27301. getSubmenuItems: function () {
  27302. return getLineHeights(editor);
  27303. }
  27304. });
  27305. };
  27306. var registerButtons$3 = function (editor) {
  27307. editor.ui.registry.addMenuButton('lineheight', {
  27308. tooltip: 'Line height',
  27309. icon: 'line-height',
  27310. fetch: function (callback) {
  27311. return callback(getLineHeights(editor));
  27312. }
  27313. });
  27314. };
  27315. var register$b = function (editor) {
  27316. registerMenuItems$3(editor);
  27317. registerButtons$3(editor);
  27318. };
  27319. var setup$8 = function (editor, backstage) {
  27320. register$5(editor);
  27321. register$8(editor);
  27322. register$6(editor, backstage);
  27323. register$9(editor);
  27324. register$1(editor);
  27325. register$a(editor);
  27326. register$7(editor);
  27327. register$b(editor);
  27328. };
  27329. var nu$d = function (x, y) {
  27330. return {
  27331. anchor: 'makeshift',
  27332. x: x,
  27333. y: y
  27334. };
  27335. };
  27336. var transpose$1 = function (pos, dx, dy) {
  27337. return nu$d(pos.x + dx, pos.y + dy);
  27338. };
  27339. var isTouchEvent$1 = function (e) {
  27340. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  27341. };
  27342. var fromPageXY = function (e) {
  27343. if (isTouchEvent$1(e)) {
  27344. var touch = e.touches[0];
  27345. return nu$d(touch.pageX, touch.pageY);
  27346. } else {
  27347. return nu$d(e.pageX, e.pageY);
  27348. }
  27349. };
  27350. var fromClientXY = function (e) {
  27351. if (isTouchEvent$1(e)) {
  27352. var touch = e.touches[0];
  27353. return nu$d(touch.clientX, touch.clientY);
  27354. } else {
  27355. return nu$d(e.clientX, e.clientY);
  27356. }
  27357. };
  27358. var transposeContentAreaContainer = function (element, pos) {
  27359. var containerPos = global$5.DOM.getPos(element);
  27360. return transpose$1(pos, containerPos.x, containerPos.y);
  27361. };
  27362. var getPointAnchor = function (editor, e) {
  27363. if (e.type === 'contextmenu' || e.type === 'longpress') {
  27364. if (editor.inline) {
  27365. return fromPageXY(e);
  27366. } else {
  27367. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  27368. }
  27369. } else {
  27370. return getSelectionAnchor(editor);
  27371. }
  27372. };
  27373. var getSelectionAnchor = function (editor) {
  27374. return {
  27375. anchor: 'selection',
  27376. root: SugarElement.fromDom(editor.selection.getNode())
  27377. };
  27378. };
  27379. var getNodeAnchor$1 = function (editor) {
  27380. return {
  27381. anchor: 'node',
  27382. node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
  27383. root: SugarElement.fromDom(editor.getBody())
  27384. };
  27385. };
  27386. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, useNodeAnchor) {
  27387. var items = buildMenu();
  27388. var anchorSpec = useNodeAnchor ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  27389. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  27390. e.preventDefault();
  27391. InlineView.showMenuAt(contextmenu, anchorSpec, {
  27392. menu: { markers: markers$1('normal') },
  27393. data: menuData
  27394. });
  27395. });
  27396. };
  27397. var layouts = {
  27398. onLtr: function () {
  27399. return [
  27400. south$1,
  27401. southeast$1,
  27402. southwest$1,
  27403. northeast$1,
  27404. northwest$1,
  27405. north$1,
  27406. north$3,
  27407. south$3,
  27408. northeast$3,
  27409. southeast$3,
  27410. northwest$3,
  27411. southwest$3
  27412. ];
  27413. },
  27414. onRtl: function () {
  27415. return [
  27416. south$1,
  27417. southwest$1,
  27418. southeast$1,
  27419. northwest$1,
  27420. northeast$1,
  27421. north$1,
  27422. north$3,
  27423. south$3,
  27424. northwest$3,
  27425. southwest$3,
  27426. northeast$3,
  27427. southeast$3
  27428. ];
  27429. }
  27430. };
  27431. var bubbleSize$1 = 12;
  27432. var bubbleAlignments$2 = {
  27433. valignCentre: [],
  27434. alignCentre: [],
  27435. alignLeft: ['tox-pop--align-left'],
  27436. alignRight: ['tox-pop--align-right'],
  27437. right: ['tox-pop--right'],
  27438. left: ['tox-pop--left'],
  27439. bottom: ['tox-pop--bottom'],
  27440. top: ['tox-pop--top']
  27441. };
  27442. var isTouchWithinSelection = function (editor, e) {
  27443. var selection = editor.selection;
  27444. if (selection.isCollapsed() || e.touches.length < 1) {
  27445. return false;
  27446. } else {
  27447. var touch_1 = e.touches[0];
  27448. var rng = selection.getRng();
  27449. var rngRectOpt = getFirstRect$1(editor.getWin(), SimSelection.domRange(rng));
  27450. return rngRectOpt.exists(function (rngRect) {
  27451. return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
  27452. });
  27453. }
  27454. };
  27455. var getPointAnchorSpec = function (editor, e) {
  27456. return __assign({
  27457. bubble: nu$8(0, bubbleSize$1, bubbleAlignments$2),
  27458. layouts: layouts,
  27459. overrides: {
  27460. maxWidthFunction: expandable$1(),
  27461. maxHeightFunction: expandable()
  27462. }
  27463. }, getPointAnchor(editor, e));
  27464. };
  27465. var setupiOSOverrides = function (editor) {
  27466. var originalSelection = editor.selection.getRng();
  27467. var selectionReset = function () {
  27468. global$2.setEditorTimeout(editor, function () {
  27469. editor.selection.setRng(originalSelection);
  27470. }, 10);
  27471. unbindEventListeners();
  27472. };
  27473. editor.once('touchend', selectionReset);
  27474. var preventMousedown = function (e) {
  27475. e.preventDefault();
  27476. e.stopImmediatePropagation();
  27477. };
  27478. editor.on('mousedown', preventMousedown, true);
  27479. var clearSelectionReset = function () {
  27480. return unbindEventListeners();
  27481. };
  27482. editor.once('longpresscancel', clearSelectionReset);
  27483. var unbindEventListeners = function () {
  27484. editor.off('touchend', selectionReset);
  27485. editor.off('longpresscancel', clearSelectionReset);
  27486. editor.off('mousedown', preventMousedown);
  27487. };
  27488. };
  27489. var show = function (editor, e, items, backstage, contextmenu, useNodeAnchor, highlightImmediately) {
  27490. var anchorSpec = useNodeAnchor ? getNodeAnchor$1(editor) : getPointAnchorSpec(editor, e);
  27491. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  27492. e.preventDefault();
  27493. InlineView.showMenuWithinBounds(contextmenu, anchorSpec, {
  27494. menu: {
  27495. markers: markers$1('normal'),
  27496. highlightImmediately: highlightImmediately
  27497. },
  27498. data: menuData,
  27499. type: 'horizontal'
  27500. }, function () {
  27501. return Optional.some(getContextToolbarBounds(editor, backstage.shared));
  27502. });
  27503. editor.fire(hideContextToolbarEvent);
  27504. });
  27505. };
  27506. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, useNodeAnchor) {
  27507. var detection = detect$3();
  27508. var isiOS = detection.os.isiOS();
  27509. var isOSX = detection.os.isOSX();
  27510. var isAndroid = detection.os.isAndroid();
  27511. var isTouch = detection.deviceType.isTouch();
  27512. var shouldHighlightImmediately = function () {
  27513. return !(isAndroid || isiOS || isOSX && isTouch);
  27514. };
  27515. var open = function () {
  27516. var items = buildMenu();
  27517. show(editor, e, items, backstage, contextmenu, useNodeAnchor, shouldHighlightImmediately());
  27518. };
  27519. if ((isOSX || isiOS) && !useNodeAnchor) {
  27520. var openiOS_1 = function () {
  27521. setupiOSOverrides(editor);
  27522. open();
  27523. };
  27524. if (isTouchWithinSelection(editor, e)) {
  27525. openiOS_1();
  27526. } else {
  27527. editor.once('selectionchange', openiOS_1);
  27528. editor.once('touchend', function () {
  27529. return editor.off('selectionchange', openiOS_1);
  27530. });
  27531. }
  27532. } else {
  27533. if (isAndroid && !useNodeAnchor) {
  27534. editor.selection.setCursorLocation(e.target, 0);
  27535. }
  27536. open();
  27537. }
  27538. };
  27539. var patchPipeConfig = function (config) {
  27540. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  27541. };
  27542. var shouldNeverUseNative = function (editor) {
  27543. return editor.getParam('contextmenu_never_use_native', false, 'boolean');
  27544. };
  27545. var getMenuItems = function (editor, name, defaultItems) {
  27546. var contextMenus = editor.ui.registry.getAll().contextMenus;
  27547. return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () {
  27548. return filter(patchPipeConfig(defaultItems), function (item) {
  27549. return has(contextMenus, item);
  27550. });
  27551. });
  27552. };
  27553. var isContextMenuDisabled = function (editor) {
  27554. return editor.getParam('contextmenu') === false;
  27555. };
  27556. var getContextMenu = function (editor) {
  27557. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  27558. };
  27559. var getAvoidOverlapSelector = function (editor) {
  27560. return editor.getParam('contextmenu_avoid_overlap', '', 'string');
  27561. };
  27562. var isSeparator$1 = function (item) {
  27563. return isString(item) ? item === '|' : item.type === 'separator';
  27564. };
  27565. var separator$3 = { type: 'separator' };
  27566. var makeContextItem = function (item) {
  27567. if (isString(item)) {
  27568. return item;
  27569. } else {
  27570. switch (item.type) {
  27571. case 'separator':
  27572. return separator$3;
  27573. case 'submenu':
  27574. return {
  27575. type: 'nestedmenuitem',
  27576. text: item.text,
  27577. icon: item.icon,
  27578. getSubmenuItems: function () {
  27579. var items = item.getSubmenuItems();
  27580. if (isString(items)) {
  27581. return items;
  27582. } else {
  27583. return map(items, makeContextItem);
  27584. }
  27585. }
  27586. };
  27587. default:
  27588. return {
  27589. type: 'menuitem',
  27590. text: item.text,
  27591. icon: item.icon,
  27592. onAction: noarg(item.onAction)
  27593. };
  27594. }
  27595. }
  27596. };
  27597. var addContextMenuGroup = function (xs, groupItems) {
  27598. if (groupItems.length === 0) {
  27599. return xs;
  27600. }
  27601. var lastMenuItem = last(xs).filter(function (item) {
  27602. return !isSeparator$1(item);
  27603. });
  27604. var before = lastMenuItem.fold(function () {
  27605. return [];
  27606. }, function (_) {
  27607. return [separator$3];
  27608. });
  27609. return xs.concat(before).concat(groupItems).concat([separator$3]);
  27610. };
  27611. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  27612. var sections = foldl(menuConfig, function (acc, name) {
  27613. if (has(contextMenus, name)) {
  27614. var items = contextMenus[name].update(selectedElement);
  27615. if (isString(items)) {
  27616. return addContextMenuGroup(acc, items.split(' '));
  27617. } else if (items.length > 0) {
  27618. var allItems = map(items, makeContextItem);
  27619. return addContextMenuGroup(acc, allItems);
  27620. } else {
  27621. return acc;
  27622. }
  27623. } else {
  27624. return acc.concat([name]);
  27625. }
  27626. }, []);
  27627. if (sections.length > 0 && isSeparator$1(sections[sections.length - 1])) {
  27628. sections.pop();
  27629. }
  27630. return sections;
  27631. };
  27632. var isNativeOverrideKeyEvent = function (editor, e) {
  27633. return e.ctrlKey && !shouldNeverUseNative(editor);
  27634. };
  27635. var isTriggeredByKeyboard = function (editor, e) {
  27636. return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  27637. };
  27638. var getSelectedElement = function (editor, e) {
  27639. return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
  27640. };
  27641. var shouldUseNodeAnchor = function (editor, e) {
  27642. var selector = getAvoidOverlapSelector(editor);
  27643. if (isTriggeredByKeyboard(editor, e)) {
  27644. return true;
  27645. } else if (selector) {
  27646. var target = getSelectedElement(editor, e);
  27647. return closest$4(SugarElement.fromDom(target), selector);
  27648. } else {
  27649. return false;
  27650. }
  27651. };
  27652. var setup$9 = function (editor, lazySink, backstage) {
  27653. var detection = detect$3();
  27654. var isTouch = detection.deviceType.isTouch;
  27655. var contextmenu = build$1(InlineView.sketch({
  27656. dom: { tag: 'div' },
  27657. lazySink: lazySink,
  27658. onEscape: function () {
  27659. return editor.focus();
  27660. },
  27661. onShow: function () {
  27662. return backstage.setContextMenuState(true);
  27663. },
  27664. onHide: function () {
  27665. return backstage.setContextMenuState(false);
  27666. },
  27667. fireDismissalEventInstead: {},
  27668. inlineBehaviours: derive$1([config('dismissContextMenu', [run(dismissRequested(), function (comp, _se) {
  27669. Sandboxing.close(comp);
  27670. editor.focus();
  27671. })])])
  27672. }));
  27673. var hideContextMenu = function (_e) {
  27674. return InlineView.hide(contextmenu);
  27675. };
  27676. var showContextMenu = function (e) {
  27677. if (shouldNeverUseNative(editor)) {
  27678. e.preventDefault();
  27679. }
  27680. if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  27681. return;
  27682. }
  27683. var useNodeAnchor = shouldUseNodeAnchor(editor, e);
  27684. var buildMenu = function () {
  27685. var selectedElement = getSelectedElement(editor, e);
  27686. var registry = editor.ui.registry.getAll();
  27687. var menuConfig = getContextMenu(editor);
  27688. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  27689. };
  27690. var initAndShow$2 = isTouch() ? initAndShow$1 : initAndShow;
  27691. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, useNodeAnchor);
  27692. };
  27693. editor.on('init', function () {
  27694. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  27695. editor.on(hideEvents, hideContextMenu);
  27696. editor.on('longpress contextmenu', showContextMenu);
  27697. });
  27698. };
  27699. var adt$c = Adt.generate([
  27700. {
  27701. offset: [
  27702. 'x',
  27703. 'y'
  27704. ]
  27705. },
  27706. {
  27707. absolute: [
  27708. 'x',
  27709. 'y'
  27710. ]
  27711. },
  27712. {
  27713. fixed: [
  27714. 'x',
  27715. 'y'
  27716. ]
  27717. }
  27718. ]);
  27719. var subtract = function (change) {
  27720. return function (point) {
  27721. return point.translate(-change.left, -change.top);
  27722. };
  27723. };
  27724. var add$4 = function (change) {
  27725. return function (point) {
  27726. return point.translate(change.left, change.top);
  27727. };
  27728. };
  27729. var transform$1 = function (changes) {
  27730. return function (x, y) {
  27731. return foldl(changes, function (rest, f) {
  27732. return f(rest);
  27733. }, SugarPosition(x, y));
  27734. };
  27735. };
  27736. var asFixed = function (coord, scroll, origin) {
  27737. return coord.fold(transform$1([
  27738. add$4(origin),
  27739. subtract(scroll)
  27740. ]), transform$1([subtract(scroll)]), transform$1([]));
  27741. };
  27742. var asAbsolute = function (coord, scroll, origin) {
  27743. return coord.fold(transform$1([add$4(origin)]), transform$1([]), transform$1([add$4(scroll)]));
  27744. };
  27745. var asOffset = function (coord, scroll, origin) {
  27746. return coord.fold(transform$1([]), transform$1([subtract(origin)]), transform$1([
  27747. add$4(scroll),
  27748. subtract(origin)
  27749. ]));
  27750. };
  27751. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  27752. var a1 = asAbsolute(coord1, scroll, origin);
  27753. var a2 = asAbsolute(coord2, scroll, origin);
  27754. return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
  27755. };
  27756. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  27757. var a1 = asAbsolute(coord1, scroll, origin);
  27758. var a2 = asAbsolute(coord2, scroll, origin);
  27759. var left = Math.abs(a1.left - a2.left);
  27760. var top = Math.abs(a1.top - a2.top);
  27761. return SugarPosition(left, top);
  27762. };
  27763. var toStyles = function (coord, scroll, origin) {
  27764. var stylesOpt = coord.fold(function (x, y) {
  27765. return {
  27766. position: Optional.some('absolute'),
  27767. left: Optional.some(x + 'px'),
  27768. top: Optional.some(y + 'px')
  27769. };
  27770. }, function (x, y) {
  27771. return {
  27772. position: Optional.some('absolute'),
  27773. left: Optional.some(x - origin.left + 'px'),
  27774. top: Optional.some(y - origin.top + 'px')
  27775. };
  27776. }, function (x, y) {
  27777. return {
  27778. position: Optional.some('fixed'),
  27779. left: Optional.some(x + 'px'),
  27780. top: Optional.some(y + 'px')
  27781. };
  27782. });
  27783. return __assign({
  27784. right: Optional.none(),
  27785. bottom: Optional.none()
  27786. }, stylesOpt);
  27787. };
  27788. var translate$2 = function (coord, deltaX, deltaY) {
  27789. return coord.fold(function (x, y) {
  27790. return offset(x + deltaX, y + deltaY);
  27791. }, function (x, y) {
  27792. return absolute$3(x + deltaX, y + deltaY);
  27793. }, function (x, y) {
  27794. return fixed$1(x + deltaX, y + deltaY);
  27795. });
  27796. };
  27797. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  27798. var absorbOne = function (stencil, nu) {
  27799. return function (optX, optY) {
  27800. var original = stencil(originalCoord, scroll, origin);
  27801. return nu(optX.getOr(original.left), optY.getOr(original.top));
  27802. };
  27803. };
  27804. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute$3), absorbOne(asFixed, fixed$1));
  27805. };
  27806. var offset = adt$c.offset;
  27807. var absolute$3 = adt$c.absolute;
  27808. var fixed$1 = adt$c.fixed;
  27809. var parseAttrToInt = function (element, name) {
  27810. var value = get$2(element, name);
  27811. return isUndefined(value) ? NaN : parseInt(value, 10);
  27812. };
  27813. var get$e = function (component, snapsInfo) {
  27814. var element = component.element;
  27815. var x = parseAttrToInt(element, snapsInfo.leftAttr);
  27816. var y = parseAttrToInt(element, snapsInfo.topAttr);
  27817. return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
  27818. };
  27819. var set$8 = function (component, snapsInfo, pt) {
  27820. var element = component.element;
  27821. set$1(element, snapsInfo.leftAttr, pt.left + 'px');
  27822. set$1(element, snapsInfo.topAttr, pt.top + 'px');
  27823. };
  27824. var clear = function (component, snapsInfo) {
  27825. var element = component.element;
  27826. remove$1(element, snapsInfo.leftAttr);
  27827. remove$1(element, snapsInfo.topAttr);
  27828. };
  27829. var getCoords = function (component, snapInfo, coord, delta) {
  27830. return get$e(component, snapInfo).fold(function () {
  27831. return coord;
  27832. }, function (fixed) {
  27833. return fixed$1(fixed.left + delta.left, fixed.top + delta.top);
  27834. });
  27835. };
  27836. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  27837. var newCoord = getCoords(component, snapInfo, coord, delta);
  27838. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  27839. var fixedCoord = asFixed(newCoord, scroll, origin);
  27840. set$8(component, snapInfo, fixedCoord);
  27841. return snap.fold(function () {
  27842. return {
  27843. coord: fixed$1(fixedCoord.left, fixedCoord.top),
  27844. extra: Optional.none()
  27845. };
  27846. }, function (spanned) {
  27847. return {
  27848. coord: spanned.output,
  27849. extra: spanned.extra
  27850. };
  27851. });
  27852. };
  27853. var stopDrag = function (component, snapInfo) {
  27854. clear(component, snapInfo);
  27855. };
  27856. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  27857. return findMap(snaps, function (snap) {
  27858. var sensor = snap.sensor;
  27859. var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  27860. return inRange ? Optional.some({
  27861. output: absorb(snap.output, newCoord, scroll, origin),
  27862. extra: snap.extra
  27863. }) : Optional.none();
  27864. });
  27865. };
  27866. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27867. var snaps = snapInfo.getSnapPoints(component);
  27868. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  27869. return matchSnap.orThunk(function () {
  27870. var bestSnap = foldl(snaps, function (acc, snap) {
  27871. var sensor = snap.sensor;
  27872. var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  27873. return acc.deltas.fold(function () {
  27874. return {
  27875. deltas: Optional.some(deltas),
  27876. snap: Optional.some(snap)
  27877. };
  27878. }, function (bestDeltas) {
  27879. var currAvg = (deltas.left + deltas.top) / 2;
  27880. var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
  27881. if (currAvg <= bestAvg) {
  27882. return {
  27883. deltas: Optional.some(deltas),
  27884. snap: Optional.some(snap)
  27885. };
  27886. } else {
  27887. return acc;
  27888. }
  27889. });
  27890. }, {
  27891. deltas: Optional.none(),
  27892. snap: Optional.none()
  27893. });
  27894. return bestSnap.snap.map(function (snap) {
  27895. return {
  27896. output: absorb(snap.output, newCoord, scroll, origin),
  27897. extra: snap.extra
  27898. };
  27899. });
  27900. });
  27901. };
  27902. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27903. var snaps = snapInfo.getSnapPoints(component);
  27904. return findMatchingSnap(snaps, newCoord, scroll, origin);
  27905. };
  27906. var snapTo = function (snap, scroll, origin) {
  27907. return {
  27908. coord: absorb(snap.output, snap.output, scroll, origin),
  27909. extra: snap.extra
  27910. };
  27911. };
  27912. var snapTo$1 = function (component, dragConfig, _state, snap) {
  27913. var target = dragConfig.getTarget(component.element);
  27914. if (dragConfig.repositionTarget) {
  27915. var doc = owner(component.element);
  27916. var scroll_1 = get$8(doc);
  27917. var origin_1 = getOrigin(target);
  27918. var snapPin = snapTo(snap, scroll_1, origin_1);
  27919. var styles = toStyles(snapPin.coord, scroll_1, origin_1);
  27920. setOptions(target, styles);
  27921. }
  27922. };
  27923. var DraggingApis = /*#__PURE__*/Object.freeze({
  27924. __proto__: null,
  27925. snapTo: snapTo$1
  27926. });
  27927. var initialAttribute = 'data-initial-z-index';
  27928. var resetZIndex = function (blocker) {
  27929. parent(blocker.element).filter(isElement).each(function (root) {
  27930. getOpt(root, initialAttribute).fold(function () {
  27931. return remove$6(root, 'z-index');
  27932. }, function (zIndex) {
  27933. return set$2(root, 'z-index', zIndex);
  27934. });
  27935. remove$1(root, initialAttribute);
  27936. });
  27937. };
  27938. var changeZIndex = function (blocker) {
  27939. parent(blocker.element).filter(isElement).each(function (root) {
  27940. getRaw(root, 'z-index').each(function (zindex) {
  27941. set$1(root, initialAttribute, zindex);
  27942. });
  27943. set$2(root, 'z-index', get$4(blocker.element, 'z-index'));
  27944. });
  27945. };
  27946. var instigate = function (anyComponent, blocker) {
  27947. anyComponent.getSystem().addToGui(blocker);
  27948. changeZIndex(blocker);
  27949. };
  27950. var discard = function (blocker) {
  27951. resetZIndex(blocker);
  27952. blocker.getSystem().removeFromGui(blocker);
  27953. };
  27954. var createComponent = function (component, blockerClass, blockerEvents) {
  27955. return component.getSystem().build(Container.sketch({
  27956. dom: {
  27957. styles: {
  27958. 'left': '0px',
  27959. 'top': '0px',
  27960. 'width': '100%',
  27961. 'height': '100%',
  27962. 'position': 'fixed',
  27963. 'z-index': '1000000000000000'
  27964. },
  27965. classes: [blockerClass]
  27966. },
  27967. events: blockerEvents
  27968. }));
  27969. };
  27970. var SnapSchema = optionObjOf('snaps', [
  27971. strict$1('getSnapPoints'),
  27972. onHandler('onSensor'),
  27973. strict$1('leftAttr'),
  27974. strict$1('topAttr'),
  27975. defaulted$1('lazyViewport', win),
  27976. defaulted$1('mustSnap', false)
  27977. ]);
  27978. var schema$t = [
  27979. defaulted$1('useFixed', never),
  27980. strict$1('blockerClass'),
  27981. defaulted$1('getTarget', identity),
  27982. defaulted$1('onDrag', noop),
  27983. defaulted$1('repositionTarget', true),
  27984. defaulted$1('onDrop', noop),
  27985. defaultedFunction('getBounds', win),
  27986. SnapSchema
  27987. ];
  27988. var getCurrentCoord = function (target) {
  27989. return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  27990. var nu = position === 'fixed' ? fixed$1 : offset;
  27991. return nu(parseInt(left, 10), parseInt(top, 10));
  27992. }).getOrThunk(function () {
  27993. var location = absolute(target);
  27994. return absolute$3(location.left, location.top);
  27995. });
  27996. };
  27997. var clampCoords = function (component, coords, scroll, origin, startData) {
  27998. var bounds = startData.bounds;
  27999. var absoluteCoord = asAbsolute(coords, scroll, origin);
  28000. var newX = clamp(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
  28001. var newY = clamp(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
  28002. var newCoords = absolute$3(newX, newY);
  28003. return coords.fold(function () {
  28004. var offset$1 = asOffset(newCoords, scroll, origin);
  28005. return offset(offset$1.left, offset$1.top);
  28006. }, function () {
  28007. return newCoords;
  28008. }, function () {
  28009. var fixed = asFixed(newCoords, scroll, origin);
  28010. return fixed$1(fixed.left, fixed.top);
  28011. });
  28012. };
  28013. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  28014. var newCoord = optSnaps.fold(function () {
  28015. var translated = translate$2(currentCoord, delta.left, delta.top);
  28016. var fixedCoord = asFixed(translated, scroll, origin);
  28017. return fixed$1(fixedCoord.left, fixedCoord.top);
  28018. }, function (snapInfo) {
  28019. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  28020. snapping.extra.each(function (extra) {
  28021. snapInfo.onSensor(component, extra);
  28022. });
  28023. return snapping.coord;
  28024. });
  28025. return clampCoords(component, newCoord, scroll, origin, startData);
  28026. };
  28027. var dragBy = function (component, dragConfig, startData, delta) {
  28028. var target = dragConfig.getTarget(component.element);
  28029. if (dragConfig.repositionTarget) {
  28030. var doc = owner(component.element);
  28031. var scroll_1 = get$8(doc);
  28032. var origin_1 = getOrigin(target);
  28033. var currentCoord = getCurrentCoord(target);
  28034. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
  28035. var styles = toStyles(newCoord, scroll_1, origin_1);
  28036. setOptions(target, styles);
  28037. }
  28038. dragConfig.onDrag(component, target, delta);
  28039. };
  28040. var calcStartData = function (dragConfig, comp) {
  28041. return {
  28042. bounds: dragConfig.getBounds(),
  28043. height: getOuter$1(comp.element),
  28044. width: getOuter$2(comp.element)
  28045. };
  28046. };
  28047. var move$1 = function (component, dragConfig, dragState, dragMode, event) {
  28048. var delta = dragState.update(dragMode, event);
  28049. var dragStartData = dragState.getStartData().getOrThunk(function () {
  28050. return calcStartData(dragConfig, component);
  28051. });
  28052. delta.each(function (dlt) {
  28053. dragBy(component, dragConfig, dragStartData, dlt);
  28054. });
  28055. };
  28056. var stop = function (component, blocker, dragConfig, dragState) {
  28057. blocker.each(discard);
  28058. dragConfig.snaps.each(function (snapInfo) {
  28059. stopDrag(component, snapInfo);
  28060. });
  28061. var target = dragConfig.getTarget(component.element);
  28062. dragState.reset();
  28063. dragConfig.onDrop(component, target);
  28064. };
  28065. var handlers = function (events) {
  28066. return function (dragConfig, dragState) {
  28067. var updateStartState = function (comp) {
  28068. dragState.setStartData(calcStartData(dragConfig, comp));
  28069. };
  28070. return derive(__spreadArrays([run(windowScroll(), function (comp) {
  28071. dragState.getStartData().each(function () {
  28072. return updateStartState(comp);
  28073. });
  28074. })], events(dragConfig, dragState, updateStartState)));
  28075. };
  28076. };
  28077. var init$c = function (dragApi) {
  28078. return derive([
  28079. run(mousedown(), dragApi.forceDrop),
  28080. run(mouseup(), dragApi.drop),
  28081. run(mousemove(), function (comp, simulatedEvent) {
  28082. dragApi.move(simulatedEvent.event);
  28083. }),
  28084. run(mouseout(), dragApi.delayDrop)
  28085. ]);
  28086. };
  28087. var getData$1 = function (event) {
  28088. return Optional.from(SugarPosition(event.x, event.y));
  28089. };
  28090. var getDelta$1 = function (old, nu) {
  28091. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28092. };
  28093. var MouseData = /*#__PURE__*/Object.freeze({
  28094. __proto__: null,
  28095. getData: getData$1,
  28096. getDelta: getDelta$1
  28097. });
  28098. var events$g = function (dragConfig, dragState, updateStartState) {
  28099. return [run(mousedown(), function (component, simulatedEvent) {
  28100. var raw = simulatedEvent.event.raw;
  28101. if (raw.button !== 0) {
  28102. return;
  28103. }
  28104. simulatedEvent.stop();
  28105. var stop$1 = function () {
  28106. return stop(component, Optional.some(blocker), dragConfig, dragState);
  28107. };
  28108. var delayDrop = DelayedFunction(stop$1, 200);
  28109. var dragApi = {
  28110. drop: stop$1,
  28111. delayDrop: delayDrop.schedule,
  28112. forceDrop: stop$1,
  28113. move: function (event) {
  28114. delayDrop.cancel();
  28115. move$1(component, dragConfig, dragState, MouseData, event);
  28116. }
  28117. };
  28118. var blocker = createComponent(component, dragConfig.blockerClass, init$c(dragApi));
  28119. var start = function () {
  28120. updateStartState(component);
  28121. instigate(component, blocker);
  28122. };
  28123. start();
  28124. })];
  28125. };
  28126. var schema$u = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$g) })]);
  28127. var init$d = function (dragApi) {
  28128. return derive([
  28129. run(touchstart(), dragApi.forceDrop),
  28130. run(touchend(), dragApi.drop),
  28131. run(touchcancel(), dragApi.drop),
  28132. run(touchmove(), function (comp, simulatedEvent) {
  28133. dragApi.move(simulatedEvent.event);
  28134. })
  28135. ]);
  28136. };
  28137. var getDataFrom = function (touches) {
  28138. var touch = touches[0];
  28139. return Optional.some(SugarPosition(touch.clientX, touch.clientY));
  28140. };
  28141. var getData$2 = function (event) {
  28142. var raw = event.raw;
  28143. var touches = raw.touches;
  28144. return touches.length === 1 ? getDataFrom(touches) : Optional.none();
  28145. };
  28146. var getDelta$2 = function (old, nu) {
  28147. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28148. };
  28149. var TouchData = /*#__PURE__*/Object.freeze({
  28150. __proto__: null,
  28151. getData: getData$2,
  28152. getDelta: getDelta$2
  28153. });
  28154. var events$h = function (dragConfig, dragState, updateStartState) {
  28155. var blockerCell = Cell(Optional.none());
  28156. return [
  28157. run(touchstart(), function (component, simulatedEvent) {
  28158. simulatedEvent.stop();
  28159. var stop$1 = function () {
  28160. stop(component, blockerCell.get(), dragConfig, dragState);
  28161. blockerCell.set(Optional.none());
  28162. };
  28163. var dragApi = {
  28164. drop: stop$1,
  28165. delayDrop: function () {
  28166. },
  28167. forceDrop: stop$1,
  28168. move: function (event) {
  28169. move$1(component, dragConfig, dragState, TouchData, event);
  28170. }
  28171. };
  28172. var blocker = createComponent(component, dragConfig.blockerClass, init$d(dragApi));
  28173. blockerCell.set(Optional.some(blocker));
  28174. var start = function () {
  28175. updateStartState(component);
  28176. instigate(component, blocker);
  28177. };
  28178. start();
  28179. }),
  28180. run(touchmove(), function (component, simulatedEvent) {
  28181. simulatedEvent.stop();
  28182. move$1(component, dragConfig, dragState, TouchData, simulatedEvent.event);
  28183. }),
  28184. run(touchend(), function (component, simulatedEvent) {
  28185. simulatedEvent.stop();
  28186. stop(component, blockerCell.get(), dragConfig, dragState);
  28187. blockerCell.set(Optional.none());
  28188. }),
  28189. run(touchcancel(), function (component) {
  28190. stop(component, blockerCell.get(), dragConfig, dragState);
  28191. blockerCell.set(Optional.none());
  28192. })
  28193. ];
  28194. };
  28195. var schema$v = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$h) })]);
  28196. var events$i = function (dragConfig, dragState, updateStartState) {
  28197. return __spreadArrays(events$g(dragConfig, dragState, updateStartState), events$h(dragConfig, dragState, updateStartState));
  28198. };
  28199. var schema$w = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$i) })]);
  28200. var mouse = schema$u;
  28201. var touch = schema$v;
  28202. var mouseOrTouch = schema$w;
  28203. var DraggingBranches = /*#__PURE__*/Object.freeze({
  28204. __proto__: null,
  28205. mouse: mouse,
  28206. touch: touch,
  28207. mouseOrTouch: mouseOrTouch
  28208. });
  28209. var init$e = function () {
  28210. var previous = Optional.none();
  28211. var startData = Optional.none();
  28212. var reset = function () {
  28213. previous = Optional.none();
  28214. startData = Optional.none();
  28215. };
  28216. var calculateDelta = function (mode, nu) {
  28217. var result = previous.map(function (old) {
  28218. return mode.getDelta(old, nu);
  28219. });
  28220. previous = Optional.some(nu);
  28221. return result;
  28222. };
  28223. var update = function (mode, dragEvent) {
  28224. return mode.getData(dragEvent).bind(function (nuData) {
  28225. return calculateDelta(mode, nuData);
  28226. });
  28227. };
  28228. var setStartData = function (data) {
  28229. startData = Optional.some(data);
  28230. };
  28231. var getStartData = function () {
  28232. return startData;
  28233. };
  28234. var readState = constant({});
  28235. return nu$5({
  28236. readState: readState,
  28237. reset: reset,
  28238. update: update,
  28239. getStartData: getStartData,
  28240. setStartData: setStartData
  28241. });
  28242. };
  28243. var DragState = /*#__PURE__*/Object.freeze({
  28244. __proto__: null,
  28245. init: init$e
  28246. });
  28247. var Dragging = createModes$1({
  28248. branchKey: 'mode',
  28249. branches: DraggingBranches,
  28250. name: 'dragging',
  28251. active: {
  28252. events: function (dragConfig, dragState) {
  28253. var dragger = dragConfig.dragger;
  28254. return dragger.handlers(dragConfig, dragState);
  28255. }
  28256. },
  28257. extra: {
  28258. snap: function (sConfig) {
  28259. return {
  28260. sensor: sConfig.sensor,
  28261. range: sConfig.range,
  28262. output: sConfig.output,
  28263. extra: Optional.from(sConfig.extra)
  28264. };
  28265. }
  28266. },
  28267. state: DragState,
  28268. apis: DraggingApis
  28269. });
  28270. var snapWidth = 40;
  28271. var snapOffset = snapWidth / 2;
  28272. var calcSnap = function (selectorOpt, td, x, y, width, height) {
  28273. return selectorOpt.fold(function () {
  28274. return Dragging.snap({
  28275. sensor: absolute$3(x - snapOffset, y - snapOffset),
  28276. range: SugarPosition(width, height),
  28277. output: absolute$3(Optional.some(x), Optional.some(y)),
  28278. extra: { td: td }
  28279. });
  28280. }, function (selectorHandle) {
  28281. var sensorLeft = x - snapOffset;
  28282. var sensorTop = y - snapOffset;
  28283. var sensorWidth = snapWidth;
  28284. var sensorHeight = snapWidth;
  28285. var rect = selectorHandle.element.dom.getBoundingClientRect();
  28286. return Dragging.snap({
  28287. sensor: absolute$3(sensorLeft, sensorTop),
  28288. range: SugarPosition(sensorWidth, sensorHeight),
  28289. output: absolute$3(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
  28290. extra: { td: td }
  28291. });
  28292. });
  28293. };
  28294. var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  28295. var isSameCell = function (cellOpt, td) {
  28296. return cellOpt.exists(function (currentTd) {
  28297. return eq$1(currentTd, td);
  28298. });
  28299. };
  28300. return {
  28301. getSnapPoints: getSnapPoints,
  28302. leftAttr: 'data-drag-left',
  28303. topAttr: 'data-drag-top',
  28304. onSensor: function (component, extra) {
  28305. var td = extra.td;
  28306. if (!isSameCell(cell.get(), td)) {
  28307. cell.set(Optional.some(td));
  28308. onChange(td);
  28309. }
  28310. },
  28311. mustSnap: true
  28312. };
  28313. };
  28314. var createSelector = function (snaps) {
  28315. return record(Button.sketch({
  28316. dom: {
  28317. tag: 'div',
  28318. classes: ['tox-selector']
  28319. },
  28320. buttonBehaviours: derive$1([
  28321. Dragging.config({
  28322. mode: 'mouseOrTouch',
  28323. blockerClass: 'blocker',
  28324. snaps: snaps
  28325. }),
  28326. Unselecting.config({})
  28327. ]),
  28328. eventOrder: {
  28329. mousedown: [
  28330. 'dragging',
  28331. 'alloy.base.behaviour'
  28332. ],
  28333. touchstart: [
  28334. 'dragging',
  28335. 'alloy.base.behaviour'
  28336. ]
  28337. }
  28338. }));
  28339. };
  28340. var setup$a = function (editor, sink) {
  28341. var tlTds = Cell([]);
  28342. var brTds = Cell([]);
  28343. var isVisible = Cell(false);
  28344. var startCell = Cell(Optional.none());
  28345. var finishCell = Cell(Optional.none());
  28346. var getTopLeftSnap = function (td) {
  28347. var box = absolute$1(td);
  28348. return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  28349. };
  28350. var getTopLeftSnaps = function () {
  28351. return map(tlTds.get(), function (td) {
  28352. return getTopLeftSnap(td);
  28353. });
  28354. };
  28355. var getBottomRightSnap = function (td) {
  28356. var box = absolute$1(td);
  28357. return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  28358. };
  28359. var getBottomRightSnaps = function () {
  28360. return map(brTds.get(), function (td) {
  28361. return getBottomRightSnap(td);
  28362. });
  28363. };
  28364. var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  28365. finishCell.get().each(function (finish) {
  28366. editor.fire('TableSelectorChange', {
  28367. start: start,
  28368. finish: finish
  28369. });
  28370. });
  28371. });
  28372. var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  28373. startCell.get().each(function (start) {
  28374. editor.fire('TableSelectorChange', {
  28375. start: start,
  28376. finish: finish
  28377. });
  28378. });
  28379. });
  28380. var memTopLeft = createSelector(topLeftSnaps);
  28381. var memBottomRight = createSelector(bottomRightSnaps);
  28382. var topLeft = build$1(memTopLeft.asSpec());
  28383. var bottomRight = build$1(memBottomRight.asSpec());
  28384. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  28385. var cellRect = cell.dom.getBoundingClientRect();
  28386. remove$6(selector.element, 'display');
  28387. var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
  28388. var aboveViewport = isAbove(cellRect);
  28389. var belowViewport = isBelow(cellRect, viewportHeight);
  28390. if (aboveViewport || belowViewport) {
  28391. set$2(selector.element, 'display', 'none');
  28392. }
  28393. };
  28394. var snapTo = function (selector, cell, getSnapConfig, pos) {
  28395. var snap = getSnapConfig(cell);
  28396. Dragging.snapTo(selector, snap);
  28397. var isAbove = function (rect) {
  28398. return rect[pos] < 0;
  28399. };
  28400. var isBelow = function (rect, viewportHeight) {
  28401. return rect[pos] > viewportHeight;
  28402. };
  28403. showOrHideHandle(selector, cell, isAbove, isBelow);
  28404. };
  28405. var snapTopLeft = function (cell) {
  28406. return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  28407. };
  28408. var snapLastTopLeft = function () {
  28409. return startCell.get().each(snapTopLeft);
  28410. };
  28411. var snapBottomRight = function (cell) {
  28412. return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  28413. };
  28414. var snapLastBottomRight = function () {
  28415. return finishCell.get().each(snapBottomRight);
  28416. };
  28417. if (detect$3().deviceType.isTouch()) {
  28418. editor.on('TableSelectionChange', function (e) {
  28419. if (!isVisible.get()) {
  28420. attach$1(sink, topLeft);
  28421. attach$1(sink, bottomRight);
  28422. isVisible.set(true);
  28423. }
  28424. startCell.set(Optional.some(e.start));
  28425. finishCell.set(Optional.some(e.finish));
  28426. e.otherCells.each(function (otherCells) {
  28427. tlTds.set(otherCells.upOrLeftCells);
  28428. brTds.set(otherCells.downOrRightCells);
  28429. snapTopLeft(e.start);
  28430. snapBottomRight(e.finish);
  28431. });
  28432. });
  28433. editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  28434. snapLastTopLeft();
  28435. snapLastBottomRight();
  28436. });
  28437. editor.on('TableSelectionClear', function () {
  28438. if (isVisible.get()) {
  28439. detach(topLeft);
  28440. detach(bottomRight);
  28441. isVisible.set(false);
  28442. }
  28443. startCell.set(Optional.none());
  28444. finishCell.set(Optional.none());
  28445. });
  28446. }
  28447. };
  28448. var ResizeTypes;
  28449. (function (ResizeTypes) {
  28450. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  28451. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  28452. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  28453. }(ResizeTypes || (ResizeTypes = {})));
  28454. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  28455. var dimensions = {};
  28456. dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
  28457. if (resizeType === ResizeTypes.Both) {
  28458. dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
  28459. }
  28460. return dimensions;
  28461. };
  28462. var resize$3 = function (editor, deltas, resizeType) {
  28463. var container = SugarElement.fromDom(editor.getContainer());
  28464. var dimensions = getDimensions(editor, deltas, resizeType, get$6(container), get$7(container));
  28465. each$1(dimensions, function (val, dim) {
  28466. return set$2(container, dim, numToPx(val));
  28467. });
  28468. fireResizeEditor(editor);
  28469. };
  28470. var isHidden$1 = function (elm) {
  28471. if (elm.nodeType === 1) {
  28472. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  28473. return true;
  28474. }
  28475. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  28476. return true;
  28477. }
  28478. }
  28479. return false;
  28480. };
  28481. var renderElementPath = function (editor, settings, providersBackstage) {
  28482. if (!settings.delimiter) {
  28483. settings.delimiter = '\xBB';
  28484. }
  28485. var getDataPath = function (data) {
  28486. var parts = data || [];
  28487. var newPathElements = map(parts, function (part, index) {
  28488. return Button.sketch({
  28489. dom: {
  28490. tag: 'div',
  28491. classes: ['tox-statusbar__path-item'],
  28492. attributes: {
  28493. 'role': 'button',
  28494. 'data-index': index,
  28495. 'tab-index': -1,
  28496. 'aria-level': index + 1
  28497. },
  28498. innerHtml: part.name
  28499. },
  28500. action: function (_btn) {
  28501. editor.focus();
  28502. editor.selection.select(part.element);
  28503. editor.nodeChanged();
  28504. },
  28505. buttonBehaviours: derive$1([
  28506. DisablingConfigs.button(providersBackstage.isReadOnly),
  28507. receivingConfig()
  28508. ])
  28509. });
  28510. });
  28511. var divider = {
  28512. dom: {
  28513. tag: 'div',
  28514. classes: ['tox-statusbar__path-divider'],
  28515. attributes: { 'aria-hidden': true },
  28516. innerHtml: ' ' + settings.delimiter + ' '
  28517. }
  28518. };
  28519. return foldl(newPathElements.slice(1), function (acc, element) {
  28520. var newAcc = acc;
  28521. newAcc.push(divider);
  28522. newAcc.push(element);
  28523. return newAcc;
  28524. }, [newPathElements[0]]);
  28525. };
  28526. var updatePath = function (parents) {
  28527. var newPath = [];
  28528. var i = parents.length;
  28529. while (i-- > 0) {
  28530. var parent_1 = parents[i];
  28531. if (parent_1.nodeType === 1 && !isHidden$1(parent_1)) {
  28532. var args = editor.fire('ResolveName', {
  28533. name: parent_1.nodeName.toLowerCase(),
  28534. target: parent_1
  28535. });
  28536. if (!args.isDefaultPrevented()) {
  28537. newPath.push({
  28538. name: args.name,
  28539. element: parent_1
  28540. });
  28541. }
  28542. if (args.isPropagationStopped()) {
  28543. break;
  28544. }
  28545. }
  28546. }
  28547. return newPath;
  28548. };
  28549. return {
  28550. dom: {
  28551. tag: 'div',
  28552. classes: ['tox-statusbar__path'],
  28553. attributes: { role: 'navigation' }
  28554. },
  28555. behaviours: derive$1([
  28556. Keying.config({
  28557. mode: 'flow',
  28558. selector: 'div[role=button]'
  28559. }),
  28560. Disabling.config({ disabled: providersBackstage.isReadOnly }),
  28561. receivingConfig(),
  28562. Tabstopping.config({}),
  28563. Replacing.config({}),
  28564. config('elementPathEvents', [runOnAttached(function (comp, _e) {
  28565. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  28566. return Keying.focusIn(comp);
  28567. });
  28568. editor.on('NodeChange', function (e) {
  28569. var newPath = updatePath(e.parents);
  28570. if (newPath.length > 0) {
  28571. Replacing.set(comp, getDataPath(newPath));
  28572. } else {
  28573. Replacing.set(comp, []);
  28574. }
  28575. });
  28576. })])
  28577. ]),
  28578. components: []
  28579. };
  28580. };
  28581. var renderWordCount = function (editor, providersBackstage) {
  28582. var _a;
  28583. var replaceCountText = function (comp, count, mode) {
  28584. return Replacing.set(comp, [text(providersBackstage.translate([
  28585. '{0} ' + mode,
  28586. count[mode]
  28587. ]))]);
  28588. };
  28589. return Button.sketch({
  28590. dom: {
  28591. tag: 'button',
  28592. classes: ['tox-statusbar__wordcount']
  28593. },
  28594. components: [],
  28595. buttonBehaviours: derive$1([
  28596. DisablingConfigs.button(providersBackstage.isReadOnly),
  28597. receivingConfig(),
  28598. Tabstopping.config({}),
  28599. Replacing.config({}),
  28600. Representing.config({
  28601. store: {
  28602. mode: 'memory',
  28603. initialValue: {
  28604. mode: 'words',
  28605. count: {
  28606. words: 0,
  28607. characters: 0
  28608. }
  28609. }
  28610. }
  28611. }),
  28612. config('wordcount-events', [
  28613. runOnExecute(function (comp) {
  28614. var currentVal = Representing.getValue(comp);
  28615. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  28616. Representing.setValue(comp, {
  28617. mode: newMode,
  28618. count: currentVal.count
  28619. });
  28620. replaceCountText(comp, currentVal.count, newMode);
  28621. }),
  28622. runOnAttached(function (comp) {
  28623. editor.on('wordCountUpdate', function (e) {
  28624. var mode = Representing.getValue(comp).mode;
  28625. Representing.setValue(comp, {
  28626. mode: mode,
  28627. count: e.wordCount
  28628. });
  28629. replaceCountText(comp, e.wordCount, mode);
  28630. });
  28631. })
  28632. ])
  28633. ]),
  28634. eventOrder: (_a = {}, _a[execute()] = [
  28635. 'disabling',
  28636. 'alloy.base.behaviour',
  28637. 'wordcount-events'
  28638. ], _a)
  28639. });
  28640. };
  28641. var renderStatusbar = function (editor, providersBackstage) {
  28642. var renderResizeHandlerIcon = function (resizeType) {
  28643. return {
  28644. dom: {
  28645. tag: 'div',
  28646. classes: ['tox-statusbar__resize-handle'],
  28647. attributes: {
  28648. 'title': providersBackstage.translate('Resize'),
  28649. 'aria-hidden': 'true'
  28650. },
  28651. innerHtml: get$d('resize-handle', providersBackstage.icons)
  28652. },
  28653. behaviours: derive$1([Dragging.config({
  28654. mode: 'mouse',
  28655. repositionTarget: false,
  28656. onDrag: function (comp, target, delta) {
  28657. resize$3(editor, delta, resizeType);
  28658. },
  28659. blockerClass: 'tox-blocker'
  28660. })])
  28661. };
  28662. };
  28663. var renderBranding = function () {
  28664. var label = global$6.translate([
  28665. 'Powered by {0}',
  28666. 'Tiny'
  28667. ]);
  28668. var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce&amp;utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + '</a>';
  28669. return {
  28670. dom: {
  28671. tag: 'span',
  28672. classes: ['tox-statusbar__branding'],
  28673. innerHtml: linkHtml
  28674. }
  28675. };
  28676. };
  28677. var getResizeType = function (editor) {
  28678. var fallback = !editor.hasPlugin('autoresize');
  28679. var resize = editor.getParam('resize', fallback);
  28680. if (resize === false) {
  28681. return ResizeTypes.None;
  28682. } else if (resize === 'both') {
  28683. return ResizeTypes.Both;
  28684. } else {
  28685. return ResizeTypes.Vertical;
  28686. }
  28687. };
  28688. var getTextComponents = function () {
  28689. var components = [];
  28690. if (editor.getParam('elementpath', true, 'boolean')) {
  28691. components.push(renderElementPath(editor, {}, providersBackstage));
  28692. }
  28693. if (editor.hasPlugin('wordcount')) {
  28694. components.push(renderWordCount(editor, providersBackstage));
  28695. }
  28696. if (editor.getParam('branding', true, 'boolean')) {
  28697. components.push(renderBranding());
  28698. }
  28699. if (components.length > 0) {
  28700. return [{
  28701. dom: {
  28702. tag: 'div',
  28703. classes: ['tox-statusbar__text-container']
  28704. },
  28705. components: components
  28706. }];
  28707. }
  28708. return [];
  28709. };
  28710. var getComponents = function () {
  28711. var components = getTextComponents();
  28712. var resizeType = getResizeType(editor);
  28713. if (resizeType !== ResizeTypes.None) {
  28714. components.push(renderResizeHandlerIcon(resizeType));
  28715. }
  28716. return components;
  28717. };
  28718. return {
  28719. dom: {
  28720. tag: 'div',
  28721. classes: ['tox-statusbar']
  28722. },
  28723. components: getComponents()
  28724. };
  28725. };
  28726. var setup$b = function (editor) {
  28727. var _a;
  28728. var isInline = editor.inline;
  28729. var mode = isInline ? Inline : Iframe;
  28730. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  28731. var lazyOuterContainer = Optional.none();
  28732. var platform = detect$3();
  28733. var isIE = platform.browser.isIE();
  28734. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  28735. var isTouch = platform.deviceType.isTouch();
  28736. var touchPlatformClass = 'tox-platform-touch';
  28737. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  28738. var isToolbarBottom = isToolbarLocationBottom(editor);
  28739. var dirAttributes = global$6.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  28740. var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
  28741. var lazyHeader = function () {
  28742. return lazyOuterContainer.bind(OuterContainer.getHeader);
  28743. };
  28744. var isHeaderDocked = function () {
  28745. return header.isDocked(lazyHeader);
  28746. };
  28747. var sink = build$1({
  28748. dom: __assign({
  28749. tag: 'div',
  28750. classes: [
  28751. 'tox',
  28752. 'tox-silver-sink',
  28753. 'tox-tinymce-aux'
  28754. ].concat(platformClasses).concat(deviceClasses)
  28755. }, dirAttributes),
  28756. behaviours: derive$1([Positioning.config({
  28757. useFixed: function () {
  28758. return isHeaderDocked();
  28759. }
  28760. })])
  28761. });
  28762. var lazySink = function () {
  28763. return Result.value(sink);
  28764. };
  28765. var memAnchorBar = record({
  28766. dom: {
  28767. tag: 'div',
  28768. classes: ['tox-anchorbar']
  28769. }
  28770. });
  28771. var lazyAnchorBar = function () {
  28772. return lazyOuterContainer.bind(function (container) {
  28773. return memAnchorBar.getOpt(container);
  28774. }).getOrDie('Could not find a anchor bar element');
  28775. };
  28776. var lazyToolbar = function () {
  28777. return lazyOuterContainer.bind(function (container) {
  28778. return OuterContainer.getToolbar(container);
  28779. }).getOrDie('Could not find more toolbar element');
  28780. };
  28781. var lazyThrobber = function () {
  28782. return lazyOuterContainer.bind(function (container) {
  28783. return OuterContainer.getThrobber(container);
  28784. }).getOrDie('Could not find throbber element');
  28785. };
  28786. var backstage = init$8(sink, editor, lazyAnchorBar);
  28787. var partMenubar = OuterContainer.parts.menubar({
  28788. dom: {
  28789. tag: 'div',
  28790. classes: ['tox-menubar']
  28791. },
  28792. backstage: backstage,
  28793. onEscape: function () {
  28794. editor.focus();
  28795. }
  28796. });
  28797. var toolbarMode = getToolbarMode(editor);
  28798. var partToolbar = OuterContainer.parts.toolbar(__assign({
  28799. dom: {
  28800. tag: 'div',
  28801. classes: ['tox-toolbar']
  28802. },
  28803. getSink: lazySink,
  28804. providers: backstage.shared.providers,
  28805. onEscape: function () {
  28806. editor.focus();
  28807. },
  28808. type: toolbarMode,
  28809. lazyToolbar: lazyToolbar,
  28810. lazyHeader: function () {
  28811. return lazyHeader().getOrDie('Could not find header element');
  28812. }
  28813. }, verticalDirAttributes));
  28814. var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
  28815. dom: {
  28816. tag: 'div',
  28817. classes: ['tox-toolbar-overlord']
  28818. },
  28819. providers: backstage.shared.providers,
  28820. onEscape: function () {
  28821. editor.focus();
  28822. },
  28823. type: toolbarMode
  28824. });
  28825. var partSocket = OuterContainer.parts.socket({
  28826. dom: {
  28827. tag: 'div',
  28828. classes: ['tox-edit-area']
  28829. }
  28830. });
  28831. var partSidebar = OuterContainer.parts.sidebar({
  28832. dom: {
  28833. tag: 'div',
  28834. classes: ['tox-sidebar']
  28835. }
  28836. });
  28837. var partThrobber = OuterContainer.parts.throbber({
  28838. dom: {
  28839. tag: 'div',
  28840. classes: ['tox-throbber']
  28841. },
  28842. backstage: backstage
  28843. });
  28844. var sb = editor.getParam('statusbar', true, 'boolean');
  28845. var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
  28846. var socketSidebarContainer = {
  28847. dom: {
  28848. tag: 'div',
  28849. classes: ['tox-sidebar-wrap']
  28850. },
  28851. components: [
  28852. partSocket,
  28853. partSidebar
  28854. ]
  28855. };
  28856. var hasMultipleToolbar = isMultipleToolbars(editor);
  28857. var hasToolbar = isToolbarEnabled(editor);
  28858. var hasMenubar = isMenubarEnabled(editor);
  28859. var getPartToolbar = function () {
  28860. if (hasMultipleToolbar) {
  28861. return [partMultipleToolbar];
  28862. } else if (hasToolbar) {
  28863. return [partToolbar];
  28864. } else {
  28865. return [];
  28866. }
  28867. };
  28868. var partHeader = OuterContainer.parts.header({
  28869. dom: __assign({
  28870. tag: 'div',
  28871. classes: ['tox-editor-header']
  28872. }, verticalDirAttributes),
  28873. components: flatten([
  28874. hasMenubar ? [partMenubar] : [],
  28875. getPartToolbar(),
  28876. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  28877. ]),
  28878. sticky: isStickyToolbar(editor),
  28879. editor: editor,
  28880. sharedBackstage: backstage.shared
  28881. });
  28882. var editorComponents = flatten([
  28883. isToolbarBottom ? [] : [partHeader],
  28884. isInline ? [] : [socketSidebarContainer],
  28885. isToolbarBottom ? [partHeader] : []
  28886. ]);
  28887. var editorContainer = {
  28888. dom: {
  28889. tag: 'div',
  28890. classes: ['tox-editor-container']
  28891. },
  28892. components: editorComponents
  28893. };
  28894. var containerComponents = flatten([
  28895. [editorContainer],
  28896. isInline ? [] : statusbar.toArray(),
  28897. [partThrobber]
  28898. ]);
  28899. var isHidden = isDistractionFree(editor);
  28900. var attributes = __assign(__assign({ role: 'application' }, global$6.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  28901. var outerContainer = build$1(OuterContainer.sketch({
  28902. dom: {
  28903. tag: 'div',
  28904. classes: [
  28905. 'tox',
  28906. 'tox-tinymce'
  28907. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
  28908. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  28909. opacity: '0',
  28910. border: '0'
  28911. } : {}),
  28912. attributes: attributes
  28913. },
  28914. components: containerComponents,
  28915. behaviours: derive$1([Keying.config({
  28916. mode: 'cyclic',
  28917. selector: '.tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a'
  28918. })])
  28919. }));
  28920. lazyOuterContainer = Optional.some(outerContainer);
  28921. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  28922. OuterContainer.focusMenubar(outerContainer);
  28923. });
  28924. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  28925. OuterContainer.focusToolbar(outerContainer);
  28926. });
  28927. editor.addCommand('ToggleToolbarDrawer', function () {
  28928. OuterContainer.toggleToolbarDrawer(outerContainer);
  28929. });
  28930. editor.addQueryStateHandler('ToggleToolbarDrawer', function () {
  28931. return OuterContainer.isToolbarDrawerToggled(outerContainer);
  28932. });
  28933. var mothership = takeover(outerContainer);
  28934. var uiMothership = takeover(sink);
  28935. setup$3(editor, mothership, uiMothership);
  28936. var getUi = function () {
  28937. var channels = {
  28938. broadcastAll: uiMothership.broadcast,
  28939. broadcastOn: uiMothership.broadcastOn,
  28940. register: function () {
  28941. }
  28942. };
  28943. return { channels: channels };
  28944. };
  28945. var setEditorSize = function () {
  28946. var parsedHeight = numToPx(getHeightWithFallback(editor));
  28947. var parsedWidth = numToPx(getWidthWithFallback(editor));
  28948. if (!editor.inline) {
  28949. if (isValidValue('div', 'width', parsedWidth)) {
  28950. set$2(outerContainer.element, 'width', parsedWidth);
  28951. }
  28952. if (isValidValue('div', 'height', parsedHeight)) {
  28953. set$2(outerContainer.element, 'height', parsedHeight);
  28954. } else {
  28955. set$2(outerContainer.element, 'height', '200px');
  28956. }
  28957. }
  28958. return parsedHeight;
  28959. };
  28960. var renderUI = function () {
  28961. header.setup(editor, backstage.shared, lazyHeader);
  28962. setup$8(editor, backstage);
  28963. setup$9(editor, lazySink, backstage);
  28964. setup$6(editor);
  28965. setup$7(editor, lazyThrobber, backstage.shared);
  28966. map$2(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  28967. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  28968. });
  28969. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  28970. var toolbarOpt = getMultipleToolbarsSetting(editor);
  28971. var rawUiConfig = {
  28972. menuItems: menuItems,
  28973. menus: getMenus(editor),
  28974. menubar: getMenubar(editor),
  28975. toolbar: toolbarOpt.getOrThunk(function () {
  28976. return getToolbar(editor);
  28977. }),
  28978. allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  28979. buttons: buttons,
  28980. sidebar: sidebars
  28981. };
  28982. register$4(editor, contextToolbars, sink, { backstage: backstage });
  28983. setup$a(editor, sink);
  28984. var elm = editor.getElement();
  28985. var height = setEditorSize();
  28986. var uiComponents = {
  28987. mothership: mothership,
  28988. uiMothership: uiMothership,
  28989. outerContainer: outerContainer
  28990. };
  28991. var args = {
  28992. targetNode: elm,
  28993. height: height
  28994. };
  28995. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  28996. };
  28997. return {
  28998. mothership: mothership,
  28999. uiMothership: uiMothership,
  29000. backstage: backstage,
  29001. renderUI: renderUI,
  29002. getUi: getUi
  29003. };
  29004. };
  29005. var describedBy = function (describedElement, describeElement) {
  29006. var describeId = Optional.from(get$2(describedElement, 'id')).fold(function () {
  29007. var id = generate$1('dialog-describe');
  29008. set$1(describeElement, 'id', id);
  29009. return id;
  29010. }, identity);
  29011. set$1(describedElement, 'aria-describedby', describeId);
  29012. };
  29013. var labelledBy = function (labelledElement, labelElement) {
  29014. var labelId = getOpt(labelledElement, 'id').fold(function () {
  29015. var id = generate$1('dialog-label');
  29016. set$1(labelElement, 'id', id);
  29017. return id;
  29018. }, identity);
  29019. set$1(labelledElement, 'aria-labelledby', labelId);
  29020. };
  29021. var schema$x = constant([
  29022. strict$1('lazySink'),
  29023. option('dragBlockClass'),
  29024. defaultedFunction('getBounds', win),
  29025. defaulted$1('useTabstopAt', always),
  29026. defaulted$1('eventOrder', {}),
  29027. field$1('modalBehaviours', [Keying]),
  29028. onKeyboardHandler('onExecute'),
  29029. onStrictKeyboardHandler('onEscape')
  29030. ]);
  29031. var basic = { sketch: identity };
  29032. var parts$f = constant([
  29033. optional({
  29034. name: 'draghandle',
  29035. overrides: function (detail, spec) {
  29036. return {
  29037. behaviours: derive$1([Dragging.config({
  29038. mode: 'mouse',
  29039. getTarget: function (handle) {
  29040. return ancestor$2(handle, '[role="dialog"]').getOr(handle);
  29041. },
  29042. blockerClass: detail.dragBlockClass.getOrDie(new Error('The drag blocker class was not specified for a dialog with a drag handle: \n' + JSON.stringify(spec, null, 2)).message),
  29043. getBounds: detail.getDragBounds
  29044. })])
  29045. };
  29046. }
  29047. }),
  29048. required({
  29049. schema: [strict$1('dom')],
  29050. name: 'title'
  29051. }),
  29052. required({
  29053. factory: basic,
  29054. schema: [strict$1('dom')],
  29055. name: 'close'
  29056. }),
  29057. required({
  29058. factory: basic,
  29059. schema: [strict$1('dom')],
  29060. name: 'body'
  29061. }),
  29062. optional({
  29063. factory: basic,
  29064. schema: [strict$1('dom')],
  29065. name: 'footer'
  29066. }),
  29067. external$1({
  29068. factory: {
  29069. sketch: function (spec, detail) {
  29070. return __assign(__assign({}, spec), {
  29071. dom: detail.dom,
  29072. components: detail.components
  29073. });
  29074. }
  29075. },
  29076. schema: [
  29077. defaulted$1('dom', {
  29078. tag: 'div',
  29079. styles: {
  29080. position: 'fixed',
  29081. left: '0px',
  29082. top: '0px',
  29083. right: '0px',
  29084. bottom: '0px'
  29085. }
  29086. }),
  29087. defaulted$1('components', [])
  29088. ],
  29089. name: 'blocker'
  29090. })
  29091. ]);
  29092. var factory$i = function (detail, components, spec, externals) {
  29093. var _a;
  29094. var dialogBusyEvent = generate$1('alloy.dialog.busy');
  29095. var dialogIdleEvent = generate$1('alloy.dialog.idle');
  29096. var busyBehaviours = derive$1([
  29097. Keying.config({
  29098. mode: 'special',
  29099. onTab: function () {
  29100. return Optional.some(true);
  29101. },
  29102. onShiftTab: function () {
  29103. return Optional.some(true);
  29104. }
  29105. }),
  29106. Focusing.config({})
  29107. ]);
  29108. var showDialog = function (dialog) {
  29109. var sink = detail.lazySink(dialog).getOrDie();
  29110. var busyComp = Cell(Optional.none());
  29111. var externalBlocker = externals.blocker();
  29112. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  29113. components: externalBlocker.components.concat([premade$1(dialog)]),
  29114. behaviours: derive$1([
  29115. Focusing.config({}),
  29116. config('dialog-blocker-events', [
  29117. runOnSource(focusin(), function () {
  29118. Keying.focusIn(dialog);
  29119. }),
  29120. run(dialogIdleEvent, function (_blocker, _se) {
  29121. if (has$1(dialog.element, 'aria-busy')) {
  29122. remove$1(dialog.element, 'aria-busy');
  29123. busyComp.get().each(function (bc) {
  29124. return Replacing.remove(dialog, bc);
  29125. });
  29126. }
  29127. }),
  29128. run(dialogBusyEvent, function (blocker, se) {
  29129. set$1(dialog.element, 'aria-busy', 'true');
  29130. var getBusySpec = se.event.getBusySpec;
  29131. busyComp.get().each(function (bc) {
  29132. Replacing.remove(dialog, bc);
  29133. });
  29134. var busySpec = getBusySpec(dialog, busyBehaviours);
  29135. var busy = blocker.getSystem().build(busySpec);
  29136. busyComp.set(Optional.some(busy));
  29137. Replacing.append(dialog, premade$1(busy));
  29138. if (busy.hasConfigured(Keying)) {
  29139. Keying.focusIn(busy);
  29140. }
  29141. })
  29142. ])
  29143. ])
  29144. }));
  29145. attach$1(sink, blocker);
  29146. Keying.focusIn(dialog);
  29147. };
  29148. var hideDialog = function (dialog) {
  29149. parent(dialog.element).each(function (blockerDom) {
  29150. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  29151. detach(blocker);
  29152. });
  29153. });
  29154. };
  29155. var getDialogBody = function (dialog) {
  29156. return getPartOrDie(dialog, detail, 'body');
  29157. };
  29158. var getDialogFooter = function (dialog) {
  29159. return getPartOrDie(dialog, detail, 'footer');
  29160. };
  29161. var setBusy = function (dialog, getBusySpec) {
  29162. emitWith(dialog, dialogBusyEvent, { getBusySpec: getBusySpec });
  29163. };
  29164. var setIdle = function (dialog) {
  29165. emit(dialog, dialogIdleEvent);
  29166. };
  29167. var modalEventsId = generate$1('modal-events');
  29168. var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a));
  29169. return {
  29170. uid: detail.uid,
  29171. dom: detail.dom,
  29172. components: components,
  29173. apis: {
  29174. show: showDialog,
  29175. hide: hideDialog,
  29176. getBody: getDialogBody,
  29177. getFooter: getDialogFooter,
  29178. setIdle: setIdle,
  29179. setBusy: setBusy
  29180. },
  29181. eventOrder: eventOrder,
  29182. domModification: {
  29183. attributes: {
  29184. 'role': 'dialog',
  29185. 'aria-modal': 'true'
  29186. }
  29187. },
  29188. behaviours: augment(detail.modalBehaviours, [
  29189. Replacing.config({}),
  29190. Keying.config({
  29191. mode: 'cyclic',
  29192. onEnter: detail.onExecute,
  29193. onEscape: detail.onEscape,
  29194. useTabstopAt: detail.useTabstopAt
  29195. }),
  29196. config(modalEventsId, [runOnAttached(function (c) {
  29197. labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
  29198. describedBy(c.element, getPartOrDie(c, detail, 'body').element);
  29199. })])
  29200. ])
  29201. };
  29202. };
  29203. var ModalDialog = composite$1({
  29204. name: 'ModalDialog',
  29205. configFields: schema$x(),
  29206. partFields: parts$f(),
  29207. factory: factory$i,
  29208. apis: {
  29209. show: function (apis, dialog) {
  29210. apis.show(dialog);
  29211. },
  29212. hide: function (apis, dialog) {
  29213. apis.hide(dialog);
  29214. },
  29215. getBody: function (apis, dialog) {
  29216. return apis.getBody(dialog);
  29217. },
  29218. getFooter: function (apis, dialog) {
  29219. return apis.getFooter(dialog);
  29220. },
  29221. setBusy: function (apis, dialog, getBusySpec) {
  29222. apis.setBusy(dialog, getBusySpec);
  29223. },
  29224. setIdle: function (apis, dialog) {
  29225. apis.setIdle(dialog);
  29226. }
  29227. }
  29228. });
  29229. var dialogToggleMenuItemSchema = objOf([
  29230. strictString('type'),
  29231. strictString('name')
  29232. ].concat(commonMenuItemFields));
  29233. var dialogToggleMenuItemDataProcessor = boolean;
  29234. var baseFooterButtonFields = [
  29235. field('name', 'name', defaultedThunk(function () {
  29236. return generate$1('button-name');
  29237. }), string),
  29238. optionString('icon'),
  29239. defaultedStringEnum('align', 'end', [
  29240. 'start',
  29241. 'end'
  29242. ]),
  29243. defaultedBoolean('primary', false),
  29244. defaultedBoolean('disabled', false)
  29245. ];
  29246. var dialogFooterButtonFields = __spreadArrays(baseFooterButtonFields, [strictString('text')]);
  29247. var normalFooterButtonFields = __spreadArrays([strictStringEnum('type', [
  29248. 'submit',
  29249. 'cancel',
  29250. 'custom'
  29251. ])], dialogFooterButtonFields);
  29252. var menuFooterButtonFields = __spreadArrays([
  29253. strictStringEnum('type', ['menu']),
  29254. optionString('text'),
  29255. optionString('tooltip'),
  29256. optionString('icon'),
  29257. strictArrayOf('items', dialogToggleMenuItemSchema)
  29258. ], baseFooterButtonFields);
  29259. var dialogFooterButtonSchema = choose$1('type', {
  29260. submit: normalFooterButtonFields,
  29261. cancel: normalFooterButtonFields,
  29262. custom: normalFooterButtonFields,
  29263. menu: menuFooterButtonFields
  29264. });
  29265. var alertBannerFields = [
  29266. strictString('type'),
  29267. strictString('text'),
  29268. strictStringEnum('level', [
  29269. 'info',
  29270. 'warn',
  29271. 'error',
  29272. 'success'
  29273. ]),
  29274. strictString('icon'),
  29275. defaulted$1('url', '')
  29276. ];
  29277. var alertBannerSchema = objOf(alertBannerFields);
  29278. var createBarFields = function (itemsField) {
  29279. return [
  29280. strictString('type'),
  29281. itemsField
  29282. ];
  29283. };
  29284. var buttonFields = [
  29285. strictString('type'),
  29286. strictString('text'),
  29287. defaultedBoolean('disabled', false),
  29288. defaultedBoolean('primary', false),
  29289. field('name', 'name', defaultedThunk(function () {
  29290. return generate$1('button-name');
  29291. }), string),
  29292. optionString('icon'),
  29293. defaultedBoolean('borderless', false)
  29294. ];
  29295. var buttonSchema = objOf(buttonFields);
  29296. var checkboxFields = [
  29297. strictString('type'),
  29298. strictString('name'),
  29299. strictString('label'),
  29300. defaultedBoolean('disabled', false)
  29301. ];
  29302. var checkboxSchema = objOf(checkboxFields);
  29303. var checkboxDataProcessor = boolean;
  29304. var formComponentFields = [
  29305. strictString('type'),
  29306. strictString('name')
  29307. ];
  29308. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  29309. var collectionFields = formComponentWithLabelFields.concat([defaulted$1('columns', 'auto')]);
  29310. var collectionSchema = objOf(collectionFields);
  29311. var collectionDataProcessor = arrOfObj$1([
  29312. strictString('value'),
  29313. strictString('text'),
  29314. strictString('icon')
  29315. ]);
  29316. var colorInputFields = formComponentWithLabelFields;
  29317. var colorInputSchema = objOf(colorInputFields);
  29318. var colorInputDataProcessor = string;
  29319. var colorPickerFields = formComponentWithLabelFields;
  29320. var colorPickerSchema = objOf(colorPickerFields);
  29321. var colorPickerDataProcessor = string;
  29322. var customEditorFields = formComponentFields.concat([
  29323. defaultedString('tag', 'textarea'),
  29324. strictString('scriptId'),
  29325. strictString('scriptUrl'),
  29326. defaultedPostMsg('settings', undefined)
  29327. ]);
  29328. var customEditorFieldsOld = formComponentFields.concat([
  29329. defaultedString('tag', 'textarea'),
  29330. strictFunction('init')
  29331. ]);
  29332. var customEditorSchema = valueOf(function (v) {
  29333. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  29334. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  29335. });
  29336. });
  29337. var customEditorDataProcessor = string;
  29338. var dropZoneFields = formComponentWithLabelFields;
  29339. var dropZoneSchema = objOf(dropZoneFields);
  29340. var dropZoneDataProcessor = arrOfVal();
  29341. var createGridFields = function (itemsField) {
  29342. return [
  29343. strictString('type'),
  29344. strictNumber('columns'),
  29345. itemsField
  29346. ];
  29347. };
  29348. var htmlPanelFields = [
  29349. strictString('type'),
  29350. strictString('html'),
  29351. defaultedStringEnum('presets', 'presentation', [
  29352. 'presentation',
  29353. 'document'
  29354. ])
  29355. ];
  29356. var htmlPanelSchema = objOf(htmlPanelFields);
  29357. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  29358. var iframeSchema = objOf(iframeFields);
  29359. var iframeDataProcessor = string;
  29360. var imageToolsFields = formComponentWithLabelFields.concat([strictOf('currentState', objOf([
  29361. strict$1('blob'),
  29362. strictString('url')
  29363. ]))]);
  29364. var imageToolsSchema = objOf(imageToolsFields);
  29365. var inputFields = formComponentWithLabelFields.concat([
  29366. optionString('inputMode'),
  29367. optionString('placeholder'),
  29368. defaultedBoolean('maximized', false),
  29369. defaultedBoolean('disabled', false)
  29370. ]);
  29371. var inputSchema = objOf(inputFields);
  29372. var inputDataProcessor = string;
  29373. var createLabelFields = function (itemsField) {
  29374. return [
  29375. strictString('type'),
  29376. strictString('label'),
  29377. itemsField
  29378. ];
  29379. };
  29380. var listBoxSingleItemFields = [
  29381. strictString('text'),
  29382. strictString('value')
  29383. ];
  29384. var listBoxNestedItemFields = [
  29385. strictString('text'),
  29386. strictArrayOf('items', thunkOf('items', function () {
  29387. return listBoxItemSchema;
  29388. }))
  29389. ];
  29390. var listBoxItemSchema = oneOf([
  29391. objOf(listBoxSingleItemFields),
  29392. objOf(listBoxNestedItemFields)
  29393. ]);
  29394. var listBoxFields = formComponentWithLabelFields.concat([
  29395. strictArrayOf('items', listBoxItemSchema),
  29396. defaultedBoolean('disabled', false)
  29397. ]);
  29398. var listBoxSchema = objOf(listBoxFields);
  29399. var listBoxDataProcessor = string;
  29400. var selectBoxFields = formComponentWithLabelFields.concat([
  29401. strictArrayOfObj('items', [
  29402. strictString('text'),
  29403. strictString('value')
  29404. ]),
  29405. defaultedNumber('size', 1),
  29406. defaultedBoolean('disabled', false)
  29407. ]);
  29408. var selectBoxSchema = objOf(selectBoxFields);
  29409. var selectBoxDataProcessor = string;
  29410. var sizeInputFields = formComponentWithLabelFields.concat([
  29411. defaultedBoolean('constrain', true),
  29412. defaultedBoolean('disabled', false)
  29413. ]);
  29414. var sizeInputSchema = objOf(sizeInputFields);
  29415. var sizeInputDataProcessor = objOf([
  29416. strictString('width'),
  29417. strictString('height')
  29418. ]);
  29419. var tableFields = [
  29420. strictString('type'),
  29421. strictArrayOf('header', string),
  29422. strictArrayOf('cells', arrOf(string))
  29423. ];
  29424. var tableSchema = objOf(tableFields);
  29425. var textAreaFields = formComponentWithLabelFields.concat([
  29426. optionString('placeholder'),
  29427. defaultedBoolean('maximized', false),
  29428. defaultedBoolean('disabled', false)
  29429. ]);
  29430. var textAreaSchema = objOf(textAreaFields);
  29431. var textAreaDataProcessor = string;
  29432. var urlInputFields = formComponentWithLabelFields.concat([
  29433. defaultedStringEnum('filetype', 'file', [
  29434. 'image',
  29435. 'media',
  29436. 'file'
  29437. ]),
  29438. defaulted$1('disabled', false)
  29439. ]);
  29440. var urlInputSchema = objOf(urlInputFields);
  29441. var urlInputDataProcessor = objOf([
  29442. strictString('value'),
  29443. defaulted$1('meta', {})
  29444. ]);
  29445. var createItemsField = function (name) {
  29446. return field('items', 'items', strict(), arrOf(valueOf(function (v) {
  29447. return asRaw('Checking item of ' + name, itemSchema$2, v).fold(function (sErr) {
  29448. return Result.error(formatError(sErr));
  29449. }, function (passValue) {
  29450. return Result.value(passValue);
  29451. });
  29452. })));
  29453. };
  29454. var itemSchema$2 = valueThunkOf(function () {
  29455. return chooseProcessor('type', {
  29456. alertbanner: alertBannerSchema,
  29457. bar: objOf(createBarFields(createItemsField('bar'))),
  29458. button: buttonSchema,
  29459. checkbox: checkboxSchema,
  29460. colorinput: colorInputSchema,
  29461. colorpicker: colorPickerSchema,
  29462. dropzone: dropZoneSchema,
  29463. grid: objOf(createGridFields(createItemsField('grid'))),
  29464. iframe: iframeSchema,
  29465. input: inputSchema,
  29466. listbox: listBoxSchema,
  29467. selectbox: selectBoxSchema,
  29468. sizeinput: sizeInputSchema,
  29469. textarea: textAreaSchema,
  29470. urlinput: urlInputSchema,
  29471. customeditor: customEditorSchema,
  29472. htmlpanel: htmlPanelSchema,
  29473. imagetools: imageToolsSchema,
  29474. collection: collectionSchema,
  29475. label: objOf(createLabelFields(createItemsField('label'))),
  29476. table: tableSchema,
  29477. panel: panelSchema
  29478. });
  29479. });
  29480. var panelFields = [
  29481. strictString('type'),
  29482. defaulted$1('classes', []),
  29483. strictArrayOf('items', itemSchema$2)
  29484. ];
  29485. var panelSchema = objOf(panelFields);
  29486. var tabFields = [
  29487. field('name', 'name', defaultedThunk(function () {
  29488. return generate$1('tab-name');
  29489. }), string),
  29490. strictString('title'),
  29491. strictArrayOf('items', itemSchema$2)
  29492. ];
  29493. var tabPanelFields = [
  29494. strictString('type'),
  29495. strictArrayOfObj('tabs', tabFields)
  29496. ];
  29497. var tabPanelSchema = objOf(tabPanelFields);
  29498. var dialogButtonFields = dialogFooterButtonFields;
  29499. var dialogButtonSchema = dialogFooterButtonSchema;
  29500. var dialogSchema = objOf([
  29501. strictString('title'),
  29502. strictOf('body', chooseProcessor('type', {
  29503. panel: panelSchema,
  29504. tabpanel: tabPanelSchema
  29505. })),
  29506. defaultedString('size', 'normal'),
  29507. strictArrayOf('buttons', dialogButtonSchema),
  29508. defaulted$1('initialData', {}),
  29509. defaultedFunction('onAction', noop),
  29510. defaultedFunction('onChange', noop),
  29511. defaultedFunction('onSubmit', noop),
  29512. defaultedFunction('onClose', noop),
  29513. defaultedFunction('onCancel', noop),
  29514. defaulted$1('onTabChange', noop)
  29515. ]);
  29516. var createDialog = function (spec) {
  29517. return asRaw('dialog', dialogSchema, spec);
  29518. };
  29519. var urlDialogButtonSchema = objOf(__spreadArrays([strictStringEnum('type', [
  29520. 'cancel',
  29521. 'custom'
  29522. ])], dialogButtonFields));
  29523. var urlDialogSchema = objOf([
  29524. strictString('title'),
  29525. strictString('url'),
  29526. optionNumber('height'),
  29527. optionNumber('width'),
  29528. optionArrayOf('buttons', urlDialogButtonSchema),
  29529. defaultedFunction('onAction', noop),
  29530. defaultedFunction('onCancel', noop),
  29531. defaultedFunction('onClose', noop),
  29532. defaultedFunction('onMessage', noop)
  29533. ]);
  29534. var createUrlDialog = function (spec) {
  29535. return asRaw('dialog', urlDialogSchema, spec);
  29536. };
  29537. var getAllObjects = function (obj) {
  29538. if (isObject(obj)) {
  29539. return [obj].concat(bind(values(obj), getAllObjects));
  29540. } else if (isArray(obj)) {
  29541. return bind(obj, getAllObjects);
  29542. } else {
  29543. return [];
  29544. }
  29545. };
  29546. var isNamedItem = function (obj) {
  29547. return isString(obj.type) && isString(obj.name);
  29548. };
  29549. var dataProcessors = {
  29550. checkbox: checkboxDataProcessor,
  29551. colorinput: colorInputDataProcessor,
  29552. colorpicker: colorPickerDataProcessor,
  29553. dropzone: dropZoneDataProcessor,
  29554. input: inputDataProcessor,
  29555. iframe: iframeDataProcessor,
  29556. sizeinput: sizeInputDataProcessor,
  29557. selectbox: selectBoxDataProcessor,
  29558. listbox: listBoxDataProcessor,
  29559. size: sizeInputDataProcessor,
  29560. textarea: textAreaDataProcessor,
  29561. urlinput: urlInputDataProcessor,
  29562. customeditor: customEditorDataProcessor,
  29563. collection: collectionDataProcessor,
  29564. togglemenuitem: dialogToggleMenuItemDataProcessor
  29565. };
  29566. var getDataProcessor = function (item) {
  29567. return Optional.from(dataProcessors[item.type]);
  29568. };
  29569. var getNamedItems = function (structure) {
  29570. return filter(getAllObjects(structure), isNamedItem);
  29571. };
  29572. var createDataValidator = function (structure) {
  29573. var namedItems = getNamedItems(structure);
  29574. var fields = bind(namedItems, function (item) {
  29575. return getDataProcessor(item).fold(function () {
  29576. return [];
  29577. }, function (schema) {
  29578. return [strictOf(item.name, schema)];
  29579. });
  29580. });
  29581. return objOf(fields);
  29582. };
  29583. var extract$1 = function (structure) {
  29584. var internalDialog = getOrDie(createDialog(structure));
  29585. var dataValidator = createDataValidator(structure);
  29586. var initialData = structure.initialData;
  29587. return {
  29588. internalDialog: internalDialog,
  29589. dataValidator: dataValidator,
  29590. initialData: initialData
  29591. };
  29592. };
  29593. var DialogManager = {
  29594. open: function (factory, structure) {
  29595. var extraction = extract$1(structure);
  29596. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  29597. },
  29598. openUrl: function (factory, structure) {
  29599. var internalDialog = getOrDie(createUrlDialog(structure));
  29600. return factory(internalDialog);
  29601. },
  29602. redial: function (structure) {
  29603. return extract$1(structure);
  29604. }
  29605. };
  29606. var toValidValues = function (values) {
  29607. var errors = [];
  29608. var result = {};
  29609. each$1(values, function (value, name) {
  29610. value.fold(function () {
  29611. errors.push(name);
  29612. }, function (v) {
  29613. result[name] = v;
  29614. });
  29615. });
  29616. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  29617. };
  29618. var renderBodyPanel = function (spec, backstage) {
  29619. var memForm = record(Form.sketch(function (parts) {
  29620. return {
  29621. dom: {
  29622. tag: 'div',
  29623. classes: ['tox-form'].concat(spec.classes)
  29624. },
  29625. components: map(spec.items, function (item) {
  29626. return interpretInForm(parts, item, backstage);
  29627. })
  29628. };
  29629. }));
  29630. return {
  29631. dom: {
  29632. tag: 'div',
  29633. classes: ['tox-dialog__body']
  29634. },
  29635. components: [{
  29636. dom: {
  29637. tag: 'div',
  29638. classes: ['tox-dialog__body-content']
  29639. },
  29640. components: [memForm.asSpec()]
  29641. }],
  29642. behaviours: derive$1([
  29643. Keying.config({
  29644. mode: 'acyclic',
  29645. useTabstopAt: not(isPseudoStop)
  29646. }),
  29647. ComposingConfigs.memento(memForm),
  29648. RepresentingConfigs.memento(memForm, {
  29649. postprocess: function (formValue) {
  29650. return toValidValues(formValue).fold(function (err) {
  29651. console.error(err);
  29652. return {};
  29653. }, function (vals) {
  29654. return vals;
  29655. });
  29656. }
  29657. })
  29658. ])
  29659. };
  29660. };
  29661. var factory$j = function (detail, _spec) {
  29662. return {
  29663. uid: detail.uid,
  29664. dom: detail.dom,
  29665. components: detail.components,
  29666. events: events$7(detail.action),
  29667. behaviours: augment(detail.tabButtonBehaviours, [
  29668. Focusing.config({}),
  29669. Keying.config({
  29670. mode: 'execution',
  29671. useSpace: true,
  29672. useEnter: true
  29673. }),
  29674. Representing.config({
  29675. store: {
  29676. mode: 'memory',
  29677. initialValue: detail.value
  29678. }
  29679. })
  29680. ]),
  29681. domModification: detail.domModification
  29682. };
  29683. };
  29684. var TabButton = single$2({
  29685. name: 'TabButton',
  29686. configFields: [
  29687. defaulted$1('uid', undefined),
  29688. strict$1('value'),
  29689. field('dom', 'dom', mergeWithThunk(function () {
  29690. return {
  29691. attributes: {
  29692. 'role': 'tab',
  29693. 'id': generate$1('aria'),
  29694. 'aria-selected': 'false'
  29695. }
  29696. };
  29697. }), anyValue$1()),
  29698. option('action'),
  29699. defaulted$1('domModification', {}),
  29700. field$1('tabButtonBehaviours', [
  29701. Focusing,
  29702. Keying,
  29703. Representing
  29704. ]),
  29705. strict$1('view')
  29706. ],
  29707. factory: factory$j
  29708. });
  29709. var schema$y = constant([
  29710. strict$1('tabs'),
  29711. strict$1('dom'),
  29712. defaulted$1('clickToDismiss', false),
  29713. field$1('tabbarBehaviours', [
  29714. Highlighting,
  29715. Keying
  29716. ]),
  29717. markers([
  29718. 'tabClass',
  29719. 'selectedClass'
  29720. ])
  29721. ]);
  29722. var tabsPart = group({
  29723. factory: TabButton,
  29724. name: 'tabs',
  29725. unit: 'tab',
  29726. overrides: function (barDetail) {
  29727. var dismissTab$1 = function (tabbar, button) {
  29728. Highlighting.dehighlight(tabbar, button);
  29729. emitWith(tabbar, dismissTab(), {
  29730. tabbar: tabbar,
  29731. button: button
  29732. });
  29733. };
  29734. var changeTab$1 = function (tabbar, button) {
  29735. Highlighting.highlight(tabbar, button);
  29736. emitWith(tabbar, changeTab(), {
  29737. tabbar: tabbar,
  29738. button: button
  29739. });
  29740. };
  29741. return {
  29742. action: function (button) {
  29743. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  29744. var activeButton = Highlighting.isHighlighted(tabbar, button);
  29745. var response = function () {
  29746. if (activeButton && barDetail.clickToDismiss) {
  29747. return dismissTab$1;
  29748. } else if (!activeButton) {
  29749. return changeTab$1;
  29750. } else {
  29751. return noop;
  29752. }
  29753. }();
  29754. response(tabbar, button);
  29755. },
  29756. domModification: { classes: [barDetail.markers.tabClass] }
  29757. };
  29758. }
  29759. });
  29760. var parts$g = constant([tabsPart]);
  29761. var factory$k = function (detail, components, _spec, _externals) {
  29762. return {
  29763. 'uid': detail.uid,
  29764. 'dom': detail.dom,
  29765. components: components,
  29766. 'debug.sketcher': 'Tabbar',
  29767. 'domModification': { attributes: { role: 'tablist' } },
  29768. 'behaviours': augment(detail.tabbarBehaviours, [
  29769. Highlighting.config({
  29770. highlightClass: detail.markers.selectedClass,
  29771. itemClass: detail.markers.tabClass,
  29772. onHighlight: function (tabbar, tab) {
  29773. set$1(tab.element, 'aria-selected', 'true');
  29774. },
  29775. onDehighlight: function (tabbar, tab) {
  29776. set$1(tab.element, 'aria-selected', 'false');
  29777. }
  29778. }),
  29779. Keying.config({
  29780. mode: 'flow',
  29781. getInitial: function (tabbar) {
  29782. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  29783. return tab.element;
  29784. });
  29785. },
  29786. selector: '.' + detail.markers.tabClass,
  29787. executeOnMove: true
  29788. })
  29789. ])
  29790. };
  29791. };
  29792. var Tabbar = composite$1({
  29793. name: 'Tabbar',
  29794. configFields: schema$y(),
  29795. partFields: parts$g(),
  29796. factory: factory$k
  29797. });
  29798. var factory$l = function (detail, _spec) {
  29799. return {
  29800. uid: detail.uid,
  29801. dom: detail.dom,
  29802. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  29803. domModification: { attributes: { role: 'tabpanel' } }
  29804. };
  29805. };
  29806. var Tabview = single$2({
  29807. name: 'Tabview',
  29808. configFields: [field$1('tabviewBehaviours', [Replacing])],
  29809. factory: factory$l
  29810. });
  29811. var schema$z = constant([
  29812. defaulted$1('selectFirst', true),
  29813. onHandler('onChangeTab'),
  29814. onHandler('onDismissTab'),
  29815. defaulted$1('tabs', []),
  29816. field$1('tabSectionBehaviours', [])
  29817. ]);
  29818. var barPart = required({
  29819. factory: Tabbar,
  29820. schema: [
  29821. strict$1('dom'),
  29822. strictObjOf('markers', [
  29823. strict$1('tabClass'),
  29824. strict$1('selectedClass')
  29825. ])
  29826. ],
  29827. name: 'tabbar',
  29828. defaults: function (detail) {
  29829. return { tabs: detail.tabs };
  29830. }
  29831. });
  29832. var viewPart = required({
  29833. factory: Tabview,
  29834. name: 'tabview'
  29835. });
  29836. var parts$h = constant([
  29837. barPart,
  29838. viewPart
  29839. ]);
  29840. var factory$m = function (detail, components, _spec, _externals) {
  29841. var changeTab$1 = function (button) {
  29842. var tabValue = Representing.getValue(button);
  29843. getPart(button, detail, 'tabview').each(function (tabview) {
  29844. var tabWithValue = find(detail.tabs, function (t) {
  29845. return t.value === tabValue;
  29846. });
  29847. tabWithValue.each(function (tabData) {
  29848. var panel = tabData.view();
  29849. getOpt(button.element, 'id').each(function (id) {
  29850. set$1(tabview.element, 'aria-labelledby', id);
  29851. });
  29852. Replacing.set(tabview, panel);
  29853. detail.onChangeTab(tabview, button, panel);
  29854. });
  29855. });
  29856. };
  29857. var changeTabBy = function (section, byPred) {
  29858. getPart(section, detail, 'tabbar').each(function (tabbar) {
  29859. byPred(tabbar).each(emitExecute);
  29860. });
  29861. };
  29862. return {
  29863. uid: detail.uid,
  29864. dom: detail.dom,
  29865. components: components,
  29866. behaviours: get$c(detail.tabSectionBehaviours),
  29867. events: derive(flatten([
  29868. detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
  29869. changeTabBy(section, Highlighting.getFirst);
  29870. })] : [],
  29871. [
  29872. run(changeTab(), function (section, simulatedEvent) {
  29873. var button = simulatedEvent.event.button;
  29874. changeTab$1(button);
  29875. }),
  29876. run(dismissTab(), function (section, simulatedEvent) {
  29877. var button = simulatedEvent.event.button;
  29878. detail.onDismissTab(section, button);
  29879. })
  29880. ]
  29881. ])),
  29882. apis: {
  29883. getViewItems: function (section) {
  29884. return getPart(section, detail, 'tabview').map(function (tabview) {
  29885. return Replacing.contents(tabview);
  29886. }).getOr([]);
  29887. },
  29888. showTab: function (section, tabKey) {
  29889. var getTabIfNotActive = function (tabbar) {
  29890. var candidates = Highlighting.getCandidates(tabbar);
  29891. var optTab = find(candidates, function (c) {
  29892. return Representing.getValue(c) === tabKey;
  29893. });
  29894. return optTab.filter(function (tab) {
  29895. return !Highlighting.isHighlighted(tabbar, tab);
  29896. });
  29897. };
  29898. changeTabBy(section, getTabIfNotActive);
  29899. }
  29900. }
  29901. };
  29902. };
  29903. var TabSection = composite$1({
  29904. name: 'TabSection',
  29905. configFields: schema$z(),
  29906. partFields: parts$h(),
  29907. factory: factory$m,
  29908. apis: {
  29909. getViewItems: function (apis, component) {
  29910. return apis.getViewItems(component);
  29911. },
  29912. showTab: function (apis, component, tabKey) {
  29913. apis.showTab(component, tabKey);
  29914. }
  29915. }
  29916. });
  29917. var measureHeights = function (allTabs, tabview, tabviewComp) {
  29918. return map(allTabs, function (_tab, i) {
  29919. Replacing.set(tabviewComp, allTabs[i].view());
  29920. var rect = tabview.dom.getBoundingClientRect();
  29921. Replacing.set(tabviewComp, []);
  29922. return rect.height;
  29923. });
  29924. };
  29925. var getMaxHeight = function (heights) {
  29926. return head(sort(heights, function (a, b) {
  29927. if (a > b) {
  29928. return -1;
  29929. } else if (a < b) {
  29930. return +1;
  29931. } else {
  29932. return 0;
  29933. }
  29934. }));
  29935. };
  29936. var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  29937. var documentElement$1 = documentElement(dialog).dom;
  29938. var rootElm = ancestor$2(dialog, '.tox-dialog-wrap').getOr(dialog);
  29939. var isFixed = get$4(rootElm, 'position') === 'fixed';
  29940. var maxHeight;
  29941. if (isFixed) {
  29942. maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
  29943. } else {
  29944. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  29945. }
  29946. var tabviewHeight = get$6(tabview);
  29947. var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$7(tablist);
  29948. var currentTabHeight = isTabListBeside ? Math.max(get$6(tablist), tabviewHeight) : tabviewHeight;
  29949. var dialogTopMargin = parseInt(get$4(dialog, 'margin-top'), 10) || 0;
  29950. var dialogBottomMargin = parseInt(get$4(dialog, 'margin-bottom'), 10) || 0;
  29951. var dialogHeight = get$6(dialog) + dialogTopMargin + dialogBottomMargin;
  29952. var chromeHeight = dialogHeight - currentTabHeight;
  29953. return maxHeight - chromeHeight;
  29954. };
  29955. var showTab = function (allTabs, comp) {
  29956. head(allTabs).each(function (tab) {
  29957. return TabSection.showTab(comp, tab.value);
  29958. });
  29959. };
  29960. var setTabviewHeight = function (tabview, height) {
  29961. set$2(tabview, 'height', height + 'px');
  29962. if (!detect$3().browser.isIE()) {
  29963. set$2(tabview, 'flex-basis', height + 'px');
  29964. } else {
  29965. remove$6(tabview, 'flex-basis');
  29966. }
  29967. };
  29968. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  29969. ancestor$2(dialogBody, '[role="dialog"]').each(function (dialog) {
  29970. descendant$1(dialog, '[role="tablist"]').each(function (tablist) {
  29971. maxTabHeight.get().map(function (height) {
  29972. set$2(tabview, 'height', '0');
  29973. set$2(tabview, 'flex-basis', '0');
  29974. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  29975. }).each(function (height) {
  29976. setTabviewHeight(tabview, height);
  29977. });
  29978. });
  29979. });
  29980. };
  29981. var getTabview = function (dialog) {
  29982. return descendant$1(dialog, '[role="tabpanel"]');
  29983. };
  29984. var setMode = function (allTabs) {
  29985. var smartTabHeight = function () {
  29986. var maxTabHeight = Cell(Optional.none());
  29987. var extraEvents = [
  29988. runOnAttached(function (comp) {
  29989. var dialog = comp.element;
  29990. getTabview(dialog).each(function (tabview) {
  29991. set$2(tabview, 'visibility', 'hidden');
  29992. comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) {
  29993. var heights = measureHeights(allTabs, tabview, tabviewComp);
  29994. var maxTabHeightOpt = getMaxHeight(heights);
  29995. maxTabHeight.set(maxTabHeightOpt);
  29996. });
  29997. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29998. remove$6(tabview, 'visibility');
  29999. showTab(allTabs, comp);
  30000. global$2.requestAnimationFrame(function () {
  30001. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30002. });
  30003. });
  30004. }),
  30005. run(windowResize(), function (comp) {
  30006. var dialog = comp.element;
  30007. getTabview(dialog).each(function (tabview) {
  30008. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30009. });
  30010. }),
  30011. run(formResizeEvent, function (comp, _se) {
  30012. var dialog = comp.element;
  30013. getTabview(dialog).each(function (tabview) {
  30014. var oldFocus = active();
  30015. set$2(tabview, 'visibility', 'hidden');
  30016. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  30017. return parseInt(h, 10);
  30018. });
  30019. remove$6(tabview, 'height');
  30020. remove$6(tabview, 'flex-basis');
  30021. var newHeight = tabview.dom.getBoundingClientRect().height;
  30022. var hasGrown = oldHeight.forall(function (h) {
  30023. return newHeight > h;
  30024. });
  30025. if (hasGrown) {
  30026. maxTabHeight.set(Optional.from(newHeight));
  30027. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30028. } else {
  30029. oldHeight.each(function (h) {
  30030. setTabviewHeight(tabview, h);
  30031. });
  30032. }
  30033. remove$6(tabview, 'visibility');
  30034. oldFocus.each(focus$1);
  30035. });
  30036. })
  30037. ];
  30038. var selectFirst = false;
  30039. return {
  30040. extraEvents: extraEvents,
  30041. selectFirst: selectFirst
  30042. };
  30043. }();
  30044. var naiveTabHeight = function () {
  30045. var extraEvents = [];
  30046. var selectFirst = true;
  30047. return {
  30048. extraEvents: extraEvents,
  30049. selectFirst: selectFirst
  30050. };
  30051. }();
  30052. return {
  30053. smartTabHeight: smartTabHeight,
  30054. naiveTabHeight: naiveTabHeight
  30055. };
  30056. };
  30057. var SendDataToSectionChannel = 'send-data-to-section';
  30058. var SendDataToViewChannel = 'send-data-to-view';
  30059. var renderTabPanel = function (spec, backstage) {
  30060. var storedValue = Cell({});
  30061. var updateDataWithForm = function (form) {
  30062. var formData = Representing.getValue(form);
  30063. var validData = toValidValues(formData).getOr({});
  30064. var currentData = storedValue.get();
  30065. var newData = deepMerge(currentData, validData);
  30066. storedValue.set(newData);
  30067. };
  30068. var setDataOnForm = function (form) {
  30069. var tabData = storedValue.get();
  30070. Representing.setValue(form, tabData);
  30071. };
  30072. var oldTab = Cell(null);
  30073. var allTabs = map(spec.tabs, function (tab) {
  30074. return {
  30075. value: tab.name,
  30076. dom: {
  30077. tag: 'div',
  30078. classes: ['tox-dialog__body-nav-item'],
  30079. innerHtml: backstage.shared.providers.translate(tab.title)
  30080. },
  30081. view: function () {
  30082. return [Form.sketch(function (parts) {
  30083. return {
  30084. dom: {
  30085. tag: 'div',
  30086. classes: ['tox-form']
  30087. },
  30088. components: map(tab.items, function (item) {
  30089. return interpretInForm(parts, item, backstage);
  30090. }),
  30091. formBehaviours: derive$1([
  30092. Keying.config({
  30093. mode: 'acyclic',
  30094. useTabstopAt: not(isPseudoStop)
  30095. }),
  30096. config('TabView.form.events', [
  30097. runOnAttached(setDataOnForm),
  30098. runOnDetached(updateDataWithForm)
  30099. ]),
  30100. Receiving.config({
  30101. channels: wrapAll$1([
  30102. {
  30103. key: SendDataToSectionChannel,
  30104. value: { onReceive: updateDataWithForm }
  30105. },
  30106. {
  30107. key: SendDataToViewChannel,
  30108. value: { onReceive: setDataOnForm }
  30109. }
  30110. ])
  30111. })
  30112. ])
  30113. };
  30114. })];
  30115. }
  30116. };
  30117. });
  30118. var tabMode = setMode(allTabs).smartTabHeight;
  30119. return TabSection.sketch({
  30120. dom: {
  30121. tag: 'div',
  30122. classes: ['tox-dialog__body']
  30123. },
  30124. onChangeTab: function (section, button, _viewItems) {
  30125. var name = Representing.getValue(button);
  30126. emitWith(section, formTabChangeEvent, {
  30127. name: name,
  30128. oldName: oldTab.get()
  30129. });
  30130. oldTab.set(name);
  30131. },
  30132. tabs: allTabs,
  30133. components: [
  30134. TabSection.parts.tabbar({
  30135. dom: {
  30136. tag: 'div',
  30137. classes: ['tox-dialog__body-nav']
  30138. },
  30139. components: [Tabbar.parts.tabs({})],
  30140. markers: {
  30141. tabClass: 'tox-tab',
  30142. selectedClass: 'tox-dialog__body-nav-item--active'
  30143. },
  30144. tabbarBehaviours: derive$1([Tabstopping.config({})])
  30145. }),
  30146. TabSection.parts.tabview({
  30147. dom: {
  30148. tag: 'div',
  30149. classes: ['tox-dialog__body-content']
  30150. }
  30151. })
  30152. ],
  30153. selectFirst: tabMode.selectFirst,
  30154. tabSectionBehaviours: derive$1([
  30155. config('tabpanel', tabMode.extraEvents),
  30156. Keying.config({ mode: 'acyclic' }),
  30157. Composing.config({
  30158. find: function (comp) {
  30159. return head(TabSection.getViewItems(comp));
  30160. }
  30161. }),
  30162. Representing.config({
  30163. store: {
  30164. mode: 'manual',
  30165. getValue: function (tsection) {
  30166. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  30167. return storedValue.get();
  30168. },
  30169. setValue: function (tsection, value) {
  30170. storedValue.set(value);
  30171. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  30172. }
  30173. }
  30174. })
  30175. ])
  30176. });
  30177. };
  30178. var dialogChannel = generate$1('update-dialog');
  30179. var titleChannel = generate$1('update-title');
  30180. var bodyChannel = generate$1('update-body');
  30181. var footerChannel = generate$1('update-footer');
  30182. var bodySendMessageChannel = generate$1('body-send-message');
  30183. var renderBody = function (spec, id, backstage, ariaAttrs) {
  30184. var renderComponents = function (incoming) {
  30185. switch (incoming.body.type) {
  30186. case 'tabpanel': {
  30187. return [renderTabPanel(incoming.body, backstage)];
  30188. }
  30189. default: {
  30190. return [renderBodyPanel(incoming.body, backstage)];
  30191. }
  30192. }
  30193. };
  30194. var updateState = function (_comp, incoming) {
  30195. return Optional.some({
  30196. isTabPanel: function () {
  30197. return incoming.body.type === 'tabpanel';
  30198. }
  30199. });
  30200. };
  30201. var ariaAttributes = { 'aria-live': 'polite' };
  30202. return {
  30203. dom: {
  30204. tag: 'div',
  30205. classes: ['tox-dialog__content-js'],
  30206. attributes: __assign(__assign({}, id.map(function (x) {
  30207. return { id: x };
  30208. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  30209. },
  30210. components: [],
  30211. behaviours: derive$1([
  30212. ComposingConfigs.childAt(0),
  30213. Reflecting.config({
  30214. channel: bodyChannel,
  30215. updateState: updateState,
  30216. renderComponents: renderComponents,
  30217. initialData: spec
  30218. })
  30219. ])
  30220. };
  30221. };
  30222. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  30223. return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
  30224. };
  30225. var renderModalBody = function (spec, backstage) {
  30226. var bodySpec = renderBody(spec, Optional.none(), backstage, false);
  30227. return ModalDialog.parts.body(bodySpec);
  30228. };
  30229. var renderIframeBody = function (spec) {
  30230. var bodySpec = {
  30231. dom: {
  30232. tag: 'div',
  30233. classes: ['tox-dialog__content-js']
  30234. },
  30235. components: [{
  30236. dom: {
  30237. tag: 'div',
  30238. classes: ['tox-dialog__body-iframe']
  30239. },
  30240. components: [craft({
  30241. dom: {
  30242. tag: 'iframe',
  30243. attributes: { src: spec.url }
  30244. },
  30245. behaviours: derive$1([
  30246. Tabstopping.config({}),
  30247. Focusing.config({})
  30248. ])
  30249. })]
  30250. }],
  30251. behaviours: derive$1([Keying.config({
  30252. mode: 'acyclic',
  30253. useTabstopAt: not(isPseudoStop)
  30254. })])
  30255. };
  30256. return ModalDialog.parts.body(bodySpec);
  30257. };
  30258. var isTouch = global$8.deviceType.isTouch();
  30259. var hiddenHeader = function (title, close) {
  30260. return {
  30261. dom: {
  30262. tag: 'div',
  30263. styles: { display: 'none' },
  30264. classes: ['tox-dialog__header']
  30265. },
  30266. components: [
  30267. title,
  30268. close
  30269. ]
  30270. };
  30271. };
  30272. var pClose = function (onClose, providersBackstage) {
  30273. return ModalDialog.parts.close(Button.sketch({
  30274. dom: {
  30275. tag: 'button',
  30276. classes: [
  30277. 'tox-button',
  30278. 'tox-button--icon',
  30279. 'tox-button--naked'
  30280. ],
  30281. attributes: {
  30282. 'type': 'button',
  30283. 'aria-label': providersBackstage.translate('Close')
  30284. }
  30285. },
  30286. action: onClose,
  30287. buttonBehaviours: derive$1([Tabstopping.config({})])
  30288. }));
  30289. };
  30290. var pUntitled = function () {
  30291. return ModalDialog.parts.title({
  30292. dom: {
  30293. tag: 'div',
  30294. classes: ['tox-dialog__title'],
  30295. innerHtml: '',
  30296. styles: { display: 'none' }
  30297. }
  30298. });
  30299. };
  30300. var pBodyMessage = function (message, providersBackstage) {
  30301. return ModalDialog.parts.body({
  30302. dom: {
  30303. tag: 'div',
  30304. classes: ['tox-dialog__body']
  30305. },
  30306. components: [{
  30307. dom: {
  30308. tag: 'div',
  30309. classes: ['tox-dialog__body-content']
  30310. },
  30311. components: [{ dom: fromHtml$2('<p>' + providersBackstage.translate(message) + '</p>') }]
  30312. }]
  30313. });
  30314. };
  30315. var pFooter = function (buttons) {
  30316. return ModalDialog.parts.footer({
  30317. dom: {
  30318. tag: 'div',
  30319. classes: ['tox-dialog__footer']
  30320. },
  30321. components: buttons
  30322. });
  30323. };
  30324. var pFooterGroup = function (startButtons, endButtons) {
  30325. return [
  30326. Container.sketch({
  30327. dom: {
  30328. tag: 'div',
  30329. classes: ['tox-dialog__footer-start']
  30330. },
  30331. components: startButtons
  30332. }),
  30333. Container.sketch({
  30334. dom: {
  30335. tag: 'div',
  30336. classes: ['tox-dialog__footer-end']
  30337. },
  30338. components: endButtons
  30339. })
  30340. ];
  30341. };
  30342. var renderDialog = function (spec) {
  30343. var _a;
  30344. var dialogClass = 'tox-dialog';
  30345. var blockerClass = dialogClass + '-wrap';
  30346. var blockerBackdropClass = blockerClass + '__backdrop';
  30347. var scrollLockClass = dialogClass + '__disable-scroll';
  30348. return ModalDialog.sketch({
  30349. lazySink: spec.lazySink,
  30350. onEscape: function (comp) {
  30351. spec.onEscape(comp);
  30352. return Optional.some(true);
  30353. },
  30354. useTabstopAt: function (elem) {
  30355. return !isPseudoStop(elem);
  30356. },
  30357. dom: {
  30358. tag: 'div',
  30359. classes: [dialogClass].concat(spec.extraClasses),
  30360. styles: __assign({ position: 'relative' }, spec.extraStyles)
  30361. },
  30362. components: __spreadArrays([
  30363. spec.header,
  30364. spec.body
  30365. ], spec.footer.toArray()),
  30366. parts: {
  30367. blocker: {
  30368. dom: fromHtml$2('<div class="' + blockerClass + '"></div>'),
  30369. components: [{
  30370. dom: {
  30371. tag: 'div',
  30372. classes: isTouch ? [
  30373. blockerBackdropClass,
  30374. blockerBackdropClass + '--opaque'
  30375. ] : [blockerBackdropClass]
  30376. }
  30377. }]
  30378. }
  30379. },
  30380. dragBlockClass: blockerClass,
  30381. modalBehaviours: derive$1(__spreadArrays([
  30382. Focusing.config({}),
  30383. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  30384. Keying.focusIn(comp);
  30385. })])),
  30386. config('scroll-lock', [
  30387. runOnAttached(function () {
  30388. add$2(body(), scrollLockClass);
  30389. }),
  30390. runOnDetached(function () {
  30391. remove$4(body(), scrollLockClass);
  30392. })
  30393. ])
  30394. ], spec.extraBehaviours)),
  30395. eventOrder: __assign((_a = {}, _a[execute()] = ['dialog-events'], _a[attachedToDom()] = [
  30396. 'scroll-lock',
  30397. 'dialog-events',
  30398. 'alloy.base.behaviour'
  30399. ], _a[detachedFromDom()] = [
  30400. 'alloy.base.behaviour',
  30401. 'dialog-events',
  30402. 'scroll-lock'
  30403. ], _a), spec.eventOrder)
  30404. });
  30405. };
  30406. var renderClose = function (providersBackstage) {
  30407. return Button.sketch({
  30408. dom: {
  30409. tag: 'button',
  30410. classes: [
  30411. 'tox-button',
  30412. 'tox-button--icon',
  30413. 'tox-button--naked'
  30414. ],
  30415. attributes: {
  30416. 'type': 'button',
  30417. 'aria-label': providersBackstage.translate('Close'),
  30418. 'title': providersBackstage.translate('Close')
  30419. }
  30420. },
  30421. components: [{
  30422. dom: {
  30423. tag: 'div',
  30424. classes: ['tox-icon'],
  30425. innerHtml: get$d('close', providersBackstage.icons)
  30426. }
  30427. }],
  30428. action: function (comp) {
  30429. emit(comp, formCancelEvent);
  30430. }
  30431. });
  30432. };
  30433. var renderTitle = function (spec, id, providersBackstage) {
  30434. var renderComponents = function (data) {
  30435. return [text(providersBackstage.translate(data.title))];
  30436. };
  30437. return {
  30438. dom: {
  30439. tag: 'div',
  30440. classes: ['tox-dialog__title'],
  30441. attributes: __assign({}, id.map(function (x) {
  30442. return { id: x };
  30443. }).getOr({}))
  30444. },
  30445. components: renderComponents(spec),
  30446. behaviours: derive$1([Reflecting.config({
  30447. channel: titleChannel,
  30448. renderComponents: renderComponents
  30449. })])
  30450. };
  30451. };
  30452. var renderDragHandle = function () {
  30453. return { dom: fromHtml$2('<div class="tox-dialog__draghandle"></div>') };
  30454. };
  30455. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  30456. return Container.sketch({
  30457. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  30458. components: [
  30459. renderTitle(spec, Optional.some(titleId), providersBackstage),
  30460. renderDragHandle(),
  30461. renderClose(providersBackstage)
  30462. ],
  30463. containerBehaviours: derive$1([Dragging.config({
  30464. mode: 'mouse',
  30465. blockerClass: 'blocker',
  30466. getTarget: function (handle) {
  30467. return closest$3(handle, '[role="dialog"]').getOrDie();
  30468. },
  30469. snaps: {
  30470. getSnapPoints: function () {
  30471. return [];
  30472. },
  30473. leftAttr: 'data-drag-left',
  30474. topAttr: 'data-drag-top'
  30475. }
  30476. })])
  30477. });
  30478. };
  30479. var renderModalHeader = function (spec, providersBackstage) {
  30480. var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
  30481. var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
  30482. var pClose = ModalDialog.parts.close(renderClose(providersBackstage));
  30483. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  30484. return Container.sketch({
  30485. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  30486. components: components
  30487. });
  30488. };
  30489. var getHeader = function (title, backstage) {
  30490. return renderModalHeader({
  30491. title: backstage.shared.providers.translate(title),
  30492. draggable: backstage.dialog.isDraggableModal()
  30493. }, backstage.shared.providers);
  30494. };
  30495. var getEventExtras = function (lazyDialog, extra) {
  30496. return {
  30497. onClose: function () {
  30498. return extra.closeWindow();
  30499. },
  30500. onBlock: function (blockEvent) {
  30501. ModalDialog.setBusy(lazyDialog(), function (d, bs) {
  30502. return {
  30503. dom: {
  30504. tag: 'div',
  30505. classes: ['tox-dialog__busy-spinner'],
  30506. attributes: { 'aria-label': blockEvent.message },
  30507. styles: {
  30508. left: '0px',
  30509. right: '0px',
  30510. bottom: '0px',
  30511. top: '0px',
  30512. position: 'absolute'
  30513. }
  30514. },
  30515. behaviours: bs,
  30516. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  30517. };
  30518. });
  30519. },
  30520. onUnblock: function () {
  30521. ModalDialog.setIdle(lazyDialog());
  30522. }
  30523. };
  30524. };
  30525. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  30526. var _a;
  30527. var updateState = function (_comp, incoming) {
  30528. return Optional.some(incoming);
  30529. };
  30530. return build$1(renderDialog(__assign(__assign({}, spec), {
  30531. lazySink: backstage.shared.getSink,
  30532. extraBehaviours: __spreadArrays([
  30533. Reflecting.config({
  30534. channel: dialogChannel,
  30535. updateState: updateState,
  30536. initialData: initialData
  30537. }),
  30538. RepresentingConfigs.memory({})
  30539. ], spec.extraBehaviours),
  30540. onEscape: function (comp) {
  30541. emit(comp, formCancelEvent);
  30542. },
  30543. dialogEvents: dialogEvents,
  30544. eventOrder: (_a = {}, _a[receive()] = [
  30545. 'reflecting',
  30546. 'receiving'
  30547. ], _a[attachedToDom()] = [
  30548. 'scroll-lock',
  30549. 'reflecting',
  30550. 'messages',
  30551. 'dialog-events',
  30552. 'alloy.base.behaviour'
  30553. ], _a[detachedFromDom()] = [
  30554. 'alloy.base.behaviour',
  30555. 'dialog-events',
  30556. 'messages',
  30557. 'reflecting',
  30558. 'scroll-lock'
  30559. ], _a)
  30560. })));
  30561. };
  30562. var mapMenuButtons = function (buttons) {
  30563. var mapItems = function (button) {
  30564. var items = map(button.items, function (item) {
  30565. var cell = Cell(false);
  30566. return __assign(__assign({}, item), { storage: cell });
  30567. });
  30568. return __assign(__assign({}, button), { items: items });
  30569. };
  30570. return map(buttons, function (button) {
  30571. if (button.type === 'menu') {
  30572. return mapItems(button);
  30573. }
  30574. return button;
  30575. });
  30576. };
  30577. var extractCellsToObject = function (buttons) {
  30578. return foldl(buttons, function (acc, button) {
  30579. if (button.type === 'menu') {
  30580. var menuButton = button;
  30581. return foldl(menuButton.items, function (innerAcc, item) {
  30582. innerAcc[item.name] = item.storage;
  30583. return innerAcc;
  30584. }, acc);
  30585. }
  30586. return acc;
  30587. }, {});
  30588. };
  30589. var initCommonEvents = function (fireApiEvent, extras) {
  30590. return [
  30591. runWithTarget(focusin(), onFocus$1),
  30592. fireApiEvent(formCloseEvent, function (_api, spec) {
  30593. extras.onClose();
  30594. spec.onClose();
  30595. }),
  30596. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  30597. spec.onCancel(api);
  30598. emit(self, formCloseEvent);
  30599. }),
  30600. run(formUnblockEvent, function (_c, _se) {
  30601. return extras.onUnblock();
  30602. }),
  30603. run(formBlockEvent, function (_c, se) {
  30604. return extras.onBlock(se.event);
  30605. })
  30606. ];
  30607. };
  30608. var initUrlDialog = function (getInstanceApi, extras) {
  30609. var fireApiEvent = function (eventName, f) {
  30610. return run(eventName, function (c, se) {
  30611. withSpec(c, function (spec, _c) {
  30612. f(getInstanceApi(), spec, se.event, c);
  30613. });
  30614. });
  30615. };
  30616. var withSpec = function (c, f) {
  30617. Reflecting.getState(c).get().each(function (currentDialog) {
  30618. f(currentDialog, c);
  30619. });
  30620. };
  30621. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [fireApiEvent(formActionEvent, function (api, spec, event) {
  30622. spec.onAction(api, { name: event.name });
  30623. })]);
  30624. };
  30625. var initDialog = function (getInstanceApi, extras, getSink) {
  30626. var fireApiEvent = function (eventName, f) {
  30627. return run(eventName, function (c, se) {
  30628. withSpec(c, function (spec, _c) {
  30629. f(getInstanceApi(), spec, se.event, c);
  30630. });
  30631. });
  30632. };
  30633. var withSpec = function (c, f) {
  30634. Reflecting.getState(c).get().each(function (currentDialogInit) {
  30635. f(currentDialogInit.internalDialog, c);
  30636. });
  30637. };
  30638. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [
  30639. fireApiEvent(formSubmitEvent, function (api, spec) {
  30640. return spec.onSubmit(api);
  30641. }),
  30642. fireApiEvent(formChangeEvent, function (api, spec, event) {
  30643. spec.onChange(api, { name: event.name });
  30644. }),
  30645. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  30646. var focusIn = function () {
  30647. return Keying.focusIn(component);
  30648. };
  30649. var isDisabled = function (focused) {
  30650. return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
  30651. return val === 'true';
  30652. });
  30653. };
  30654. var rootNode = getRootNode(component.element);
  30655. var current = active(rootNode);
  30656. spec.onAction(api, {
  30657. name: event.name,
  30658. value: event.value
  30659. });
  30660. active(rootNode).fold(focusIn, function (focused) {
  30661. if (isDisabled(focused)) {
  30662. focusIn();
  30663. } else if (current.exists(function (cur) {
  30664. return contains$2(focused, cur) && isDisabled(cur);
  30665. })) {
  30666. focusIn();
  30667. } else {
  30668. getSink().toOptional().filter(function (sink) {
  30669. return !contains$2(sink.element, focused);
  30670. }).each(focusIn);
  30671. }
  30672. });
  30673. }),
  30674. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  30675. spec.onTabChange(api, {
  30676. newTabName: event.name,
  30677. oldTabName: event.oldName
  30678. });
  30679. }),
  30680. runOnDetached(function (component) {
  30681. var api = getInstanceApi();
  30682. Representing.setValue(component, api.getData());
  30683. })
  30684. ]);
  30685. };
  30686. var SilverDialogEvents = {
  30687. initUrlDialog: initUrlDialog,
  30688. initDialog: initDialog
  30689. };
  30690. var makeButton = function (button, backstage) {
  30691. return renderFooterButton(button, button.type, backstage);
  30692. };
  30693. var lookup$2 = function (compInSystem, footerButtons, buttonName) {
  30694. return find(footerButtons, function (button) {
  30695. return button.name === buttonName;
  30696. }).bind(function (memButton) {
  30697. return memButton.memento.getOpt(compInSystem);
  30698. });
  30699. };
  30700. var renderComponents = function (_data, state) {
  30701. var footerButtons = state.map(function (s) {
  30702. return s.footerButtons;
  30703. }).getOr([]);
  30704. var buttonGroups = partition(footerButtons, function (button) {
  30705. return button.align === 'start';
  30706. });
  30707. var makeGroup = function (edge, buttons) {
  30708. return Container.sketch({
  30709. dom: {
  30710. tag: 'div',
  30711. classes: ['tox-dialog__footer-' + edge]
  30712. },
  30713. components: map(buttons, function (button) {
  30714. return button.memento.asSpec();
  30715. })
  30716. });
  30717. };
  30718. var startButtons = makeGroup('start', buttonGroups.pass);
  30719. var endButtons = makeGroup('end', buttonGroups.fail);
  30720. return [
  30721. startButtons,
  30722. endButtons
  30723. ];
  30724. };
  30725. var renderFooter = function (initSpec, backstage) {
  30726. var updateState = function (_comp, data) {
  30727. var footerButtons = map(data.buttons, function (button) {
  30728. var memButton = record(makeButton(button, backstage));
  30729. return {
  30730. name: button.name,
  30731. align: button.align,
  30732. memento: memButton
  30733. };
  30734. });
  30735. var lookupByName = function (compInSystem, buttonName) {
  30736. return lookup$2(compInSystem, footerButtons, buttonName);
  30737. };
  30738. return Optional.some({
  30739. lookupByName: lookupByName,
  30740. footerButtons: footerButtons
  30741. });
  30742. };
  30743. return {
  30744. dom: fromHtml$2('<div class="tox-dialog__footer"></div>'),
  30745. components: [],
  30746. behaviours: derive$1([Reflecting.config({
  30747. channel: footerChannel,
  30748. initialData: initSpec,
  30749. updateState: updateState,
  30750. renderComponents: renderComponents
  30751. })])
  30752. };
  30753. };
  30754. var renderInlineFooter = function (initSpec, backstage) {
  30755. return renderFooter(initSpec, backstage);
  30756. };
  30757. var renderModalFooter = function (initSpec, backstage) {
  30758. return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
  30759. };
  30760. var getCompByName = function (access, name) {
  30761. var root = access.getRoot();
  30762. if (root.getSystem().isConnected()) {
  30763. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  30764. return Form.getField(form_1, name).fold(function () {
  30765. var footer = access.getFooter();
  30766. var footerState = Reflecting.getState(footer);
  30767. return footerState.get().bind(function (f) {
  30768. return f.lookupByName(form_1, name);
  30769. });
  30770. }, function (comp) {
  30771. return Optional.some(comp);
  30772. });
  30773. } else {
  30774. return Optional.none();
  30775. }
  30776. };
  30777. var validateData = function (access, data) {
  30778. var root = access.getRoot();
  30779. return Reflecting.getState(root).get().map(function (dialogState) {
  30780. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  30781. }).getOr(data);
  30782. };
  30783. var getDialogApi = function (access, doRedial, menuItemStates) {
  30784. var withRoot = function (f) {
  30785. var root = access.getRoot();
  30786. if (root.getSystem().isConnected()) {
  30787. f(root);
  30788. }
  30789. };
  30790. var getData = function () {
  30791. var root = access.getRoot();
  30792. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  30793. var representedValues = Representing.getValue(valueComp);
  30794. var menuItemCurrentState = map$2(menuItemStates, function (cell) {
  30795. return cell.get();
  30796. });
  30797. return __assign(__assign({}, representedValues), menuItemCurrentState);
  30798. };
  30799. var setData = function (newData) {
  30800. withRoot(function (_) {
  30801. var prevData = instanceApi.getData();
  30802. var mergedData = __assign(__assign({}, prevData), newData);
  30803. var newInternalData = validateData(access, mergedData);
  30804. var form = access.getFormWrapper();
  30805. Representing.setValue(form, newInternalData);
  30806. each$1(menuItemStates, function (v, k) {
  30807. if (has(mergedData, k)) {
  30808. v.set(mergedData[k]);
  30809. }
  30810. });
  30811. });
  30812. };
  30813. var disable = function (name) {
  30814. getCompByName(access, name).each(Disabling.disable);
  30815. };
  30816. var enable = function (name) {
  30817. getCompByName(access, name).each(Disabling.enable);
  30818. };
  30819. var focus = function (name) {
  30820. getCompByName(access, name).each(Focusing.focus);
  30821. };
  30822. var block = function (message) {
  30823. if (!isString(message)) {
  30824. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  30825. }
  30826. withRoot(function (root) {
  30827. emitWith(root, formBlockEvent, { message: message });
  30828. });
  30829. };
  30830. var unblock = function () {
  30831. withRoot(function (root) {
  30832. emit(root, formUnblockEvent);
  30833. });
  30834. };
  30835. var showTab = function (name) {
  30836. withRoot(function (_) {
  30837. var body = access.getBody();
  30838. var bodyState = Reflecting.getState(body);
  30839. if (bodyState.get().exists(function (b) {
  30840. return b.isTabPanel();
  30841. })) {
  30842. Composing.getCurrent(body).each(function (tabSection) {
  30843. TabSection.showTab(tabSection, name);
  30844. });
  30845. }
  30846. });
  30847. };
  30848. var redial = function (d) {
  30849. withRoot(function (root) {
  30850. var dialogInit = doRedial(d);
  30851. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  30852. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  30853. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  30854. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  30855. instanceApi.setData(dialogInit.initialData);
  30856. });
  30857. };
  30858. var close = function () {
  30859. withRoot(function (root) {
  30860. emit(root, formCloseEvent);
  30861. });
  30862. };
  30863. var instanceApi = {
  30864. getData: getData,
  30865. setData: setData,
  30866. disable: disable,
  30867. enable: enable,
  30868. focus: focus,
  30869. block: block,
  30870. unblock: unblock,
  30871. showTab: showTab,
  30872. redial: redial,
  30873. close: close
  30874. };
  30875. return instanceApi;
  30876. };
  30877. var renderDialog$1 = function (dialogInit, extra, backstage) {
  30878. var header = getHeader(dialogInit.internalDialog.title, backstage);
  30879. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  30880. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30881. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30882. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  30883. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30884. return instanceApi;
  30885. }, getEventExtras(function () {
  30886. return dialog;
  30887. }, extra), backstage.shared.getSink);
  30888. var dialogSize = dialogInit.internalDialog.size !== 'normal' ? dialogInit.internalDialog.size === 'large' ? ['tox-dialog--width-lg'] : ['tox-dialog--width-md'] : [];
  30889. var spec = {
  30890. header: header,
  30891. body: body,
  30892. footer: Optional.some(footer),
  30893. extraClasses: dialogSize,
  30894. extraBehaviours: [],
  30895. extraStyles: {}
  30896. };
  30897. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  30898. var modalAccess = function () {
  30899. var getForm = function () {
  30900. var outerForm = ModalDialog.getBody(dialog);
  30901. return Composing.getCurrent(outerForm).getOr(outerForm);
  30902. };
  30903. return {
  30904. getRoot: function () {
  30905. return dialog;
  30906. },
  30907. getBody: function () {
  30908. return ModalDialog.getBody(dialog);
  30909. },
  30910. getFooter: function () {
  30911. return ModalDialog.getFooter(dialog);
  30912. },
  30913. getFormWrapper: getForm
  30914. };
  30915. }();
  30916. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  30917. return {
  30918. dialog: dialog,
  30919. instanceApi: instanceApi
  30920. };
  30921. };
  30922. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  30923. var _a, _b;
  30924. var dialogLabelId = generate$1('dialog-label');
  30925. var dialogContentId = generate$1('dialog-content');
  30926. var updateState = function (_comp, incoming) {
  30927. return Optional.some(incoming);
  30928. };
  30929. var memHeader = record(renderInlineHeader({
  30930. title: dialogInit.internalDialog.title,
  30931. draggable: true
  30932. }, dialogLabelId, backstage.shared.providers));
  30933. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  30934. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30935. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30936. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  30937. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30938. return instanceApi;
  30939. }, {
  30940. onBlock: function () {
  30941. },
  30942. onUnblock: function () {
  30943. },
  30944. onClose: function () {
  30945. return extra.closeWindow();
  30946. }
  30947. }, backstage.shared.getSink);
  30948. var dialog = build$1({
  30949. dom: {
  30950. tag: 'div',
  30951. classes: [
  30952. 'tox-dialog',
  30953. 'tox-dialog-inline'
  30954. ],
  30955. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = '' + dialogContentId, _a)
  30956. },
  30957. eventOrder: (_b = {}, _b[receive()] = [
  30958. Reflecting.name(),
  30959. Receiving.name()
  30960. ], _b[execute()] = ['execute-on-form'], _b[attachedToDom()] = [
  30961. 'reflecting',
  30962. 'execute-on-form'
  30963. ], _b),
  30964. behaviours: derive$1([
  30965. Keying.config({
  30966. mode: 'cyclic',
  30967. onEscape: function (c) {
  30968. emit(c, formCloseEvent);
  30969. return Optional.some(true);
  30970. },
  30971. useTabstopAt: function (elem) {
  30972. return !isPseudoStop(elem) && (name(elem) !== 'button' || get$2(elem, 'disabled') !== 'disabled');
  30973. }
  30974. }),
  30975. Reflecting.config({
  30976. channel: dialogChannel,
  30977. updateState: updateState,
  30978. initialData: dialogInit
  30979. }),
  30980. Focusing.config({}),
  30981. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  30982. Keying.focusIn(comp);
  30983. })])),
  30984. RepresentingConfigs.memory({})
  30985. ]),
  30986. components: [
  30987. memHeader.asSpec(),
  30988. memBody.asSpec(),
  30989. memFooter.asSpec()
  30990. ]
  30991. });
  30992. var instanceApi = getDialogApi({
  30993. getRoot: function () {
  30994. return dialog;
  30995. },
  30996. getFooter: function () {
  30997. return memFooter.get(dialog);
  30998. },
  30999. getBody: function () {
  31000. return memBody.get(dialog);
  31001. },
  31002. getFormWrapper: function () {
  31003. var body = memBody.get(dialog);
  31004. return Composing.getCurrent(body).getOr(body);
  31005. }
  31006. }, extra.redial, objOfCells);
  31007. return {
  31008. dialog: dialog,
  31009. instanceApi: instanceApi
  31010. };
  31011. };
  31012. var global$g = tinymce.util.Tools.resolve('tinymce.util.URI');
  31013. var getUrlDialogApi = function (root) {
  31014. var withRoot = function (f) {
  31015. if (root.getSystem().isConnected()) {
  31016. f(root);
  31017. }
  31018. };
  31019. var block = function (message) {
  31020. if (!isString(message)) {
  31021. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  31022. }
  31023. withRoot(function (root) {
  31024. emitWith(root, formBlockEvent, { message: message });
  31025. });
  31026. };
  31027. var unblock = function () {
  31028. withRoot(function (root) {
  31029. emit(root, formUnblockEvent);
  31030. });
  31031. };
  31032. var close = function () {
  31033. withRoot(function (root) {
  31034. emit(root, formCloseEvent);
  31035. });
  31036. };
  31037. var sendMessage = function (data) {
  31038. withRoot(function (root) {
  31039. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  31040. });
  31041. };
  31042. return {
  31043. block: block,
  31044. unblock: unblock,
  31045. close: close,
  31046. sendMessage: sendMessage
  31047. };
  31048. };
  31049. var SUPPORTED_MESSAGE_ACTIONS = [
  31050. 'insertContent',
  31051. 'setContent',
  31052. 'execCommand',
  31053. 'close',
  31054. 'block',
  31055. 'unblock'
  31056. ];
  31057. var isSupportedMessage = function (data) {
  31058. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  31059. };
  31060. var isCustomMessage = function (data) {
  31061. return !isSupportedMessage(data) && isObject(data) && has(data, 'mceAction');
  31062. };
  31063. var handleMessage = function (editor, api, data) {
  31064. switch (data.mceAction) {
  31065. case 'insertContent':
  31066. editor.insertContent(data.content);
  31067. break;
  31068. case 'setContent':
  31069. editor.setContent(data.content);
  31070. break;
  31071. case 'execCommand':
  31072. var ui = isBoolean(data.ui) ? data.ui : false;
  31073. editor.execCommand(data.cmd, ui, data.value);
  31074. break;
  31075. case 'close':
  31076. api.close();
  31077. break;
  31078. case 'block':
  31079. api.block(data.message);
  31080. break;
  31081. case 'unblock':
  31082. api.unblock();
  31083. break;
  31084. }
  31085. };
  31086. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  31087. var _a;
  31088. var header = getHeader(internalDialog.title, backstage);
  31089. var body = renderIframeBody(internalDialog);
  31090. var footer = internalDialog.buttons.bind(function (buttons) {
  31091. if (buttons.length === 0) {
  31092. return Optional.none();
  31093. } else {
  31094. return Optional.some(renderModalFooter({ buttons: buttons }, backstage));
  31095. }
  31096. });
  31097. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  31098. return instanceApi;
  31099. }, getEventExtras(function () {
  31100. return dialog;
  31101. }, extra));
  31102. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  31103. return {};
  31104. }, function (height) {
  31105. return {
  31106. 'height': height + 'px',
  31107. 'max-height': height + 'px'
  31108. };
  31109. })), internalDialog.width.fold(function () {
  31110. return {};
  31111. }, function (width) {
  31112. return {
  31113. 'width': width + 'px',
  31114. 'max-width': width + 'px'
  31115. };
  31116. }));
  31117. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  31118. var iframeUri = new global$g(internalDialog.url, { base_uri: new global$g(window.location.href) });
  31119. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  31120. var messageHandlerUnbinder = Cell(Optional.none());
  31121. var extraBehaviours = [
  31122. config('messages', [
  31123. runOnAttached(function () {
  31124. var unbind = bind$3(SugarElement.fromDom(window), 'message', function (e) {
  31125. if (iframeUri.isSameOrigin(new global$g(e.raw.origin))) {
  31126. var data = e.raw.data;
  31127. if (isSupportedMessage(data)) {
  31128. handleMessage(editor, instanceApi, data);
  31129. } else if (isCustomMessage(data)) {
  31130. internalDialog.onMessage(instanceApi, data);
  31131. }
  31132. }
  31133. });
  31134. messageHandlerUnbinder.set(Optional.some(unbind));
  31135. }),
  31136. runOnDetached(function () {
  31137. messageHandlerUnbinder.get().each(function (unbinder) {
  31138. return unbinder.unbind();
  31139. });
  31140. })
  31141. ]),
  31142. Receiving.config({
  31143. channels: (_a = {}, _a[bodySendMessageChannel] = {
  31144. onReceive: function (comp, data) {
  31145. descendant$1(comp.element, 'iframe').each(function (iframeEle) {
  31146. var iframeWin = iframeEle.dom.contentWindow;
  31147. iframeWin.postMessage(data, iframeDomain);
  31148. });
  31149. }
  31150. }, _a)
  31151. })
  31152. ];
  31153. var spec = {
  31154. header: header,
  31155. body: body,
  31156. footer: footer,
  31157. extraClasses: classes,
  31158. extraBehaviours: extraBehaviours,
  31159. extraStyles: styles
  31160. };
  31161. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  31162. var instanceApi = getUrlDialogApi(dialog);
  31163. return {
  31164. dialog: dialog,
  31165. instanceApi: instanceApi
  31166. };
  31167. };
  31168. var setup$c = function (extras) {
  31169. var sharedBackstage = extras.backstage.shared;
  31170. var open = function (message, callback) {
  31171. var closeDialog = function () {
  31172. ModalDialog.hide(alertDialog);
  31173. callback();
  31174. };
  31175. var memFooterClose = record(renderFooterButton({
  31176. name: 'close-alert',
  31177. text: 'OK',
  31178. primary: true,
  31179. align: 'end',
  31180. disabled: false,
  31181. icon: Optional.none()
  31182. }, 'cancel', extras.backstage));
  31183. var titleSpec = pUntitled();
  31184. var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  31185. var alertDialog = build$1(renderDialog({
  31186. lazySink: function () {
  31187. return sharedBackstage.getSink();
  31188. },
  31189. header: hiddenHeader(titleSpec, closeSpec),
  31190. body: pBodyMessage(message, sharedBackstage.providers),
  31191. footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  31192. onEscape: closeDialog,
  31193. extraClasses: ['tox-alert-dialog'],
  31194. extraBehaviours: [],
  31195. extraStyles: {},
  31196. dialogEvents: [run(formCancelEvent, closeDialog)],
  31197. eventOrder: {}
  31198. }));
  31199. ModalDialog.show(alertDialog);
  31200. var footerCloseButton = memFooterClose.get(alertDialog);
  31201. Focusing.focus(footerCloseButton);
  31202. };
  31203. return { open: open };
  31204. };
  31205. var setup$d = function (extras) {
  31206. var sharedBackstage = extras.backstage.shared;
  31207. var open = function (message, callback) {
  31208. var closeDialog = function (state) {
  31209. ModalDialog.hide(confirmDialog);
  31210. callback(state);
  31211. };
  31212. var memFooterYes = record(renderFooterButton({
  31213. name: 'yes',
  31214. text: 'Yes',
  31215. primary: true,
  31216. align: 'end',
  31217. disabled: false,
  31218. icon: Optional.none()
  31219. }, 'submit', extras.backstage));
  31220. var footerNo = renderFooterButton({
  31221. name: 'no',
  31222. text: 'No',
  31223. primary: false,
  31224. align: 'end',
  31225. disabled: false,
  31226. icon: Optional.none()
  31227. }, 'cancel', extras.backstage);
  31228. var titleSpec = pUntitled();
  31229. var closeSpec = pClose(function () {
  31230. return closeDialog(false);
  31231. }, sharedBackstage.providers);
  31232. var confirmDialog = build$1(renderDialog({
  31233. lazySink: function () {
  31234. return sharedBackstage.getSink();
  31235. },
  31236. header: hiddenHeader(titleSpec, closeSpec),
  31237. body: pBodyMessage(message, sharedBackstage.providers),
  31238. footer: Optional.some(pFooter(pFooterGroup([], [
  31239. footerNo,
  31240. memFooterYes.asSpec()
  31241. ]))),
  31242. onEscape: function () {
  31243. return closeDialog(false);
  31244. },
  31245. extraClasses: ['tox-confirm-dialog'],
  31246. extraBehaviours: [],
  31247. extraStyles: {},
  31248. dialogEvents: [
  31249. run(formCancelEvent, function () {
  31250. return closeDialog(false);
  31251. }),
  31252. run(formSubmitEvent, function () {
  31253. return closeDialog(true);
  31254. })
  31255. ],
  31256. eventOrder: {}
  31257. }));
  31258. ModalDialog.show(confirmDialog);
  31259. var footerYesButton = memFooterYes.get(confirmDialog);
  31260. Focusing.focus(footerYesButton);
  31261. };
  31262. return { open: open };
  31263. };
  31264. var validateData$1 = function (data, validator) {
  31265. return getOrDie(asRaw('data', validator, data));
  31266. };
  31267. var isAlertOrConfirmDialog = function (target) {
  31268. return closest$4(target, '.tox-alert-dialog') || closest$4(target, '.tox-confirm-dialog');
  31269. };
  31270. var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  31271. if (isStickyToolbar && isToolbarLocationTop) {
  31272. return [];
  31273. } else {
  31274. return [Docking.config({
  31275. contextual: {
  31276. lazyContext: function () {
  31277. return Optional.some(box(SugarElement.fromDom(editor.getContentAreaContainer())));
  31278. },
  31279. fadeInClass: 'tox-dialog-dock-fadein',
  31280. fadeOutClass: 'tox-dialog-dock-fadeout',
  31281. transitionClass: 'tox-dialog-dock-transition'
  31282. },
  31283. modes: ['top']
  31284. })];
  31285. }
  31286. };
  31287. var setup$e = function (extras) {
  31288. var backstage = extras.backstage;
  31289. var editor = extras.editor;
  31290. var isStickyToolbar$1 = isStickyToolbar(editor);
  31291. var alertDialog = setup$c(extras);
  31292. var confirmDialog = setup$d(extras);
  31293. var open = function (config, params, closeWindow) {
  31294. if (params !== undefined && params.inline === 'toolbar') {
  31295. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  31296. } else if (params !== undefined && params.inline === 'cursor') {
  31297. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  31298. } else {
  31299. return openModalDialog(config, closeWindow);
  31300. }
  31301. };
  31302. var openUrl = function (config, closeWindow) {
  31303. return openModalUrlDialog(config, closeWindow);
  31304. };
  31305. var openModalUrlDialog = function (config, closeWindow) {
  31306. var factory = function (contents) {
  31307. var dialog = renderUrlDialog(contents, {
  31308. closeWindow: function () {
  31309. ModalDialog.hide(dialog.dialog);
  31310. closeWindow(dialog.instanceApi);
  31311. }
  31312. }, editor, backstage);
  31313. ModalDialog.show(dialog.dialog);
  31314. return dialog.instanceApi;
  31315. };
  31316. return DialogManager.openUrl(factory, config);
  31317. };
  31318. var openModalDialog = function (config, closeWindow) {
  31319. var factory = function (contents, internalInitialData, dataValidator) {
  31320. var initialData = internalInitialData;
  31321. var dialogInit = {
  31322. dataValidator: dataValidator,
  31323. initialData: initialData,
  31324. internalDialog: contents
  31325. };
  31326. var dialog = renderDialog$1(dialogInit, {
  31327. redial: DialogManager.redial,
  31328. closeWindow: function () {
  31329. ModalDialog.hide(dialog.dialog);
  31330. closeWindow(dialog.instanceApi);
  31331. }
  31332. }, backstage);
  31333. ModalDialog.show(dialog.dialog);
  31334. dialog.instanceApi.setData(initialData);
  31335. return dialog.instanceApi;
  31336. };
  31337. return DialogManager.open(factory, config);
  31338. };
  31339. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  31340. var factory = function (contents, internalInitialData, dataValidator) {
  31341. var initialData = validateData$1(internalInitialData, dataValidator);
  31342. var inlineDialog = value$3();
  31343. var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  31344. var dialogInit = {
  31345. dataValidator: dataValidator,
  31346. initialData: initialData,
  31347. internalDialog: contents
  31348. };
  31349. var refreshDocking = function () {
  31350. return inlineDialog.on(function (dialog) {
  31351. InlineView.reposition(dialog);
  31352. Docking.refresh(dialog);
  31353. });
  31354. };
  31355. var dialogUi = renderInlineDialog(dialogInit, {
  31356. redial: DialogManager.redial,
  31357. closeWindow: function () {
  31358. inlineDialog.on(InlineView.hide);
  31359. editor.off('ResizeEditor', refreshDocking);
  31360. inlineDialog.clear();
  31361. closeWindow(dialogUi.instanceApi);
  31362. }
  31363. }, backstage, ariaAttrs);
  31364. var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  31365. lazySink: backstage.shared.getSink,
  31366. dom: {
  31367. tag: 'div',
  31368. classes: []
  31369. },
  31370. fireDismissalEventInstead: {}
  31371. }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
  31372. inlineBehaviours: derive$1(__spreadArrays([config('window-manager-inline-events', [run(dismissRequested(), function (_comp, _se) {
  31373. emit(dialogUi.dialog, formCancelEvent);
  31374. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop))),
  31375. isExtraPart: function (_comp, target) {
  31376. return isAlertOrConfirmDialog(target);
  31377. }
  31378. })));
  31379. inlineDialog.set(inlineDialogComp);
  31380. InlineView.showWithin(inlineDialogComp, anchor, premade$1(dialogUi.dialog), Optional.some(body()));
  31381. if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  31382. Docking.refresh(inlineDialogComp);
  31383. editor.on('ResizeEditor', refreshDocking);
  31384. }
  31385. dialogUi.instanceApi.setData(initialData);
  31386. Keying.focusIn(dialogUi.dialog);
  31387. return dialogUi.instanceApi;
  31388. };
  31389. return DialogManager.open(factory, config$1);
  31390. };
  31391. var confirm = function (message, callback) {
  31392. confirmDialog.open(message, function (state) {
  31393. callback(state);
  31394. });
  31395. };
  31396. var alert = function (message, callback) {
  31397. alertDialog.open(message, function () {
  31398. callback();
  31399. });
  31400. };
  31401. var close = function (instanceApi) {
  31402. instanceApi.close();
  31403. };
  31404. return {
  31405. open: open,
  31406. openUrl: openUrl,
  31407. alert: alert,
  31408. close: close,
  31409. confirm: confirm
  31410. };
  31411. };
  31412. function Theme () {
  31413. global$1.add('silver', function (editor) {
  31414. var _a = setup$b(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  31415. Autocompleter.register(editor, backstage.shared);
  31416. var windowMgr = setup$e({
  31417. editor: editor,
  31418. backstage: backstage
  31419. });
  31420. return {
  31421. renderUI: renderUI,
  31422. getWindowManagerImpl: constant(windowMgr),
  31423. getNotificationManagerImpl: function () {
  31424. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  31425. },
  31426. ui: getUi()
  31427. };
  31428. });
  31429. }
  31430. Theme();
  31431. }());