theme.js 906 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108
  1. /**
  2. * TinyMCE version 6.0.3 (2022-05-25)
  3. */
  4. (function () {
  5. 'use strict';
  6. const getPrototypeOf = Object.getPrototypeOf;
  7. const hasProto = (v, constructor, predicate) => {
  8. var _a;
  9. if (predicate(v, constructor.prototype)) {
  10. return true;
  11. } else {
  12. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  13. }
  14. };
  15. const typeOf = x => {
  16. const t = typeof x;
  17. if (x === null) {
  18. return 'null';
  19. } else if (t === 'object' && Array.isArray(x)) {
  20. return 'array';
  21. } else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  22. return 'string';
  23. } else {
  24. return t;
  25. }
  26. };
  27. const isType$1 = type => value => typeOf(value) === type;
  28. const isSimpleType = type => value => typeof value === type;
  29. const eq$1 = t => a => t === a;
  30. const is$2 = (value, constructor) => isObject(value) && hasProto(value, constructor, (o, proto) => getPrototypeOf(o) === proto);
  31. const isString = isType$1('string');
  32. const isObject = isType$1('object');
  33. const isPlainObject = value => is$2(value, Object);
  34. const isArray = isType$1('array');
  35. const isNull = eq$1(null);
  36. const isBoolean = isSimpleType('boolean');
  37. const isUndefined = eq$1(undefined);
  38. const isNullable = a => a === null || a === undefined;
  39. const isNonNullable = a => !isNullable(a);
  40. const isFunction = isSimpleType('function');
  41. const isNumber = isSimpleType('number');
  42. const isArrayOf = (value, pred) => {
  43. if (isArray(value)) {
  44. for (let i = 0, len = value.length; i < len; ++i) {
  45. if (!pred(value[i])) {
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. return false;
  52. };
  53. const noop = () => {
  54. };
  55. const noarg = f => () => f();
  56. const compose = (fa, fb) => {
  57. return (...args) => {
  58. return fa(fb.apply(null, args));
  59. };
  60. };
  61. const compose1 = (fbc, fab) => a => fbc(fab(a));
  62. const constant$1 = value => {
  63. return () => {
  64. return value;
  65. };
  66. };
  67. const identity = x => {
  68. return x;
  69. };
  70. const tripleEquals = (a, b) => {
  71. return a === b;
  72. };
  73. function curry(fn, ...initialArgs) {
  74. return (...restArgs) => {
  75. const all = initialArgs.concat(restArgs);
  76. return fn.apply(null, all);
  77. };
  78. }
  79. const not = f => t => !f(t);
  80. const die = msg => {
  81. return () => {
  82. throw new Error(msg);
  83. };
  84. };
  85. const apply = f => {
  86. return f();
  87. };
  88. const never = constant$1(false);
  89. const always = constant$1(true);
  90. var global$a = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  91. class Optional {
  92. constructor(tag, value) {
  93. this.tag = tag;
  94. this.value = value;
  95. }
  96. static some(value) {
  97. return new Optional(true, value);
  98. }
  99. static none() {
  100. return Optional.singletonNone;
  101. }
  102. fold(onNone, onSome) {
  103. if (this.tag) {
  104. return onSome(this.value);
  105. } else {
  106. return onNone();
  107. }
  108. }
  109. isSome() {
  110. return this.tag;
  111. }
  112. isNone() {
  113. return !this.tag;
  114. }
  115. map(mapper) {
  116. if (this.tag) {
  117. return Optional.some(mapper(this.value));
  118. } else {
  119. return Optional.none();
  120. }
  121. }
  122. bind(binder) {
  123. if (this.tag) {
  124. return binder(this.value);
  125. } else {
  126. return Optional.none();
  127. }
  128. }
  129. exists(predicate) {
  130. return this.tag && predicate(this.value);
  131. }
  132. forall(predicate) {
  133. return !this.tag || predicate(this.value);
  134. }
  135. filter(predicate) {
  136. if (!this.tag || predicate(this.value)) {
  137. return this;
  138. } else {
  139. return Optional.none();
  140. }
  141. }
  142. getOr(replacement) {
  143. return this.tag ? this.value : replacement;
  144. }
  145. or(replacement) {
  146. return this.tag ? this : replacement;
  147. }
  148. getOrThunk(thunk) {
  149. return this.tag ? this.value : thunk();
  150. }
  151. orThunk(thunk) {
  152. return this.tag ? this : thunk();
  153. }
  154. getOrDie(message) {
  155. if (!this.tag) {
  156. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  157. } else {
  158. return this.value;
  159. }
  160. }
  161. static from(value) {
  162. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  163. }
  164. getOrNull() {
  165. return this.tag ? this.value : null;
  166. }
  167. getOrUndefined() {
  168. return this.value;
  169. }
  170. each(worker) {
  171. if (this.tag) {
  172. worker(this.value);
  173. }
  174. }
  175. toArray() {
  176. return this.tag ? [this.value] : [];
  177. }
  178. toString() {
  179. return this.tag ? `some(${ this.value })` : 'none()';
  180. }
  181. }
  182. Optional.singletonNone = new Optional(false);
  183. const nativeSlice = Array.prototype.slice;
  184. const nativeIndexOf = Array.prototype.indexOf;
  185. const nativePush = Array.prototype.push;
  186. const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
  187. const indexOf = (xs, x) => {
  188. const r = rawIndexOf(xs, x);
  189. return r === -1 ? Optional.none() : Optional.some(r);
  190. };
  191. const contains$2 = (xs, x) => rawIndexOf(xs, x) > -1;
  192. const exists = (xs, pred) => {
  193. for (let i = 0, len = xs.length; i < len; i++) {
  194. const x = xs[i];
  195. if (pred(x, i)) {
  196. return true;
  197. }
  198. }
  199. return false;
  200. };
  201. const range$2 = (num, f) => {
  202. const r = [];
  203. for (let i = 0; i < num; i++) {
  204. r.push(f(i));
  205. }
  206. return r;
  207. };
  208. const chunk$1 = (array, size) => {
  209. const r = [];
  210. for (let i = 0; i < array.length; i += size) {
  211. const s = nativeSlice.call(array, i, i + size);
  212. r.push(s);
  213. }
  214. return r;
  215. };
  216. const map$2 = (xs, f) => {
  217. const len = xs.length;
  218. const r = new Array(len);
  219. for (let i = 0; i < len; i++) {
  220. const x = xs[i];
  221. r[i] = f(x, i);
  222. }
  223. return r;
  224. };
  225. const each$1 = (xs, f) => {
  226. for (let i = 0, len = xs.length; i < len; i++) {
  227. const x = xs[i];
  228. f(x, i);
  229. }
  230. };
  231. const eachr = (xs, f) => {
  232. for (let i = xs.length - 1; i >= 0; i--) {
  233. const x = xs[i];
  234. f(x, i);
  235. }
  236. };
  237. const partition$3 = (xs, pred) => {
  238. const pass = [];
  239. const fail = [];
  240. for (let i = 0, len = xs.length; i < len; i++) {
  241. const x = xs[i];
  242. const arr = pred(x, i) ? pass : fail;
  243. arr.push(x);
  244. }
  245. return {
  246. pass,
  247. fail
  248. };
  249. };
  250. const filter$2 = (xs, pred) => {
  251. const r = [];
  252. for (let i = 0, len = xs.length; i < len; i++) {
  253. const x = xs[i];
  254. if (pred(x, i)) {
  255. r.push(x);
  256. }
  257. }
  258. return r;
  259. };
  260. const foldr = (xs, f, acc) => {
  261. eachr(xs, (x, i) => {
  262. acc = f(acc, x, i);
  263. });
  264. return acc;
  265. };
  266. const foldl = (xs, f, acc) => {
  267. each$1(xs, (x, i) => {
  268. acc = f(acc, x, i);
  269. });
  270. return acc;
  271. };
  272. const findUntil = (xs, pred, until) => {
  273. for (let i = 0, len = xs.length; i < len; i++) {
  274. const x = xs[i];
  275. if (pred(x, i)) {
  276. return Optional.some(x);
  277. } else if (until(x, i)) {
  278. break;
  279. }
  280. }
  281. return Optional.none();
  282. };
  283. const find$5 = (xs, pred) => {
  284. return findUntil(xs, pred, never);
  285. };
  286. const findIndex$1 = (xs, pred) => {
  287. for (let i = 0, len = xs.length; i < len; i++) {
  288. const x = xs[i];
  289. if (pred(x, i)) {
  290. return Optional.some(i);
  291. }
  292. }
  293. return Optional.none();
  294. };
  295. const flatten = xs => {
  296. const r = [];
  297. for (let i = 0, len = xs.length; i < len; ++i) {
  298. if (!isArray(xs[i])) {
  299. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  300. }
  301. nativePush.apply(r, xs[i]);
  302. }
  303. return r;
  304. };
  305. const bind$3 = (xs, f) => flatten(map$2(xs, f));
  306. const forall = (xs, pred) => {
  307. for (let i = 0, len = xs.length; i < len; ++i) {
  308. const x = xs[i];
  309. if (pred(x, i) !== true) {
  310. return false;
  311. }
  312. }
  313. return true;
  314. };
  315. const reverse = xs => {
  316. const r = nativeSlice.call(xs, 0);
  317. r.reverse();
  318. return r;
  319. };
  320. const difference = (a1, a2) => filter$2(a1, x => !contains$2(a2, x));
  321. const mapToObject = (xs, f) => {
  322. const r = {};
  323. for (let i = 0, len = xs.length; i < len; i++) {
  324. const x = xs[i];
  325. r[String(x)] = f(x, i);
  326. }
  327. return r;
  328. };
  329. const pure$2 = x => [x];
  330. const sort = (xs, comparator) => {
  331. const copy = nativeSlice.call(xs, 0);
  332. copy.sort(comparator);
  333. return copy;
  334. };
  335. const get$h = (xs, i) => i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  336. const head = xs => get$h(xs, 0);
  337. const last$1 = xs => get$h(xs, xs.length - 1);
  338. const from = isFunction(Array.from) ? Array.from : x => nativeSlice.call(x);
  339. const findMap = (arr, f) => {
  340. for (let i = 0; i < arr.length; i++) {
  341. const r = f(arr[i], i);
  342. if (r.isSome()) {
  343. return r;
  344. }
  345. }
  346. return Optional.none();
  347. };
  348. const keys = Object.keys;
  349. const hasOwnProperty = Object.hasOwnProperty;
  350. const each = (obj, f) => {
  351. const props = keys(obj);
  352. for (let k = 0, len = props.length; k < len; k++) {
  353. const i = props[k];
  354. const x = obj[i];
  355. f(x, i);
  356. }
  357. };
  358. const map$1 = (obj, f) => {
  359. return tupleMap(obj, (x, i) => ({
  360. k: i,
  361. v: f(x, i)
  362. }));
  363. };
  364. const tupleMap = (obj, f) => {
  365. const r = {};
  366. each(obj, (x, i) => {
  367. const tuple = f(x, i);
  368. r[tuple.k] = tuple.v;
  369. });
  370. return r;
  371. };
  372. const objAcc = r => (x, i) => {
  373. r[i] = x;
  374. };
  375. const internalFilter = (obj, pred, onTrue, onFalse) => {
  376. const r = {};
  377. each(obj, (x, i) => {
  378. (pred(x, i) ? onTrue : onFalse)(x, i);
  379. });
  380. return r;
  381. };
  382. const bifilter = (obj, pred) => {
  383. const t = {};
  384. const f = {};
  385. internalFilter(obj, pred, objAcc(t), objAcc(f));
  386. return {
  387. t,
  388. f
  389. };
  390. };
  391. const filter$1 = (obj, pred) => {
  392. const t = {};
  393. internalFilter(obj, pred, objAcc(t), noop);
  394. return t;
  395. };
  396. const mapToArray = (obj, f) => {
  397. const r = [];
  398. each(obj, (value, name) => {
  399. r.push(f(value, name));
  400. });
  401. return r;
  402. };
  403. const find$4 = (obj, pred) => {
  404. const props = keys(obj);
  405. for (let k = 0, len = props.length; k < len; k++) {
  406. const i = props[k];
  407. const x = obj[i];
  408. if (pred(x, i, obj)) {
  409. return Optional.some(x);
  410. }
  411. }
  412. return Optional.none();
  413. };
  414. const values = obj => {
  415. return mapToArray(obj, identity);
  416. };
  417. const get$g = (obj, key) => {
  418. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  419. };
  420. const has$2 = (obj, key) => hasOwnProperty.call(obj, key);
  421. const hasNonNullableKey = (obj, key) => has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  422. const is$1 = (lhs, rhs, comparator = tripleEquals) => lhs.exists(left => comparator(left, rhs));
  423. const equals = (lhs, rhs, comparator = tripleEquals) => lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
  424. const cat = arr => {
  425. const r = [];
  426. const push = x => {
  427. r.push(x);
  428. };
  429. for (let i = 0; i < arr.length; i++) {
  430. arr[i].each(push);
  431. }
  432. return r;
  433. };
  434. const sequence = arr => {
  435. const r = [];
  436. for (let i = 0; i < arr.length; i++) {
  437. const x = arr[i];
  438. if (x.isSome()) {
  439. r.push(x.getOrDie());
  440. } else {
  441. return Optional.none();
  442. }
  443. }
  444. return Optional.some(r);
  445. };
  446. const lift2 = (oa, ob, f) => oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  447. const lift3 = (oa, ob, oc, f) => oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  448. const mapFrom = (a, f) => a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none();
  449. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  450. const addToEnd = (str, suffix) => {
  451. return str + suffix;
  452. };
  453. const removeFromStart = (str, numChars) => {
  454. return str.substring(numChars);
  455. };
  456. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  457. const removeLeading = (str, prefix) => {
  458. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  459. };
  460. const ensureTrailing = (str, suffix) => {
  461. return endsWith(str, suffix) ? str : addToEnd(str, suffix);
  462. };
  463. const contains$1 = (str, substr) => {
  464. return str.indexOf(substr) !== -1;
  465. };
  466. const startsWith = (str, prefix) => {
  467. return checkRange(str, prefix, 0);
  468. };
  469. const endsWith = (str, suffix) => {
  470. return checkRange(str, suffix, str.length - suffix.length);
  471. };
  472. const blank = r => s => s.replace(r, '');
  473. const trim$1 = blank(/^\s+|\s+$/g);
  474. const isNotEmpty = s => s.length > 0;
  475. const isEmpty = s => !isNotEmpty(s);
  476. const isSupported$1 = dom => dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  477. const fromHtml$2 = (html, scope) => {
  478. const doc = scope || document;
  479. const div = doc.createElement('div');
  480. div.innerHTML = html;
  481. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  482. const message = 'HTML does not have a single root node';
  483. console.error(message, html);
  484. throw new Error(message);
  485. }
  486. return fromDom(div.childNodes[0]);
  487. };
  488. const fromTag = (tag, scope) => {
  489. const doc = scope || document;
  490. const node = doc.createElement(tag);
  491. return fromDom(node);
  492. };
  493. const fromText = (text, scope) => {
  494. const doc = scope || document;
  495. const node = doc.createTextNode(text);
  496. return fromDom(node);
  497. };
  498. const fromDom = node => {
  499. if (node === null || node === undefined) {
  500. throw new Error('Node cannot be null or undefined');
  501. }
  502. return { dom: node };
  503. };
  504. const fromPoint = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  505. const SugarElement = {
  506. fromHtml: fromHtml$2,
  507. fromTag,
  508. fromText,
  509. fromDom,
  510. fromPoint
  511. };
  512. typeof window !== 'undefined' ? window : Function('return this;')();
  513. const DOCUMENT = 9;
  514. const DOCUMENT_FRAGMENT = 11;
  515. const ELEMENT = 1;
  516. const TEXT = 3;
  517. const name$3 = element => {
  518. const r = element.dom.nodeName;
  519. return r.toLowerCase();
  520. };
  521. const type$1 = element => element.dom.nodeType;
  522. const isType = t => element => type$1(element) === t;
  523. const isElement$1 = isType(ELEMENT);
  524. const isText = isType(TEXT);
  525. const isDocument = isType(DOCUMENT);
  526. const isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  527. const isTag = tag => e => isElement$1(e) && name$3(e) === tag;
  528. const is = (element, selector) => {
  529. const dom = element.dom;
  530. if (dom.nodeType !== ELEMENT) {
  531. return false;
  532. } else {
  533. const elem = dom;
  534. if (elem.matches !== undefined) {
  535. return elem.matches(selector);
  536. } else if (elem.msMatchesSelector !== undefined) {
  537. return elem.msMatchesSelector(selector);
  538. } else if (elem.webkitMatchesSelector !== undefined) {
  539. return elem.webkitMatchesSelector(selector);
  540. } else if (elem.mozMatchesSelector !== undefined) {
  541. return elem.mozMatchesSelector(selector);
  542. } else {
  543. throw new Error('Browser lacks native selectors');
  544. }
  545. }
  546. };
  547. const bypassSelector = dom => dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  548. const all$3 = (selector, scope) => {
  549. const base = scope === undefined ? document : scope.dom;
  550. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  551. };
  552. const one = (selector, scope) => {
  553. const base = scope === undefined ? document : scope.dom;
  554. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  555. };
  556. const eq = (e1, e2) => e1.dom === e2.dom;
  557. const contains = (e1, e2) => {
  558. const d1 = e1.dom;
  559. const d2 = e2.dom;
  560. return d1 === d2 ? false : d1.contains(d2);
  561. };
  562. const owner$4 = element => SugarElement.fromDom(element.dom.ownerDocument);
  563. const documentOrOwner = dos => isDocument(dos) ? dos : owner$4(dos);
  564. const documentElement = element => SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  565. const defaultView = element => SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  566. const parent = element => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  567. const parentElement = element => Optional.from(element.dom.parentElement).map(SugarElement.fromDom);
  568. const offsetParent = element => Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  569. const nextSibling = element => Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  570. const children = element => map$2(element.dom.childNodes, SugarElement.fromDom);
  571. const child$2 = (element, index) => {
  572. const cs = element.dom.childNodes;
  573. return Optional.from(cs[index]).map(SugarElement.fromDom);
  574. };
  575. const firstChild = element => child$2(element, 0);
  576. const spot = (element, offset) => ({
  577. element,
  578. offset
  579. });
  580. const leaf = (element, offset) => {
  581. const cs = children(element);
  582. return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  583. };
  584. const isShadowRoot = dos => isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  585. const supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  586. const isSupported = constant$1(supported);
  587. const getRootNode = supported ? e => SugarElement.fromDom(e.dom.getRootNode()) : documentOrOwner;
  588. const getContentContainer = dos => isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  589. const isInShadowRoot = e => getShadowRoot(e).isSome();
  590. const getShadowRoot = e => {
  591. const r = getRootNode(e);
  592. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  593. };
  594. const getShadowHost = e => SugarElement.fromDom(e.dom.host);
  595. const getOriginalEventTarget = event => {
  596. if (isSupported() && isNonNullable(event.target)) {
  597. const el = SugarElement.fromDom(event.target);
  598. if (isElement$1(el) && isOpenShadowHost(el)) {
  599. if (event.composed && event.composedPath) {
  600. const composedPath = event.composedPath();
  601. if (composedPath) {
  602. return head(composedPath);
  603. }
  604. }
  605. }
  606. }
  607. return Optional.from(event.target);
  608. };
  609. const isOpenShadowHost = element => isNonNullable(element.dom.shadowRoot);
  610. const inBody = element => {
  611. const dom = isText(element) ? element.dom.parentNode : element.dom;
  612. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  613. return false;
  614. }
  615. const doc = dom.ownerDocument;
  616. return getShadowRoot(SugarElement.fromDom(dom)).fold(() => doc.body.contains(dom), compose1(inBody, getShadowHost));
  617. };
  618. const body = () => getBody(SugarElement.fromDom(document));
  619. const getBody = doc => {
  620. const b = doc.dom.body;
  621. if (b === null || b === undefined) {
  622. throw new Error('Body is not available yet');
  623. }
  624. return SugarElement.fromDom(b);
  625. };
  626. const rawSet = (dom, key, value) => {
  627. if (isString(value) || isBoolean(value) || isNumber(value)) {
  628. dom.setAttribute(key, value + '');
  629. } else {
  630. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  631. throw new Error('Attribute value was not simple');
  632. }
  633. };
  634. const set$9 = (element, key, value) => {
  635. rawSet(element.dom, key, value);
  636. };
  637. const setAll$1 = (element, attrs) => {
  638. const dom = element.dom;
  639. each(attrs, (v, k) => {
  640. rawSet(dom, k, v);
  641. });
  642. };
  643. const get$f = (element, key) => {
  644. const v = element.dom.getAttribute(key);
  645. return v === null ? undefined : v;
  646. };
  647. const getOpt = (element, key) => Optional.from(get$f(element, key));
  648. const has$1 = (element, key) => {
  649. const dom = element.dom;
  650. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  651. };
  652. const remove$7 = (element, key) => {
  653. element.dom.removeAttribute(key);
  654. };
  655. const clone$1 = element => foldl(element.dom.attributes, (acc, attr) => {
  656. acc[attr.name] = attr.value;
  657. return acc;
  658. }, {});
  659. const internalSet = (dom, property, value) => {
  660. if (!isString(value)) {
  661. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  662. throw new Error('CSS value must be a string: ' + value);
  663. }
  664. if (isSupported$1(dom)) {
  665. dom.style.setProperty(property, value);
  666. }
  667. };
  668. const internalRemove = (dom, property) => {
  669. if (isSupported$1(dom)) {
  670. dom.style.removeProperty(property);
  671. }
  672. };
  673. const set$8 = (element, property, value) => {
  674. const dom = element.dom;
  675. internalSet(dom, property, value);
  676. };
  677. const setAll = (element, css) => {
  678. const dom = element.dom;
  679. each(css, (v, k) => {
  680. internalSet(dom, k, v);
  681. });
  682. };
  683. const setOptions = (element, css) => {
  684. const dom = element.dom;
  685. each(css, (v, k) => {
  686. v.fold(() => {
  687. internalRemove(dom, k);
  688. }, value => {
  689. internalSet(dom, k, value);
  690. });
  691. });
  692. };
  693. const get$e = (element, property) => {
  694. const dom = element.dom;
  695. const styles = window.getComputedStyle(dom);
  696. const r = styles.getPropertyValue(property);
  697. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  698. };
  699. const getUnsafeProperty = (dom, property) => isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  700. const getRaw = (element, property) => {
  701. const dom = element.dom;
  702. const raw = getUnsafeProperty(dom, property);
  703. return Optional.from(raw).filter(r => r.length > 0);
  704. };
  705. const getAllRaw = element => {
  706. const css = {};
  707. const dom = element.dom;
  708. if (isSupported$1(dom)) {
  709. for (let i = 0; i < dom.style.length; i++) {
  710. const ruleName = dom.style.item(i);
  711. css[ruleName] = dom.style[ruleName];
  712. }
  713. }
  714. return css;
  715. };
  716. const isValidValue = (tag, property, value) => {
  717. const element = SugarElement.fromTag(tag);
  718. set$8(element, property, value);
  719. const style = getRaw(element, property);
  720. return style.isSome();
  721. };
  722. const remove$6 = (element, property) => {
  723. const dom = element.dom;
  724. internalRemove(dom, property);
  725. if (is$1(getOpt(element, 'style').map(trim$1), '')) {
  726. remove$7(element, 'style');
  727. }
  728. };
  729. const reflow = e => e.dom.offsetWidth;
  730. const Dimension = (name, getOffset) => {
  731. const set = (element, h) => {
  732. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  733. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  734. }
  735. const dom = element.dom;
  736. if (isSupported$1(dom)) {
  737. dom.style[name] = h + 'px';
  738. }
  739. };
  740. const get = element => {
  741. const r = getOffset(element);
  742. if (r <= 0 || r === null) {
  743. const css = get$e(element, name);
  744. return parseFloat(css) || 0;
  745. }
  746. return r;
  747. };
  748. const getOuter = get;
  749. const aggregate = (element, properties) => foldl(properties, (acc, property) => {
  750. const val = get$e(element, property);
  751. const value = val === undefined ? 0 : parseInt(val, 10);
  752. return isNaN(value) ? acc : acc + value;
  753. }, 0);
  754. const max = (element, value, properties) => {
  755. const cumulativeInclusions = aggregate(element, properties);
  756. const absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  757. return absoluteMax;
  758. };
  759. return {
  760. set,
  761. get,
  762. getOuter,
  763. aggregate,
  764. max
  765. };
  766. };
  767. const api$2 = Dimension('height', element => {
  768. const dom = element.dom;
  769. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  770. });
  771. const get$d = element => api$2.get(element);
  772. const getOuter$2 = element => api$2.getOuter(element);
  773. const setMax$1 = (element, value) => {
  774. const inclusions = [
  775. 'margin-top',
  776. 'border-top-width',
  777. 'padding-top',
  778. 'padding-bottom',
  779. 'border-bottom-width',
  780. 'margin-bottom'
  781. ];
  782. const absMax = api$2.max(element, value, inclusions);
  783. set$8(element, 'max-height', absMax + 'px');
  784. };
  785. const r$1 = (left, top) => {
  786. const translate = (x, y) => r$1(left + x, top + y);
  787. return {
  788. left,
  789. top,
  790. translate
  791. };
  792. };
  793. const SugarPosition = r$1;
  794. const boxPosition = dom => {
  795. const box = dom.getBoundingClientRect();
  796. return SugarPosition(box.left, box.top);
  797. };
  798. const firstDefinedOrZero = (a, b) => {
  799. if (a !== undefined) {
  800. return a;
  801. } else {
  802. return b !== undefined ? b : 0;
  803. }
  804. };
  805. const absolute$3 = element => {
  806. const doc = element.dom.ownerDocument;
  807. const body = doc.body;
  808. const win = doc.defaultView;
  809. const html = doc.documentElement;
  810. if (body === element.dom) {
  811. return SugarPosition(body.offsetLeft, body.offsetTop);
  812. }
  813. const scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  814. const scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  815. const clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  816. const clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  817. return viewport$1(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  818. };
  819. const viewport$1 = element => {
  820. const dom = element.dom;
  821. const doc = dom.ownerDocument;
  822. const body = doc.body;
  823. if (body === dom) {
  824. return SugarPosition(body.offsetLeft, body.offsetTop);
  825. }
  826. if (!inBody(element)) {
  827. return SugarPosition(0, 0);
  828. }
  829. return boxPosition(dom);
  830. };
  831. const api$1 = Dimension('width', element => element.dom.offsetWidth);
  832. const set$7 = (element, h) => api$1.set(element, h);
  833. const get$c = element => api$1.get(element);
  834. const getOuter$1 = element => api$1.getOuter(element);
  835. const setMax = (element, value) => {
  836. const inclusions = [
  837. 'margin-left',
  838. 'border-left-width',
  839. 'padding-left',
  840. 'padding-right',
  841. 'border-right-width',
  842. 'margin-right'
  843. ];
  844. const absMax = api$1.max(element, value, inclusions);
  845. set$8(element, 'max-width', absMax + 'px');
  846. };
  847. const cached = f => {
  848. let called = false;
  849. let r;
  850. return (...args) => {
  851. if (!called) {
  852. called = true;
  853. r = f.apply(null, args);
  854. }
  855. return r;
  856. };
  857. };
  858. const DeviceType = (os, browser, userAgent, mediaMatch) => {
  859. const isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  860. const isiPhone = os.isiOS() && !isiPad;
  861. const isMobile = os.isiOS() || os.isAndroid();
  862. const isTouch = isMobile || mediaMatch('(pointer:coarse)');
  863. const isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  864. const isPhone = isiPhone || isMobile && !isTablet;
  865. const iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  866. const isDesktop = !isPhone && !isTablet && !iOSwebview;
  867. return {
  868. isiPad: constant$1(isiPad),
  869. isiPhone: constant$1(isiPhone),
  870. isTablet: constant$1(isTablet),
  871. isPhone: constant$1(isPhone),
  872. isTouch: constant$1(isTouch),
  873. isAndroid: os.isAndroid,
  874. isiOS: os.isiOS,
  875. isWebView: constant$1(iOSwebview),
  876. isDesktop: constant$1(isDesktop)
  877. };
  878. };
  879. const firstMatch = (regexes, s) => {
  880. for (let i = 0; i < regexes.length; i++) {
  881. const x = regexes[i];
  882. if (x.test(s)) {
  883. return x;
  884. }
  885. }
  886. return undefined;
  887. };
  888. const find$3 = (regexes, agent) => {
  889. const r = firstMatch(regexes, agent);
  890. if (!r) {
  891. return {
  892. major: 0,
  893. minor: 0
  894. };
  895. }
  896. const group = i => {
  897. return Number(agent.replace(r, '$' + i));
  898. };
  899. return nu$d(group(1), group(2));
  900. };
  901. const detect$4 = (versionRegexes, agent) => {
  902. const cleanedAgent = String(agent).toLowerCase();
  903. if (versionRegexes.length === 0) {
  904. return unknown$3();
  905. }
  906. return find$3(versionRegexes, cleanedAgent);
  907. };
  908. const unknown$3 = () => {
  909. return nu$d(0, 0);
  910. };
  911. const nu$d = (major, minor) => {
  912. return {
  913. major,
  914. minor
  915. };
  916. };
  917. const Version = {
  918. nu: nu$d,
  919. detect: detect$4,
  920. unknown: unknown$3
  921. };
  922. const detectBrowser$1 = (browsers, userAgentData) => {
  923. return findMap(userAgentData.brands, uaBrand => {
  924. const lcBrand = uaBrand.brand.toLowerCase();
  925. return find$5(browsers, browser => {
  926. var _a;
  927. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  928. }).map(info => ({
  929. current: info.name,
  930. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  931. }));
  932. });
  933. };
  934. const detect$3 = (candidates, userAgent) => {
  935. const agent = String(userAgent).toLowerCase();
  936. return find$5(candidates, candidate => {
  937. return candidate.search(agent);
  938. });
  939. };
  940. const detectBrowser = (browsers, userAgent) => {
  941. return detect$3(browsers, userAgent).map(browser => {
  942. const version = Version.detect(browser.versionRegexes, userAgent);
  943. return {
  944. current: browser.name,
  945. version
  946. };
  947. });
  948. };
  949. const detectOs = (oses, userAgent) => {
  950. return detect$3(oses, userAgent).map(os => {
  951. const version = Version.detect(os.versionRegexes, userAgent);
  952. return {
  953. current: os.name,
  954. version
  955. };
  956. });
  957. };
  958. const normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  959. const checkContains = target => {
  960. return uastring => {
  961. return contains$1(uastring, target);
  962. };
  963. };
  964. const browsers = [
  965. {
  966. name: 'Edge',
  967. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  968. search: uastring => {
  969. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  970. }
  971. },
  972. {
  973. name: 'Chromium',
  974. brand: 'Chromium',
  975. versionRegexes: [
  976. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  977. normalVersionRegex
  978. ],
  979. search: uastring => {
  980. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  981. }
  982. },
  983. {
  984. name: 'IE',
  985. versionRegexes: [
  986. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  987. /.*?rv:([0-9]+)\.([0-9]+).*/
  988. ],
  989. search: uastring => {
  990. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  991. }
  992. },
  993. {
  994. name: 'Opera',
  995. versionRegexes: [
  996. normalVersionRegex,
  997. /.*?opera\/([0-9]+)\.([0-9]+).*/
  998. ],
  999. search: checkContains('opera')
  1000. },
  1001. {
  1002. name: 'Firefox',
  1003. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1004. search: checkContains('firefox')
  1005. },
  1006. {
  1007. name: 'Safari',
  1008. versionRegexes: [
  1009. normalVersionRegex,
  1010. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1011. ],
  1012. search: uastring => {
  1013. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1014. }
  1015. }
  1016. ];
  1017. const oses = [
  1018. {
  1019. name: 'Windows',
  1020. search: checkContains('win'),
  1021. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1022. },
  1023. {
  1024. name: 'iOS',
  1025. search: uastring => {
  1026. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1027. },
  1028. versionRegexes: [
  1029. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1030. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1031. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1032. ]
  1033. },
  1034. {
  1035. name: 'Android',
  1036. search: checkContains('android'),
  1037. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1038. },
  1039. {
  1040. name: 'macOS',
  1041. search: checkContains('mac os x'),
  1042. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  1043. },
  1044. {
  1045. name: 'Linux',
  1046. search: checkContains('linux'),
  1047. versionRegexes: []
  1048. },
  1049. {
  1050. name: 'Solaris',
  1051. search: checkContains('sunos'),
  1052. versionRegexes: []
  1053. },
  1054. {
  1055. name: 'FreeBSD',
  1056. search: checkContains('freebsd'),
  1057. versionRegexes: []
  1058. },
  1059. {
  1060. name: 'ChromeOS',
  1061. search: checkContains('cros'),
  1062. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  1063. }
  1064. ];
  1065. const PlatformInfo = {
  1066. browsers: constant$1(browsers),
  1067. oses: constant$1(oses)
  1068. };
  1069. const edge = 'Edge';
  1070. const chromium = 'Chromium';
  1071. const ie = 'IE';
  1072. const opera = 'Opera';
  1073. const firefox = 'Firefox';
  1074. const safari = 'Safari';
  1075. const unknown$2 = () => {
  1076. return nu$c({
  1077. current: undefined,
  1078. version: Version.unknown()
  1079. });
  1080. };
  1081. const nu$c = info => {
  1082. const current = info.current;
  1083. const version = info.version;
  1084. const isBrowser = name => () => current === name;
  1085. return {
  1086. current,
  1087. version,
  1088. isEdge: isBrowser(edge),
  1089. isChromium: isBrowser(chromium),
  1090. isIE: isBrowser(ie),
  1091. isOpera: isBrowser(opera),
  1092. isFirefox: isBrowser(firefox),
  1093. isSafari: isBrowser(safari)
  1094. };
  1095. };
  1096. const Browser = {
  1097. unknown: unknown$2,
  1098. nu: nu$c,
  1099. edge: constant$1(edge),
  1100. chromium: constant$1(chromium),
  1101. ie: constant$1(ie),
  1102. opera: constant$1(opera),
  1103. firefox: constant$1(firefox),
  1104. safari: constant$1(safari)
  1105. };
  1106. const windows = 'Windows';
  1107. const ios = 'iOS';
  1108. const android = 'Android';
  1109. const linux = 'Linux';
  1110. const macos = 'macOS';
  1111. const solaris = 'Solaris';
  1112. const freebsd = 'FreeBSD';
  1113. const chromeos = 'ChromeOS';
  1114. const unknown$1 = () => {
  1115. return nu$b({
  1116. current: undefined,
  1117. version: Version.unknown()
  1118. });
  1119. };
  1120. const nu$b = info => {
  1121. const current = info.current;
  1122. const version = info.version;
  1123. const isOS = name => () => current === name;
  1124. return {
  1125. current,
  1126. version,
  1127. isWindows: isOS(windows),
  1128. isiOS: isOS(ios),
  1129. isAndroid: isOS(android),
  1130. isMacOS: isOS(macos),
  1131. isLinux: isOS(linux),
  1132. isSolaris: isOS(solaris),
  1133. isFreeBSD: isOS(freebsd),
  1134. isChromeOS: isOS(chromeos)
  1135. };
  1136. };
  1137. const OperatingSystem = {
  1138. unknown: unknown$1,
  1139. nu: nu$b,
  1140. windows: constant$1(windows),
  1141. ios: constant$1(ios),
  1142. android: constant$1(android),
  1143. linux: constant$1(linux),
  1144. macos: constant$1(macos),
  1145. solaris: constant$1(solaris),
  1146. freebsd: constant$1(freebsd),
  1147. chromeos: constant$1(chromeos)
  1148. };
  1149. const detect$2 = (userAgent, userAgentDataOpt, mediaMatch) => {
  1150. const browsers = PlatformInfo.browsers();
  1151. const oses = PlatformInfo.oses();
  1152. const browser = userAgentDataOpt.bind(userAgentData => detectBrowser$1(browsers, userAgentData)).orThunk(() => detectBrowser(browsers, userAgent)).fold(Browser.unknown, Browser.nu);
  1153. const os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1154. const deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1155. return {
  1156. browser,
  1157. os,
  1158. deviceType
  1159. };
  1160. };
  1161. const PlatformDetection = { detect: detect$2 };
  1162. const mediaMatch = query => window.matchMedia(query).matches;
  1163. let platform = cached(() => PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch));
  1164. const detect$1 = () => platform();
  1165. const mkEvent = (target, x, y, stop, prevent, kill, raw) => ({
  1166. target,
  1167. x,
  1168. y,
  1169. stop,
  1170. prevent,
  1171. kill,
  1172. raw
  1173. });
  1174. const fromRawEvent$1 = rawEvent => {
  1175. const target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  1176. const stop = () => rawEvent.stopPropagation();
  1177. const prevent = () => rawEvent.preventDefault();
  1178. const kill = compose(prevent, stop);
  1179. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  1180. };
  1181. const handle = (filter, handler) => rawEvent => {
  1182. if (filter(rawEvent)) {
  1183. handler(fromRawEvent$1(rawEvent));
  1184. }
  1185. };
  1186. const binder = (element, event, filter, handler, useCapture) => {
  1187. const wrapped = handle(filter, handler);
  1188. element.dom.addEventListener(event, wrapped, useCapture);
  1189. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  1190. };
  1191. const bind$2 = (element, event, filter, handler) => binder(element, event, filter, handler, false);
  1192. const capture$1 = (element, event, filter, handler) => binder(element, event, filter, handler, true);
  1193. const unbind = (element, event, handler, useCapture) => {
  1194. element.dom.removeEventListener(event, handler, useCapture);
  1195. };
  1196. const before$1 = (marker, element) => {
  1197. const parent$1 = parent(marker);
  1198. parent$1.each(v => {
  1199. v.dom.insertBefore(element.dom, marker.dom);
  1200. });
  1201. };
  1202. const after$2 = (marker, element) => {
  1203. const sibling = nextSibling(marker);
  1204. sibling.fold(() => {
  1205. const parent$1 = parent(marker);
  1206. parent$1.each(v => {
  1207. append$2(v, element);
  1208. });
  1209. }, v => {
  1210. before$1(v, element);
  1211. });
  1212. };
  1213. const prepend$1 = (parent, element) => {
  1214. const firstChild$1 = firstChild(parent);
  1215. firstChild$1.fold(() => {
  1216. append$2(parent, element);
  1217. }, v => {
  1218. parent.dom.insertBefore(element.dom, v.dom);
  1219. });
  1220. };
  1221. const append$2 = (parent, element) => {
  1222. parent.dom.appendChild(element.dom);
  1223. };
  1224. const appendAt = (parent, element, index) => {
  1225. child$2(parent, index).fold(() => {
  1226. append$2(parent, element);
  1227. }, v => {
  1228. before$1(v, element);
  1229. });
  1230. };
  1231. const append$1 = (parent, elements) => {
  1232. each$1(elements, x => {
  1233. append$2(parent, x);
  1234. });
  1235. };
  1236. const empty = element => {
  1237. element.dom.textContent = '';
  1238. each$1(children(element), rogue => {
  1239. remove$5(rogue);
  1240. });
  1241. };
  1242. const remove$5 = element => {
  1243. const dom = element.dom;
  1244. if (dom.parentNode !== null) {
  1245. dom.parentNode.removeChild(dom);
  1246. }
  1247. };
  1248. const get$b = _DOC => {
  1249. const doc = _DOC !== undefined ? _DOC.dom : document;
  1250. const x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1251. const y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1252. return SugarPosition(x, y);
  1253. };
  1254. const to = (x, y, _DOC) => {
  1255. const doc = _DOC !== undefined ? _DOC.dom : document;
  1256. const win = doc.defaultView;
  1257. if (win) {
  1258. win.scrollTo(x, y);
  1259. }
  1260. };
  1261. const get$a = _win => {
  1262. const win = _win === undefined ? window : _win;
  1263. if (detect$1().browser.isFirefox()) {
  1264. return Optional.none();
  1265. } else {
  1266. return Optional.from(win.visualViewport);
  1267. }
  1268. };
  1269. const bounds$1 = (x, y, width, height) => ({
  1270. x,
  1271. y,
  1272. width,
  1273. height,
  1274. right: x + width,
  1275. bottom: y + height
  1276. });
  1277. const getBounds$3 = _win => {
  1278. const win = _win === undefined ? window : _win;
  1279. const doc = win.document;
  1280. const scroll = get$b(SugarElement.fromDom(doc));
  1281. return get$a(win).fold(() => {
  1282. const html = win.document.documentElement;
  1283. const width = html.clientWidth;
  1284. const height = html.clientHeight;
  1285. return bounds$1(scroll.left, scroll.top, width, height);
  1286. }, visualViewport => bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height));
  1287. };
  1288. const getDocument = () => SugarElement.fromDom(document);
  1289. const walkUp = (navigation, doc) => {
  1290. const frame = navigation.view(doc);
  1291. return frame.fold(constant$1([]), f => {
  1292. const parent = navigation.owner(f);
  1293. const rest = walkUp(navigation, parent);
  1294. return [f].concat(rest);
  1295. });
  1296. };
  1297. const pathTo = (element, navigation) => {
  1298. const d = navigation.owner(element);
  1299. const paths = walkUp(navigation, d);
  1300. return Optional.some(paths);
  1301. };
  1302. const view = doc => {
  1303. var _a;
  1304. const element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  1305. return element.map(SugarElement.fromDom);
  1306. };
  1307. const owner$3 = element => owner$4(element);
  1308. var Navigation = /*#__PURE__*/Object.freeze({
  1309. __proto__: null,
  1310. view: view,
  1311. owner: owner$3
  1312. });
  1313. const find$2 = element => {
  1314. const doc = getDocument();
  1315. const scroll = get$b(doc);
  1316. const path = pathTo(element, Navigation);
  1317. return path.fold(curry(absolute$3, element), frames => {
  1318. const offset = viewport$1(element);
  1319. const r = foldr(frames, (b, a) => {
  1320. const loc = viewport$1(a);
  1321. return {
  1322. left: b.left + loc.left,
  1323. top: b.top + loc.top
  1324. };
  1325. }, {
  1326. left: 0,
  1327. top: 0
  1328. });
  1329. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  1330. });
  1331. };
  1332. const pointed = (point, width, height) => ({
  1333. point,
  1334. width,
  1335. height
  1336. });
  1337. const rect = (x, y, width, height) => ({
  1338. x,
  1339. y,
  1340. width,
  1341. height
  1342. });
  1343. const bounds = (x, y, width, height) => ({
  1344. x,
  1345. y,
  1346. width,
  1347. height,
  1348. right: x + width,
  1349. bottom: y + height
  1350. });
  1351. const box$1 = element => {
  1352. const xy = absolute$3(element);
  1353. const w = getOuter$1(element);
  1354. const h = getOuter$2(element);
  1355. return bounds(xy.left, xy.top, w, h);
  1356. };
  1357. const absolute$2 = element => {
  1358. const position = find$2(element);
  1359. const width = getOuter$1(element);
  1360. const height = getOuter$2(element);
  1361. return bounds(position.left, position.top, width, height);
  1362. };
  1363. const win = () => getBounds$3(window);
  1364. const value$4 = value => {
  1365. const applyHelper = fn => fn(value);
  1366. const constHelper = constant$1(value);
  1367. const outputHelper = () => output;
  1368. const output = {
  1369. tag: true,
  1370. inner: value,
  1371. fold: (_onError, onValue) => onValue(value),
  1372. isValue: always,
  1373. isError: never,
  1374. map: mapper => Result.value(mapper(value)),
  1375. mapError: outputHelper,
  1376. bind: applyHelper,
  1377. exists: applyHelper,
  1378. forall: applyHelper,
  1379. getOr: constHelper,
  1380. or: outputHelper,
  1381. getOrThunk: constHelper,
  1382. orThunk: outputHelper,
  1383. getOrDie: constHelper,
  1384. each: fn => {
  1385. fn(value);
  1386. },
  1387. toOptional: () => Optional.some(value)
  1388. };
  1389. return output;
  1390. };
  1391. const error$1 = error => {
  1392. const outputHelper = () => output;
  1393. const output = {
  1394. tag: false,
  1395. inner: error,
  1396. fold: (onError, _onValue) => onError(error),
  1397. isValue: never,
  1398. isError: always,
  1399. map: outputHelper,
  1400. mapError: mapper => Result.error(mapper(error)),
  1401. bind: outputHelper,
  1402. exists: never,
  1403. forall: always,
  1404. getOr: identity,
  1405. or: identity,
  1406. getOrThunk: apply,
  1407. orThunk: apply,
  1408. getOrDie: die(String(error)),
  1409. each: noop,
  1410. toOptional: Optional.none
  1411. };
  1412. return output;
  1413. };
  1414. const fromOption = (optional, err) => optional.fold(() => error$1(err), value$4);
  1415. const Result = {
  1416. value: value$4,
  1417. error: error$1,
  1418. fromOption
  1419. };
  1420. var SimpleResultType;
  1421. (function (SimpleResultType) {
  1422. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1423. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1424. }(SimpleResultType || (SimpleResultType = {})));
  1425. const fold$1 = (res, onError, onValue) => res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1426. const partition$2 = results => {
  1427. const values = [];
  1428. const errors = [];
  1429. each$1(results, obj => {
  1430. fold$1(obj, err => errors.push(err), val => values.push(val));
  1431. });
  1432. return {
  1433. values,
  1434. errors
  1435. };
  1436. };
  1437. const mapError = (res, f) => {
  1438. if (res.stype === SimpleResultType.Error) {
  1439. return {
  1440. stype: SimpleResultType.Error,
  1441. serror: f(res.serror)
  1442. };
  1443. } else {
  1444. return res;
  1445. }
  1446. };
  1447. const map = (res, f) => {
  1448. if (res.stype === SimpleResultType.Value) {
  1449. return {
  1450. stype: SimpleResultType.Value,
  1451. svalue: f(res.svalue)
  1452. };
  1453. } else {
  1454. return res;
  1455. }
  1456. };
  1457. const bind$1 = (res, f) => {
  1458. if (res.stype === SimpleResultType.Value) {
  1459. return f(res.svalue);
  1460. } else {
  1461. return res;
  1462. }
  1463. };
  1464. const bindError = (res, f) => {
  1465. if (res.stype === SimpleResultType.Error) {
  1466. return f(res.serror);
  1467. } else {
  1468. return res;
  1469. }
  1470. };
  1471. const svalue = v => ({
  1472. stype: SimpleResultType.Value,
  1473. svalue: v
  1474. });
  1475. const serror = e => ({
  1476. stype: SimpleResultType.Error,
  1477. serror: e
  1478. });
  1479. const toResult$1 = res => fold$1(res, Result.error, Result.value);
  1480. const fromResult$1 = res => res.fold(serror, svalue);
  1481. const SimpleResult = {
  1482. fromResult: fromResult$1,
  1483. toResult: toResult$1,
  1484. svalue,
  1485. partition: partition$2,
  1486. serror,
  1487. bind: bind$1,
  1488. bindError,
  1489. map,
  1490. mapError,
  1491. fold: fold$1
  1492. };
  1493. const field$2 = (key, newKey, presence, prop) => ({
  1494. tag: 'field',
  1495. key,
  1496. newKey,
  1497. presence,
  1498. prop
  1499. });
  1500. const customField$1 = (newKey, instantiator) => ({
  1501. tag: 'custom',
  1502. newKey,
  1503. instantiator
  1504. });
  1505. const fold = (value, ifField, ifCustom) => {
  1506. switch (value.tag) {
  1507. case 'field':
  1508. return ifField(value.key, value.newKey, value.presence, value.prop);
  1509. case 'custom':
  1510. return ifCustom(value.newKey, value.instantiator);
  1511. }
  1512. };
  1513. const shallow$1 = (old, nu) => {
  1514. return nu;
  1515. };
  1516. const deep = (old, nu) => {
  1517. const bothObjects = isPlainObject(old) && isPlainObject(nu);
  1518. return bothObjects ? deepMerge(old, nu) : nu;
  1519. };
  1520. const baseMerge = merger => {
  1521. return (...objects) => {
  1522. if (objects.length === 0) {
  1523. throw new Error(`Can't merge zero objects`);
  1524. }
  1525. const ret = {};
  1526. for (let j = 0; j < objects.length; j++) {
  1527. const curObject = objects[j];
  1528. for (const key in curObject) {
  1529. if (has$2(curObject, key)) {
  1530. ret[key] = merger(ret[key], curObject[key]);
  1531. }
  1532. }
  1533. }
  1534. return ret;
  1535. };
  1536. };
  1537. const deepMerge = baseMerge(deep);
  1538. const merge$1 = baseMerge(shallow$1);
  1539. const required$2 = () => ({
  1540. tag: 'required',
  1541. process: {}
  1542. });
  1543. const defaultedThunk = fallbackThunk => ({
  1544. tag: 'defaultedThunk',
  1545. process: fallbackThunk
  1546. });
  1547. const defaulted$1 = fallback => defaultedThunk(constant$1(fallback));
  1548. const asOption = () => ({
  1549. tag: 'option',
  1550. process: {}
  1551. });
  1552. const mergeWithThunk = baseThunk => ({
  1553. tag: 'mergeWithThunk',
  1554. process: baseThunk
  1555. });
  1556. const mergeWith = base => mergeWithThunk(constant$1(base));
  1557. const mergeValues$1 = (values, base) => values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1558. const mergeErrors$1 = errors => compose(SimpleResult.serror, flatten)(errors);
  1559. const consolidateObj = (objects, base) => {
  1560. const partition = SimpleResult.partition(objects);
  1561. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1562. };
  1563. const consolidateArr = objects => {
  1564. const partitions = SimpleResult.partition(objects);
  1565. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1566. };
  1567. const ResultCombine = {
  1568. consolidateObj,
  1569. consolidateArr
  1570. };
  1571. const formatObj = input => {
  1572. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1573. };
  1574. const formatErrors = errors => {
  1575. const es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1576. path: [],
  1577. getErrorInfo: constant$1('... (only showing first ten failures)')
  1578. }]) : errors;
  1579. return map$2(es, e => {
  1580. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1581. });
  1582. };
  1583. const nu$a = (path, getErrorInfo) => {
  1584. return SimpleResult.serror([{
  1585. path,
  1586. getErrorInfo
  1587. }]);
  1588. };
  1589. const missingRequired = (path, key, obj) => nu$a(path, () => 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj));
  1590. const missingKey = (path, key) => nu$a(path, () => 'Choice schema did not contain choice key: "' + key + '"');
  1591. const missingBranch = (path, branches, branch) => nu$a(path, () => 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches));
  1592. const unsupportedFields = (path, unsupported) => nu$a(path, () => 'There are unsupported fields: [' + unsupported.join(', ') + '] specified');
  1593. const custom = (path, err) => nu$a(path, constant$1(err));
  1594. const value$3 = validator => {
  1595. const extract = (path, val) => {
  1596. return SimpleResult.bindError(validator(val), err => custom(path, err));
  1597. };
  1598. const toString = constant$1('val');
  1599. return {
  1600. extract,
  1601. toString
  1602. };
  1603. };
  1604. const anyValue$1 = value$3(SimpleResult.svalue);
  1605. const requiredAccess = (path, obj, key, bundle) => get$g(obj, key).fold(() => missingRequired(path, key, obj), bundle);
  1606. const fallbackAccess = (obj, key, fallback, bundle) => {
  1607. const v = get$g(obj, key).getOrThunk(() => fallback(obj));
  1608. return bundle(v);
  1609. };
  1610. const optionAccess = (obj, key, bundle) => bundle(get$g(obj, key));
  1611. const optionDefaultedAccess = (obj, key, fallback, bundle) => {
  1612. const opt = get$g(obj, key).map(val => val === true ? fallback(obj) : val);
  1613. return bundle(opt);
  1614. };
  1615. const extractField = (field, path, obj, key, prop) => {
  1616. const bundle = av => prop.extract(path.concat([key]), av);
  1617. const bundleAsOption = optValue => optValue.fold(() => SimpleResult.svalue(Optional.none()), ov => {
  1618. const result = prop.extract(path.concat([key]), ov);
  1619. return SimpleResult.map(result, Optional.some);
  1620. });
  1621. switch (field.tag) {
  1622. case 'required':
  1623. return requiredAccess(path, obj, key, bundle);
  1624. case 'defaultedThunk':
  1625. return fallbackAccess(obj, key, field.process, bundle);
  1626. case 'option':
  1627. return optionAccess(obj, key, bundleAsOption);
  1628. case 'defaultedOptionThunk':
  1629. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  1630. case 'mergeWithThunk': {
  1631. return fallbackAccess(obj, key, constant$1({}), v => {
  1632. const result = deepMerge(field.process(obj), v);
  1633. return bundle(result);
  1634. });
  1635. }
  1636. }
  1637. };
  1638. const extractFields = (path, obj, fields) => {
  1639. const success = {};
  1640. const errors = [];
  1641. for (const field of fields) {
  1642. fold(field, (key, newKey, presence, prop) => {
  1643. const result = extractField(presence, path, obj, key, prop);
  1644. SimpleResult.fold(result, err => {
  1645. errors.push(...err);
  1646. }, res => {
  1647. success[newKey] = res;
  1648. });
  1649. }, (newKey, instantiator) => {
  1650. success[newKey] = instantiator(obj);
  1651. });
  1652. }
  1653. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  1654. };
  1655. const valueThunk = getDelegate => {
  1656. const extract = (path, val) => getDelegate().extract(path, val);
  1657. const toString = () => getDelegate().toString();
  1658. return {
  1659. extract,
  1660. toString
  1661. };
  1662. };
  1663. const getSetKeys = obj => keys(filter$1(obj, isNonNullable));
  1664. const objOfOnly = fields => {
  1665. const delegate = objOf(fields);
  1666. const fieldNames = foldr(fields, (acc, value) => {
  1667. return fold(value, key => deepMerge(acc, { [key]: true }), constant$1(acc));
  1668. }, {});
  1669. const extract = (path, o) => {
  1670. const keys = isBoolean(o) ? [] : getSetKeys(o);
  1671. const extra = filter$2(keys, k => !hasNonNullableKey(fieldNames, k));
  1672. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  1673. };
  1674. return {
  1675. extract,
  1676. toString: delegate.toString
  1677. };
  1678. };
  1679. const objOf = values => {
  1680. const extract = (path, o) => extractFields(path, o, values);
  1681. const toString = () => {
  1682. const fieldStrings = map$2(values, value => fold(value, (key, _okey, _presence, prop) => key + ' -> ' + prop.toString(), (newKey, _instantiator) => 'state(' + newKey + ')'));
  1683. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1684. };
  1685. return {
  1686. extract,
  1687. toString
  1688. };
  1689. };
  1690. const arrOf = prop => {
  1691. const extract = (path, array) => {
  1692. const results = map$2(array, (a, i) => prop.extract(path.concat(['[' + i + ']']), a));
  1693. return ResultCombine.consolidateArr(results);
  1694. };
  1695. const toString = () => 'array(' + prop.toString() + ')';
  1696. return {
  1697. extract,
  1698. toString
  1699. };
  1700. };
  1701. const oneOf = props => {
  1702. const extract = (path, val) => {
  1703. const errors = [];
  1704. for (const prop of props) {
  1705. const res = prop.extract(path, val);
  1706. if (res.stype === SimpleResultType.Value) {
  1707. return res;
  1708. }
  1709. errors.push(res);
  1710. }
  1711. return ResultCombine.consolidateArr(errors);
  1712. };
  1713. const toString = () => 'oneOf(' + map$2(props, prop => prop.toString()).join(', ') + ')';
  1714. return {
  1715. extract,
  1716. toString
  1717. };
  1718. };
  1719. const setOf$1 = (validator, prop) => {
  1720. const validateKeys = (path, keys) => arrOf(value$3(validator)).extract(path, keys);
  1721. const extract = (path, o) => {
  1722. const keys$1 = keys(o);
  1723. const validatedKeys = validateKeys(path, keys$1);
  1724. return SimpleResult.bind(validatedKeys, validKeys => {
  1725. const schema = map$2(validKeys, vk => {
  1726. return field$2(vk, vk, required$2(), prop);
  1727. });
  1728. return objOf(schema).extract(path, o);
  1729. });
  1730. };
  1731. const toString = () => 'setOf(' + prop.toString() + ')';
  1732. return {
  1733. extract,
  1734. toString
  1735. };
  1736. };
  1737. const thunk = (_desc, processor) => {
  1738. const getP = cached(processor);
  1739. const extract = (path, val) => getP().extract(path, val);
  1740. const toString = () => getP().toString();
  1741. return {
  1742. extract,
  1743. toString
  1744. };
  1745. };
  1746. const arrOfObj = compose(arrOf, objOf);
  1747. const anyValue = constant$1(anyValue$1);
  1748. const typedValue = (validator, expectedType) => value$3(a => {
  1749. const actualType = typeof a;
  1750. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror(`Expected type: ${ expectedType } but got: ${ actualType }`);
  1751. });
  1752. const number = typedValue(isNumber, 'number');
  1753. const string = typedValue(isString, 'string');
  1754. const boolean = typedValue(isBoolean, 'boolean');
  1755. const functionProcessor = typedValue(isFunction, 'function');
  1756. const isPostMessageable = val => {
  1757. if (Object(val) !== val) {
  1758. return true;
  1759. }
  1760. switch ({}.toString.call(val).slice(8, -1)) {
  1761. case 'Boolean':
  1762. case 'Number':
  1763. case 'String':
  1764. case 'Date':
  1765. case 'RegExp':
  1766. case 'Blob':
  1767. case 'FileList':
  1768. case 'ImageData':
  1769. case 'ImageBitmap':
  1770. case 'ArrayBuffer':
  1771. return true;
  1772. case 'Array':
  1773. case 'Object':
  1774. return Object.keys(val).every(prop => isPostMessageable(val[prop]));
  1775. default:
  1776. return false;
  1777. }
  1778. };
  1779. const postMessageable = value$3(a => {
  1780. if (isPostMessageable(a)) {
  1781. return SimpleResult.svalue(a);
  1782. } else {
  1783. return SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1784. }
  1785. });
  1786. const chooseFrom = (path, input, branches, ch) => {
  1787. const fields = get$g(branches, ch);
  1788. return fields.fold(() => missingBranch(path, branches, ch), vp => vp.extract(path.concat(['branch: ' + ch]), input));
  1789. };
  1790. const choose$2 = (key, branches) => {
  1791. const extract = (path, input) => {
  1792. const choice = get$g(input, key);
  1793. return choice.fold(() => missingKey(path, key), chosen => chooseFrom(path, input, branches, chosen));
  1794. };
  1795. const toString = () => 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1796. return {
  1797. extract,
  1798. toString
  1799. };
  1800. };
  1801. const arrOfVal = () => arrOf(anyValue$1);
  1802. const valueOf = validator => value$3(v => validator(v).fold(SimpleResult.serror, SimpleResult.svalue));
  1803. const setOf = (validator, prop) => setOf$1(v => SimpleResult.fromResult(validator(v)), prop);
  1804. const extractValue = (label, prop, obj) => {
  1805. const res = prop.extract([label], obj);
  1806. return SimpleResult.mapError(res, errs => ({
  1807. input: obj,
  1808. errors: errs
  1809. }));
  1810. };
  1811. const asRaw = (label, prop, obj) => SimpleResult.toResult(extractValue(label, prop, obj));
  1812. const getOrDie = extraction => {
  1813. return extraction.fold(errInfo => {
  1814. throw new Error(formatError(errInfo));
  1815. }, identity);
  1816. };
  1817. const asRawOrDie$1 = (label, prop, obj) => getOrDie(asRaw(label, prop, obj));
  1818. const formatError = errInfo => {
  1819. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1820. };
  1821. const choose$1 = (key, branches) => choose$2(key, map$1(branches, objOf));
  1822. const thunkOf = (desc, schema) => thunk(desc, schema);
  1823. const field$1 = field$2;
  1824. const customField = customField$1;
  1825. const validateEnum = values => valueOf(value => contains$2(values, value) ? Result.value(value) : Result.error(`Unsupported value: "${ value }", choose one of "${ values.join(', ') }".`));
  1826. const required$1 = key => field$1(key, key, required$2(), anyValue());
  1827. const requiredOf = (key, schema) => field$1(key, key, required$2(), schema);
  1828. const requiredNumber = key => requiredOf(key, number);
  1829. const requiredString = key => requiredOf(key, string);
  1830. const requiredStringEnum = (key, values) => field$1(key, key, required$2(), validateEnum(values));
  1831. const requiredBoolean = key => requiredOf(key, boolean);
  1832. const requiredFunction = key => requiredOf(key, functionProcessor);
  1833. const forbid = (key, message) => field$1(key, key, asOption(), value$3(_v => SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message)));
  1834. const requiredObjOf = (key, objSchema) => field$1(key, key, required$2(), objOf(objSchema));
  1835. const requiredArrayOfObj = (key, objFields) => field$1(key, key, required$2(), arrOfObj(objFields));
  1836. const requiredArrayOf = (key, schema) => field$1(key, key, required$2(), arrOf(schema));
  1837. const option$3 = key => field$1(key, key, asOption(), anyValue());
  1838. const optionOf = (key, schema) => field$1(key, key, asOption(), schema);
  1839. const optionNumber = key => optionOf(key, number);
  1840. const optionString = key => optionOf(key, string);
  1841. const optionStringEnum = (key, values) => optionOf(key, validateEnum(values));
  1842. const optionFunction = key => optionOf(key, functionProcessor);
  1843. const optionArrayOf = (key, schema) => optionOf(key, arrOf(schema));
  1844. const optionObjOf = (key, objSchema) => optionOf(key, objOf(objSchema));
  1845. const optionObjOfOnly = (key, objSchema) => optionOf(key, objOfOnly(objSchema));
  1846. const defaulted = (key, fallback) => field$1(key, key, defaulted$1(fallback), anyValue());
  1847. const defaultedOf = (key, fallback, schema) => field$1(key, key, defaulted$1(fallback), schema);
  1848. const defaultedNumber = (key, fallback) => defaultedOf(key, fallback, number);
  1849. const defaultedString = (key, fallback) => defaultedOf(key, fallback, string);
  1850. const defaultedStringEnum = (key, fallback, values) => defaultedOf(key, fallback, validateEnum(values));
  1851. const defaultedBoolean = (key, fallback) => defaultedOf(key, fallback, boolean);
  1852. const defaultedFunction = (key, fallback) => defaultedOf(key, fallback, functionProcessor);
  1853. const defaultedPostMsg = (key, fallback) => defaultedOf(key, fallback, postMessageable);
  1854. const defaultedArrayOf = (key, fallback, schema) => defaultedOf(key, fallback, arrOf(schema));
  1855. const defaultedObjOf = (key, fallback, objSchema) => defaultedOf(key, fallback, objOf(objSchema));
  1856. const Cell = initial => {
  1857. let value = initial;
  1858. const get = () => {
  1859. return value;
  1860. };
  1861. const set = v => {
  1862. value = v;
  1863. };
  1864. return {
  1865. get,
  1866. set
  1867. };
  1868. };
  1869. const generate$7 = cases => {
  1870. if (!isArray(cases)) {
  1871. throw new Error('cases must be an array');
  1872. }
  1873. if (cases.length === 0) {
  1874. throw new Error('there must be at least one case');
  1875. }
  1876. const constructors = [];
  1877. const adt = {};
  1878. each$1(cases, (acase, count) => {
  1879. const keys$1 = keys(acase);
  1880. if (keys$1.length !== 1) {
  1881. throw new Error('one and only one name per case');
  1882. }
  1883. const key = keys$1[0];
  1884. const value = acase[key];
  1885. if (adt[key] !== undefined) {
  1886. throw new Error('duplicate key detected:' + key);
  1887. } else if (key === 'cata') {
  1888. throw new Error('cannot have a case named cata (sorry)');
  1889. } else if (!isArray(value)) {
  1890. throw new Error('case arguments must be an array');
  1891. }
  1892. constructors.push(key);
  1893. adt[key] = (...args) => {
  1894. const argLength = args.length;
  1895. if (argLength !== value.length) {
  1896. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1897. }
  1898. const match = branches => {
  1899. const branchKeys = keys(branches);
  1900. if (constructors.length !== branchKeys.length) {
  1901. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1902. }
  1903. const allReqd = forall(constructors, reqKey => {
  1904. return contains$2(branchKeys, reqKey);
  1905. });
  1906. if (!allReqd) {
  1907. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1908. }
  1909. return branches[key].apply(null, args);
  1910. };
  1911. return {
  1912. fold: (...foldArgs) => {
  1913. if (foldArgs.length !== cases.length) {
  1914. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  1915. }
  1916. const target = foldArgs[count];
  1917. return target.apply(null, args);
  1918. },
  1919. match,
  1920. log: label => {
  1921. console.log(label, {
  1922. constructors,
  1923. constructor: key,
  1924. params: args
  1925. });
  1926. }
  1927. };
  1928. };
  1929. });
  1930. return adt;
  1931. };
  1932. const Adt = { generate: generate$7 };
  1933. Adt.generate([
  1934. {
  1935. bothErrors: [
  1936. 'error1',
  1937. 'error2'
  1938. ]
  1939. },
  1940. {
  1941. firstError: [
  1942. 'error1',
  1943. 'value2'
  1944. ]
  1945. },
  1946. {
  1947. secondError: [
  1948. 'value1',
  1949. 'error2'
  1950. ]
  1951. },
  1952. {
  1953. bothValues: [
  1954. 'value1',
  1955. 'value2'
  1956. ]
  1957. }
  1958. ]);
  1959. const partition$1 = results => {
  1960. const errors = [];
  1961. const values = [];
  1962. each$1(results, result => {
  1963. result.fold(err => {
  1964. errors.push(err);
  1965. }, value => {
  1966. values.push(value);
  1967. });
  1968. });
  1969. return {
  1970. errors,
  1971. values
  1972. };
  1973. };
  1974. const exclude$1 = (obj, fields) => {
  1975. const r = {};
  1976. each(obj, (v, k) => {
  1977. if (!contains$2(fields, k)) {
  1978. r[k] = v;
  1979. }
  1980. });
  1981. return r;
  1982. };
  1983. const wrap$2 = (key, value) => ({ [key]: value });
  1984. const wrapAll$1 = keyvalues => {
  1985. const r = {};
  1986. each$1(keyvalues, kv => {
  1987. r[kv.key] = kv.value;
  1988. });
  1989. return r;
  1990. };
  1991. const exclude = (obj, fields) => exclude$1(obj, fields);
  1992. const wrap$1 = (key, value) => wrap$2(key, value);
  1993. const wrapAll = keyvalues => wrapAll$1(keyvalues);
  1994. const mergeValues = (values, base) => {
  1995. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  1996. };
  1997. const mergeErrors = errors => Result.error(flatten(errors));
  1998. const consolidate = (objs, base) => {
  1999. const partitions = partition$1(objs);
  2000. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2001. };
  2002. const ensureIsRoot = isRoot => isFunction(isRoot) ? isRoot : never;
  2003. const ancestor$2 = (scope, transform, isRoot) => {
  2004. let element = scope.dom;
  2005. const stop = ensureIsRoot(isRoot);
  2006. while (element.parentNode) {
  2007. element = element.parentNode;
  2008. const el = SugarElement.fromDom(element);
  2009. const transformed = transform(el);
  2010. if (transformed.isSome()) {
  2011. return transformed;
  2012. } else if (stop(el)) {
  2013. break;
  2014. }
  2015. }
  2016. return Optional.none();
  2017. };
  2018. const closest$4 = (scope, transform, isRoot) => {
  2019. const current = transform(scope);
  2020. const stop = ensureIsRoot(isRoot);
  2021. return current.orThunk(() => stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop));
  2022. };
  2023. const isSource = (component, simulatedEvent) => eq(component.element, simulatedEvent.event.target);
  2024. const defaultEventHandler = {
  2025. can: always,
  2026. abort: never,
  2027. run: noop
  2028. };
  2029. const nu$9 = parts => {
  2030. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2031. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2032. }
  2033. return {
  2034. ...defaultEventHandler,
  2035. ...parts
  2036. };
  2037. };
  2038. const all$2 = (handlers, f) => (...args) => foldl(handlers, (acc, handler) => acc && f(handler).apply(undefined, args), true);
  2039. const any = (handlers, f) => (...args) => foldl(handlers, (acc, handler) => acc || f(handler).apply(undefined, args), false);
  2040. const read$2 = handler => isFunction(handler) ? {
  2041. can: always,
  2042. abort: never,
  2043. run: handler
  2044. } : handler;
  2045. const fuse$1 = handlers => {
  2046. const can = all$2(handlers, handler => handler.can);
  2047. const abort = any(handlers, handler => handler.abort);
  2048. const run = (...args) => {
  2049. each$1(handlers, handler => {
  2050. handler.run.apply(undefined, args);
  2051. });
  2052. };
  2053. return {
  2054. can,
  2055. abort,
  2056. run
  2057. };
  2058. };
  2059. const constant = constant$1;
  2060. const touchstart = constant('touchstart');
  2061. const touchmove = constant('touchmove');
  2062. const touchend = constant('touchend');
  2063. const touchcancel = constant('touchcancel');
  2064. const mousedown = constant('mousedown');
  2065. const mousemove = constant('mousemove');
  2066. const mouseout = constant('mouseout');
  2067. const mouseup = constant('mouseup');
  2068. const mouseover = constant('mouseover');
  2069. const focusin = constant('focusin');
  2070. const focusout = constant('focusout');
  2071. const keydown = constant('keydown');
  2072. const keyup = constant('keyup');
  2073. const input = constant('input');
  2074. const change = constant('change');
  2075. const click = constant('click');
  2076. const transitioncancel = constant('transitioncancel');
  2077. const transitionend = constant('transitionend');
  2078. const transitionstart = constant('transitionstart');
  2079. const selectstart = constant('selectstart');
  2080. const prefixName = name => constant$1('alloy.' + name);
  2081. const alloy = { tap: prefixName('tap') };
  2082. const focus$4 = prefixName('focus');
  2083. const postBlur = prefixName('blur.post');
  2084. const postPaste = prefixName('paste.post');
  2085. const receive = prefixName('receive');
  2086. const execute$5 = prefixName('execute');
  2087. const focusItem = prefixName('focus.item');
  2088. const tap = alloy.tap;
  2089. const longpress = prefixName('longpress');
  2090. const sandboxClose = prefixName('sandbox.close');
  2091. const typeaheadCancel = prefixName('typeahead.cancel');
  2092. const systemInit = prefixName('system.init');
  2093. const documentTouchmove = prefixName('system.touchmove');
  2094. const documentTouchend = prefixName('system.touchend');
  2095. const windowScroll = prefixName('system.scroll');
  2096. const windowResize = prefixName('system.resize');
  2097. const attachedToDom = prefixName('system.attached');
  2098. const detachedFromDom = prefixName('system.detached');
  2099. const dismissRequested = prefixName('system.dismissRequested');
  2100. const repositionRequested = prefixName('system.repositionRequested');
  2101. const focusShifted = prefixName('focusmanager.shifted');
  2102. const slotVisibility = prefixName('slotcontainer.visibility');
  2103. const changeTab = prefixName('change.tab');
  2104. const dismissTab = prefixName('dismiss.tab');
  2105. const highlight$1 = prefixName('highlight');
  2106. const dehighlight$1 = prefixName('dehighlight');
  2107. const emit = (component, event) => {
  2108. dispatchWith(component, component.element, event, {});
  2109. };
  2110. const emitWith = (component, event, properties) => {
  2111. dispatchWith(component, component.element, event, properties);
  2112. };
  2113. const emitExecute = component => {
  2114. emit(component, execute$5());
  2115. };
  2116. const dispatch = (component, target, event) => {
  2117. dispatchWith(component, target, event, {});
  2118. };
  2119. const dispatchWith = (component, target, event, properties) => {
  2120. const data = {
  2121. target,
  2122. ...properties
  2123. };
  2124. component.getSystem().triggerEvent(event, target, data);
  2125. };
  2126. const dispatchEvent = (component, target, event, simulatedEvent) => {
  2127. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  2128. };
  2129. const derive$2 = configs => wrapAll(configs);
  2130. const abort = (name, predicate) => {
  2131. return {
  2132. key: name,
  2133. value: nu$9({ abort: predicate })
  2134. };
  2135. };
  2136. const can = (name, predicate) => {
  2137. return {
  2138. key: name,
  2139. value: nu$9({ can: predicate })
  2140. };
  2141. };
  2142. const preventDefault = name => {
  2143. return {
  2144. key: name,
  2145. value: nu$9({
  2146. run: (component, simulatedEvent) => {
  2147. simulatedEvent.event.prevent();
  2148. }
  2149. })
  2150. };
  2151. };
  2152. const run$1 = (name, handler) => {
  2153. return {
  2154. key: name,
  2155. value: nu$9({ run: handler })
  2156. };
  2157. };
  2158. const runActionExtra = (name, action, extra) => {
  2159. return {
  2160. key: name,
  2161. value: nu$9({
  2162. run: (component, simulatedEvent) => {
  2163. action.apply(undefined, [
  2164. component,
  2165. simulatedEvent
  2166. ].concat(extra));
  2167. }
  2168. })
  2169. };
  2170. };
  2171. const runOnName = name => {
  2172. return handler => run$1(name, handler);
  2173. };
  2174. const runOnSourceName = name => {
  2175. return handler => ({
  2176. key: name,
  2177. value: nu$9({
  2178. run: (component, simulatedEvent) => {
  2179. if (isSource(component, simulatedEvent)) {
  2180. handler(component, simulatedEvent);
  2181. }
  2182. }
  2183. })
  2184. });
  2185. };
  2186. const redirectToUid = (name, uid) => {
  2187. return run$1(name, (component, simulatedEvent) => {
  2188. component.getSystem().getByUid(uid).each(redirectee => {
  2189. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2190. });
  2191. });
  2192. };
  2193. const redirectToPart = (name, detail, partName) => {
  2194. const uid = detail.partUids[partName];
  2195. return redirectToUid(name, uid);
  2196. };
  2197. const runWithTarget = (name, f) => {
  2198. return run$1(name, (component, simulatedEvent) => {
  2199. const ev = simulatedEvent.event;
  2200. const target = component.getSystem().getByDom(ev.target).getOrThunk(() => {
  2201. const closest = closest$4(ev.target, el => component.getSystem().getByDom(el).toOptional(), never);
  2202. return closest.getOr(component);
  2203. });
  2204. f(component, target, simulatedEvent);
  2205. });
  2206. };
  2207. const cutter = name => {
  2208. return run$1(name, (component, simulatedEvent) => {
  2209. simulatedEvent.cut();
  2210. });
  2211. };
  2212. const stopper = name => {
  2213. return run$1(name, (component, simulatedEvent) => {
  2214. simulatedEvent.stop();
  2215. });
  2216. };
  2217. const runOnSource = (name, f) => {
  2218. return runOnSourceName(name)(f);
  2219. };
  2220. const runOnAttached = runOnSourceName(attachedToDom());
  2221. const runOnDetached = runOnSourceName(detachedFromDom());
  2222. const runOnInit = runOnSourceName(systemInit());
  2223. const runOnExecute$1 = runOnName(execute$5());
  2224. const fromHtml$1 = (html, scope) => {
  2225. const doc = scope || document;
  2226. const div = doc.createElement('div');
  2227. div.innerHTML = html;
  2228. return children(SugarElement.fromDom(div));
  2229. };
  2230. const get$9 = element => element.dom.innerHTML;
  2231. const set$6 = (element, content) => {
  2232. const owner = owner$4(element);
  2233. const docDom = owner.dom;
  2234. const fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2235. const contentElements = fromHtml$1(content, docDom);
  2236. append$1(fragment, contentElements);
  2237. empty(element);
  2238. append$2(element, fragment);
  2239. };
  2240. const getOuter = element => {
  2241. const container = SugarElement.fromTag('div');
  2242. const clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2243. append$2(container, clone);
  2244. return get$9(container);
  2245. };
  2246. const clone = (original, isDeep) => SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2247. const shallow = original => clone(original, false);
  2248. const getHtml = element => {
  2249. if (isShadowRoot(element)) {
  2250. return '#shadow-root';
  2251. } else {
  2252. const clone = shallow(element);
  2253. return getOuter(clone);
  2254. }
  2255. };
  2256. const element = elem => getHtml(elem);
  2257. const isRecursive = (component, originator, target) => eq(originator, component.element) && !eq(originator, target);
  2258. const events$i = derive$2([can(focus$4(), (component, simulatedEvent) => {
  2259. const event = simulatedEvent.event;
  2260. const originator = event.originator;
  2261. const target = event.target;
  2262. if (isRecursive(component, originator, target)) {
  2263. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  2264. return false;
  2265. } else {
  2266. return true;
  2267. }
  2268. })]);
  2269. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2270. __proto__: null,
  2271. events: events$i
  2272. });
  2273. let unique = 0;
  2274. const generate$6 = prefix => {
  2275. const date = new Date();
  2276. const time = date.getTime();
  2277. const random = Math.floor(Math.random() * 1000000000);
  2278. unique++;
  2279. return prefix + '_' + random + unique + String(time);
  2280. };
  2281. const prefix$1 = constant$1('alloy-id-');
  2282. const idAttr$1 = constant$1('data-alloy-id');
  2283. const prefix = prefix$1();
  2284. const idAttr = idAttr$1();
  2285. const write = (label, elem) => {
  2286. const id = generate$6(prefix + label);
  2287. writeOnly(elem, id);
  2288. return id;
  2289. };
  2290. const writeOnly = (elem, uid) => {
  2291. Object.defineProperty(elem.dom, idAttr, {
  2292. value: uid,
  2293. writable: true
  2294. });
  2295. };
  2296. const read$1 = elem => {
  2297. const id = isElement$1(elem) ? elem.dom[idAttr] : null;
  2298. return Optional.from(id);
  2299. };
  2300. const generate$5 = prefix => generate$6(prefix);
  2301. const make$8 = identity;
  2302. const NoContextApi = getComp => {
  2303. const getMessage = event => `The component must be in a context to execute: ${ event }` + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  2304. const fail = event => () => {
  2305. throw new Error(getMessage(event));
  2306. };
  2307. const warn = event => () => {
  2308. console.warn(getMessage(event));
  2309. };
  2310. return {
  2311. debugInfo: constant$1('fake'),
  2312. triggerEvent: warn('triggerEvent'),
  2313. triggerFocus: warn('triggerFocus'),
  2314. triggerEscape: warn('triggerEscape'),
  2315. broadcast: warn('broadcast'),
  2316. broadcastOn: warn('broadcastOn'),
  2317. broadcastEvent: warn('broadcastEvent'),
  2318. build: fail('build'),
  2319. buildOrPatch: fail('buildOrPatch'),
  2320. addToWorld: fail('addToWorld'),
  2321. removeFromWorld: fail('removeFromWorld'),
  2322. addToGui: fail('addToGui'),
  2323. removeFromGui: fail('removeFromGui'),
  2324. getByUid: fail('getByUid'),
  2325. getByDom: fail('getByDom'),
  2326. isConnected: never
  2327. };
  2328. };
  2329. const singleton$1 = NoContextApi();
  2330. const markAsBehaviourApi = (f, apiName, apiFunction) => {
  2331. const delegate = apiFunction.toString();
  2332. const endIndex = delegate.indexOf(')') + 1;
  2333. const openBracketIndex = delegate.indexOf('(');
  2334. const parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2335. f.toFunctionAnnotation = () => ({
  2336. name: apiName,
  2337. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2338. });
  2339. return f;
  2340. };
  2341. const cleanParameters = parameters => map$2(parameters, p => endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p);
  2342. const markAsExtraApi = (f, extraName) => {
  2343. const delegate = f.toString();
  2344. const endIndex = delegate.indexOf(')') + 1;
  2345. const openBracketIndex = delegate.indexOf('(');
  2346. const parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2347. f.toFunctionAnnotation = () => ({
  2348. name: extraName,
  2349. parameters: cleanParameters(parameters)
  2350. });
  2351. return f;
  2352. };
  2353. const markAsSketchApi = (f, apiFunction) => {
  2354. const delegate = apiFunction.toString();
  2355. const endIndex = delegate.indexOf(')') + 1;
  2356. const openBracketIndex = delegate.indexOf('(');
  2357. const parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2358. f.toFunctionAnnotation = () => ({
  2359. name: 'OVERRIDE',
  2360. parameters: cleanParameters(parameters.slice(1))
  2361. });
  2362. return f;
  2363. };
  2364. const premadeTag = generate$6('alloy-premade');
  2365. const premade$1 = comp => {
  2366. Object.defineProperty(comp.element.dom, premadeTag, {
  2367. value: comp.uid,
  2368. writable: true
  2369. });
  2370. return wrap$1(premadeTag, comp);
  2371. };
  2372. const isPremade = element => has$2(element.dom, premadeTag);
  2373. const getPremade = spec => get$g(spec, premadeTag);
  2374. const makeApi = f => markAsSketchApi((component, ...rest) => f(component.getApis(), component, ...rest), f);
  2375. const NoState = { init: () => nu$8({ readState: constant$1('No State required') }) };
  2376. const nu$8 = spec => spec;
  2377. const generateFrom$1 = (spec, all) => {
  2378. const schema = map$2(all, a => optionObjOf(a.name(), [
  2379. required$1('config'),
  2380. defaulted('state', NoState)
  2381. ]));
  2382. const validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(errInfo => {
  2383. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2384. }, identity);
  2385. return {
  2386. list: all,
  2387. data: map$1(validated, optBlobThunk => {
  2388. const output = optBlobThunk.map(blob => ({
  2389. config: blob.config,
  2390. state: blob.state.init(blob.config)
  2391. }));
  2392. return constant$1(output);
  2393. })
  2394. };
  2395. };
  2396. const getBehaviours$3 = bData => bData.list;
  2397. const getData$2 = bData => bData.data;
  2398. const byInnerKey = (data, tuple) => {
  2399. const r = {};
  2400. each(data, (detail, key) => {
  2401. each(detail, (value, indexKey) => {
  2402. const chain = get$g(r, indexKey).getOr([]);
  2403. r[indexKey] = chain.concat([tuple(key, value)]);
  2404. });
  2405. });
  2406. return r;
  2407. };
  2408. const nu$7 = s => ({
  2409. classes: isUndefined(s.classes) ? [] : s.classes,
  2410. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  2411. styles: isUndefined(s.styles) ? {} : s.styles
  2412. });
  2413. const merge = (defnA, mod) => ({
  2414. ...defnA,
  2415. attributes: {
  2416. ...defnA.attributes,
  2417. ...mod.attributes
  2418. },
  2419. styles: {
  2420. ...defnA.styles,
  2421. ...mod.styles
  2422. },
  2423. classes: defnA.classes.concat(mod.classes)
  2424. });
  2425. const combine$2 = (info, baseMod, behaviours, base) => {
  2426. const modsByBehaviour = { ...baseMod };
  2427. each$1(behaviours, behaviour => {
  2428. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2429. });
  2430. const byAspect = byInnerKey(modsByBehaviour, (name, modification) => ({
  2431. name,
  2432. modification
  2433. }));
  2434. const combineObjects = objects => foldr(objects, (b, a) => ({
  2435. ...a.modification,
  2436. ...b
  2437. }), {});
  2438. const combinedClasses = foldr(byAspect.classes, (b, a) => a.modification.concat(b), []);
  2439. const combinedAttributes = combineObjects(byAspect.attributes);
  2440. const combinedStyles = combineObjects(byAspect.styles);
  2441. return nu$7({
  2442. classes: combinedClasses,
  2443. attributes: combinedAttributes,
  2444. styles: combinedStyles
  2445. });
  2446. };
  2447. const sortKeys = (label, keyName, array, order) => {
  2448. try {
  2449. const sorted = sort(array, (a, b) => {
  2450. const aKey = a[keyName];
  2451. const bKey = b[keyName];
  2452. const aIndex = order.indexOf(aKey);
  2453. const bIndex = order.indexOf(bKey);
  2454. if (aIndex === -1) {
  2455. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2456. }
  2457. if (bIndex === -1) {
  2458. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2459. }
  2460. if (aIndex < bIndex) {
  2461. return -1;
  2462. } else if (bIndex < aIndex) {
  2463. return 1;
  2464. } else {
  2465. return 0;
  2466. }
  2467. });
  2468. return Result.value(sorted);
  2469. } catch (err) {
  2470. return Result.error([err]);
  2471. }
  2472. };
  2473. const uncurried = (handler, purpose) => ({
  2474. handler,
  2475. purpose
  2476. });
  2477. const curried = (handler, purpose) => ({
  2478. cHandler: handler,
  2479. purpose
  2480. });
  2481. const curryArgs = (descHandler, extraArgs) => curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  2482. const getCurried = descHandler => descHandler.cHandler;
  2483. const behaviourTuple = (name, handler) => ({
  2484. name,
  2485. handler
  2486. });
  2487. const nameToHandlers = (behaviours, info) => {
  2488. const r = {};
  2489. each$1(behaviours, behaviour => {
  2490. r[behaviour.name()] = behaviour.handlers(info);
  2491. });
  2492. return r;
  2493. };
  2494. const groupByEvents = (info, behaviours, base) => {
  2495. const behaviourEvents = {
  2496. ...base,
  2497. ...nameToHandlers(behaviours, info)
  2498. };
  2499. return byInnerKey(behaviourEvents, behaviourTuple);
  2500. };
  2501. const combine$1 = (info, eventOrder, behaviours, base) => {
  2502. const byEventName = groupByEvents(info, behaviours, base);
  2503. return combineGroups(byEventName, eventOrder);
  2504. };
  2505. const assemble = rawHandler => {
  2506. const handler = read$2(rawHandler);
  2507. return (component, simulatedEvent, ...rest) => {
  2508. const args = [
  2509. component,
  2510. simulatedEvent
  2511. ].concat(rest);
  2512. if (handler.abort.apply(undefined, args)) {
  2513. simulatedEvent.stop();
  2514. } else if (handler.can.apply(undefined, args)) {
  2515. handler.run.apply(undefined, args);
  2516. }
  2517. };
  2518. };
  2519. const missingOrderError = (eventName, tuples) => Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map$2(tuples, c => c.name), null, 2)]);
  2520. const fuse = (tuples, eventOrder, eventName) => {
  2521. const order = eventOrder[eventName];
  2522. if (!order) {
  2523. return missingOrderError(eventName, tuples);
  2524. } else {
  2525. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(sortedTuples => {
  2526. const handlers = map$2(sortedTuples, tuple => tuple.handler);
  2527. return fuse$1(handlers);
  2528. });
  2529. }
  2530. };
  2531. const combineGroups = (byEventName, eventOrder) => {
  2532. const r = mapToArray(byEventName, (tuples, eventName) => {
  2533. const combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  2534. return combined.map(handler => {
  2535. const assembled = assemble(handler);
  2536. const purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], o => exists(tuples, t => t.name === o)).join(' > ') : tuples[0].name;
  2537. return wrap$1(eventName, uncurried(assembled, purpose));
  2538. });
  2539. });
  2540. return consolidate(r, {});
  2541. };
  2542. const baseBehaviour = 'alloy.base.behaviour';
  2543. const schema$z = objOf([
  2544. field$1('dom', 'dom', required$2(), objOf([
  2545. required$1('tag'),
  2546. defaulted('styles', {}),
  2547. defaulted('classes', []),
  2548. defaulted('attributes', {}),
  2549. option$3('value'),
  2550. option$3('innerHtml')
  2551. ])),
  2552. required$1('components'),
  2553. required$1('uid'),
  2554. defaulted('events', {}),
  2555. defaulted('apis', {}),
  2556. field$1('eventOrder', 'eventOrder', mergeWith({
  2557. [execute$5()]: [
  2558. 'disabling',
  2559. baseBehaviour,
  2560. 'toggling',
  2561. 'typeaheadevents'
  2562. ],
  2563. [focus$4()]: [
  2564. baseBehaviour,
  2565. 'focusing',
  2566. 'keying'
  2567. ],
  2568. [systemInit()]: [
  2569. baseBehaviour,
  2570. 'disabling',
  2571. 'toggling',
  2572. 'representing'
  2573. ],
  2574. [input()]: [
  2575. baseBehaviour,
  2576. 'representing',
  2577. 'streaming',
  2578. 'invalidating'
  2579. ],
  2580. [detachedFromDom()]: [
  2581. baseBehaviour,
  2582. 'representing',
  2583. 'item-events',
  2584. 'tooltipping'
  2585. ],
  2586. [mousedown()]: [
  2587. 'focusing',
  2588. baseBehaviour,
  2589. 'item-type-events'
  2590. ],
  2591. [touchstart()]: [
  2592. 'focusing',
  2593. baseBehaviour,
  2594. 'item-type-events'
  2595. ],
  2596. [mouseover()]: [
  2597. 'item-type-events',
  2598. 'tooltipping'
  2599. ],
  2600. [receive()]: [
  2601. 'receiving',
  2602. 'reflecting',
  2603. 'tooltipping'
  2604. ]
  2605. }), anyValue()),
  2606. option$3('domModification')
  2607. ]);
  2608. const toInfo = spec => asRaw('custom.definition', schema$z, spec);
  2609. const toDefinition = detail => ({
  2610. ...detail.dom,
  2611. uid: detail.uid,
  2612. domChildren: map$2(detail.components, comp => comp.element)
  2613. });
  2614. const toModification = detail => detail.domModification.fold(() => nu$7({}), nu$7);
  2615. const toEvents = info => info.events;
  2616. const read = (element, attr) => {
  2617. const value = get$f(element, attr);
  2618. return value === undefined || value === '' ? [] : value.split(' ');
  2619. };
  2620. const add$4 = (element, attr, id) => {
  2621. const old = read(element, attr);
  2622. const nu = old.concat([id]);
  2623. set$9(element, attr, nu.join(' '));
  2624. return true;
  2625. };
  2626. const remove$4 = (element, attr, id) => {
  2627. const nu = filter$2(read(element, attr), v => v !== id);
  2628. if (nu.length > 0) {
  2629. set$9(element, attr, nu.join(' '));
  2630. } else {
  2631. remove$7(element, attr);
  2632. }
  2633. return false;
  2634. };
  2635. const supports = element => element.dom.classList !== undefined;
  2636. const get$8 = element => read(element, 'class');
  2637. const add$3 = (element, clazz) => add$4(element, 'class', clazz);
  2638. const remove$3 = (element, clazz) => remove$4(element, 'class', clazz);
  2639. const add$2 = (element, clazz) => {
  2640. if (supports(element)) {
  2641. element.dom.classList.add(clazz);
  2642. } else {
  2643. add$3(element, clazz);
  2644. }
  2645. };
  2646. const cleanClass = element => {
  2647. const classList = supports(element) ? element.dom.classList : get$8(element);
  2648. if (classList.length === 0) {
  2649. remove$7(element, 'class');
  2650. }
  2651. };
  2652. const remove$2 = (element, clazz) => {
  2653. if (supports(element)) {
  2654. const classList = element.dom.classList;
  2655. classList.remove(clazz);
  2656. } else {
  2657. remove$3(element, clazz);
  2658. }
  2659. cleanClass(element);
  2660. };
  2661. const has = (element, clazz) => supports(element) && element.dom.classList.contains(clazz);
  2662. const add$1 = (element, classes) => {
  2663. each$1(classes, x => {
  2664. add$2(element, x);
  2665. });
  2666. };
  2667. const remove$1 = (element, classes) => {
  2668. each$1(classes, x => {
  2669. remove$2(element, x);
  2670. });
  2671. };
  2672. const hasAll = (element, classes) => forall(classes, clazz => has(element, clazz));
  2673. const getNative = element => {
  2674. const classList = element.dom.classList;
  2675. const r = new Array(classList.length);
  2676. for (let i = 0; i < classList.length; i++) {
  2677. const item = classList.item(i);
  2678. if (item !== null) {
  2679. r[i] = item;
  2680. }
  2681. }
  2682. return r;
  2683. };
  2684. const get$7 = element => supports(element) ? getNative(element) : get$8(element);
  2685. const get$6 = element => element.dom.value;
  2686. const set$5 = (element, value) => {
  2687. if (value === undefined) {
  2688. throw new Error('Value.set was undefined');
  2689. }
  2690. element.dom.value = value;
  2691. };
  2692. const determineObsoleted = (parent, index, oldObsoleted) => {
  2693. const newObsoleted = child$2(parent, index);
  2694. return newObsoleted.map(newObs => {
  2695. const elemChanged = oldObsoleted.exists(o => !eq(o, newObs));
  2696. if (elemChanged) {
  2697. const oldTag = oldObsoleted.map(name$3).getOr('span');
  2698. const marker = SugarElement.fromTag(oldTag);
  2699. before$1(newObs, marker);
  2700. return marker;
  2701. } else {
  2702. return newObs;
  2703. }
  2704. });
  2705. };
  2706. const ensureInDom = (parent, child, obsoleted) => {
  2707. obsoleted.fold(() => append$2(parent, child), obs => {
  2708. if (!eq(obs, child)) {
  2709. before$1(obs, child);
  2710. remove$5(obs);
  2711. }
  2712. });
  2713. };
  2714. const patchChildrenWith = (parent, nu, f) => {
  2715. const builtChildren = map$2(nu, f);
  2716. const currentChildren = children(parent);
  2717. each$1(currentChildren.slice(builtChildren.length), remove$5);
  2718. return builtChildren;
  2719. };
  2720. const patchSpecChild = (parent, index, spec, build) => {
  2721. const oldObsoleted = child$2(parent, index);
  2722. const childComp = build(spec, oldObsoleted);
  2723. const obsoleted = determineObsoleted(parent, index, oldObsoleted);
  2724. ensureInDom(parent, childComp.element, obsoleted);
  2725. return childComp;
  2726. };
  2727. const patchSpecChildren = (parent, specs, build) => patchChildrenWith(parent, specs, (spec, index) => patchSpecChild(parent, index, spec, build));
  2728. const patchDomChildren = (parent, nodes) => patchChildrenWith(parent, nodes, (node, index) => {
  2729. const optObsoleted = child$2(parent, index);
  2730. ensureInDom(parent, node, optObsoleted);
  2731. return node;
  2732. });
  2733. const diffKeyValueSet = (newObj, oldObj) => {
  2734. const newKeys = keys(newObj);
  2735. const oldKeys = keys(oldObj);
  2736. const toRemove = difference(oldKeys, newKeys);
  2737. const toSet = bifilter(newObj, (v, k) => {
  2738. return !has$2(oldObj, k) || v !== oldObj[k];
  2739. }).t;
  2740. return {
  2741. toRemove,
  2742. toSet
  2743. };
  2744. };
  2745. const reconcileToDom = (definition, obsoleted) => {
  2746. const {
  2747. class: clazz,
  2748. style,
  2749. ...existingAttributes
  2750. } = clone$1(obsoleted);
  2751. const {
  2752. toSet: attrsToSet,
  2753. toRemove: attrsToRemove
  2754. } = diffKeyValueSet(definition.attributes, existingAttributes);
  2755. const updateAttrs = () => {
  2756. each$1(attrsToRemove, a => remove$7(obsoleted, a));
  2757. setAll$1(obsoleted, attrsToSet);
  2758. };
  2759. const existingStyles = getAllRaw(obsoleted);
  2760. const {
  2761. toSet: stylesToSet,
  2762. toRemove: stylesToRemove
  2763. } = diffKeyValueSet(definition.styles, existingStyles);
  2764. const updateStyles = () => {
  2765. each$1(stylesToRemove, s => remove$6(obsoleted, s));
  2766. setAll(obsoleted, stylesToSet);
  2767. };
  2768. const existingClasses = get$7(obsoleted);
  2769. const classesToRemove = difference(existingClasses, definition.classes);
  2770. const classesToAdd = difference(definition.classes, existingClasses);
  2771. const updateClasses = () => {
  2772. add$1(obsoleted, classesToAdd);
  2773. remove$1(obsoleted, classesToRemove);
  2774. };
  2775. const updateHtml = html => {
  2776. set$6(obsoleted, html);
  2777. };
  2778. const updateChildren = () => {
  2779. const children = definition.domChildren;
  2780. patchDomChildren(obsoleted, children);
  2781. };
  2782. const updateValue = () => {
  2783. const valueElement = obsoleted;
  2784. definition.value.filter(value => value !== get$6(valueElement)).each(value => set$5(valueElement, value));
  2785. };
  2786. updateAttrs();
  2787. updateClasses();
  2788. updateStyles();
  2789. definition.innerHtml.fold(updateChildren, updateHtml);
  2790. updateValue();
  2791. return obsoleted;
  2792. };
  2793. const introduceToDom = definition => {
  2794. const subject = SugarElement.fromTag(definition.tag);
  2795. setAll$1(subject, definition.attributes);
  2796. add$1(subject, definition.classes);
  2797. setAll(subject, definition.styles);
  2798. definition.innerHtml.each(html => set$6(subject, html));
  2799. const children = definition.domChildren;
  2800. append$1(subject, children);
  2801. definition.value.each(value => {
  2802. set$5(subject, value);
  2803. });
  2804. return subject;
  2805. };
  2806. const attemptPatch = (definition, obsoleted) => {
  2807. try {
  2808. const e = reconcileToDom(definition, obsoleted);
  2809. return Optional.some(e);
  2810. } catch (err) {
  2811. return Optional.none();
  2812. }
  2813. };
  2814. const hasMixedChildren = definition => definition.innerHtml.isSome() && definition.domChildren.length > 0;
  2815. const renderToDom = (definition, optObsoleted) => {
  2816. const canBePatched = candidate => name$3(candidate) === definition.tag && !hasMixedChildren(definition) && !isPremade(candidate);
  2817. const elem = optObsoleted.filter(canBePatched).bind(obsoleted => attemptPatch(definition, obsoleted)).getOrThunk(() => introduceToDom(definition));
  2818. writeOnly(elem, definition.uid);
  2819. return elem;
  2820. };
  2821. const getBehaviours$2 = spec => {
  2822. const behaviours = get$g(spec, 'behaviours').getOr({});
  2823. return bind$3(keys(behaviours), name => {
  2824. const behaviour = behaviours[name];
  2825. return isNonNullable(behaviour) ? [behaviour.me] : [];
  2826. });
  2827. };
  2828. const generateFrom = (spec, all) => generateFrom$1(spec, all);
  2829. const generate$4 = spec => {
  2830. const all = getBehaviours$2(spec);
  2831. return generateFrom(spec, all);
  2832. };
  2833. const getDomDefinition = (info, bList, bData) => {
  2834. const definition = toDefinition(info);
  2835. const infoModification = toModification(info);
  2836. const baseModification = { 'alloy.base.modification': infoModification };
  2837. const modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
  2838. return merge(definition, modification);
  2839. };
  2840. const getEvents = (info, bList, bData) => {
  2841. const baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  2842. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  2843. };
  2844. const build$2 = (spec, obsoleted) => {
  2845. const getMe = () => me;
  2846. const systemApi = Cell(singleton$1);
  2847. const info = getOrDie(toInfo(spec));
  2848. const bBlob = generate$4(spec);
  2849. const bList = getBehaviours$3(bBlob);
  2850. const bData = getData$2(bBlob);
  2851. const modDefinition = getDomDefinition(info, bList, bData);
  2852. const item = renderToDom(modDefinition, obsoleted);
  2853. const events = getEvents(info, bList, bData);
  2854. const subcomponents = Cell(info.components);
  2855. const connect = newApi => {
  2856. systemApi.set(newApi);
  2857. };
  2858. const disconnect = () => {
  2859. systemApi.set(NoContextApi(getMe));
  2860. };
  2861. const syncComponents = () => {
  2862. const children$1 = children(item);
  2863. const subs = bind$3(children$1, child => systemApi.get().getByDom(child).fold(() => [], pure$2));
  2864. subcomponents.set(subs);
  2865. };
  2866. const config = behaviour => {
  2867. const b = bData;
  2868. const f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : () => {
  2869. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  2870. };
  2871. return f();
  2872. };
  2873. const hasConfigured = behaviour => isFunction(bData[behaviour.name()]);
  2874. const getApis = () => info.apis;
  2875. const readState = behaviourName => bData[behaviourName]().map(b => b.state.readState()).getOr('not enabled');
  2876. const me = {
  2877. uid: spec.uid,
  2878. getSystem: systemApi.get,
  2879. config,
  2880. hasConfigured,
  2881. spec,
  2882. readState,
  2883. getApis,
  2884. connect,
  2885. disconnect,
  2886. element: item,
  2887. syncComponents,
  2888. components: subcomponents.get,
  2889. events
  2890. };
  2891. return me;
  2892. };
  2893. const buildSubcomponents = (spec, obsoleted) => {
  2894. const components = get$g(spec, 'components').getOr([]);
  2895. return obsoleted.fold(() => map$2(components, build$1), obs => map$2(components, (c, i) => {
  2896. return buildOrPatch(c, child$2(obs, i));
  2897. }));
  2898. };
  2899. const buildFromSpec = (userSpec, obsoleted) => {
  2900. const {
  2901. events: specEvents,
  2902. ...spec
  2903. } = make$8(userSpec);
  2904. const components = buildSubcomponents(spec, obsoleted);
  2905. const completeSpec = {
  2906. ...spec,
  2907. events: {
  2908. ...DefaultEvents,
  2909. ...specEvents
  2910. },
  2911. components
  2912. };
  2913. return Result.value(build$2(completeSpec, obsoleted));
  2914. };
  2915. const text$1 = textContent => {
  2916. const element = SugarElement.fromText(textContent);
  2917. return external$1({ element });
  2918. };
  2919. const external$1 = spec => {
  2920. const extSpec = asRawOrDie$1('external.component', objOfOnly([
  2921. required$1('element'),
  2922. option$3('uid')
  2923. ]), spec);
  2924. const systemApi = Cell(NoContextApi());
  2925. const connect = newApi => {
  2926. systemApi.set(newApi);
  2927. };
  2928. const disconnect = () => {
  2929. systemApi.set(NoContextApi(() => me));
  2930. };
  2931. const uid = extSpec.uid.getOrThunk(() => generate$5('external'));
  2932. writeOnly(extSpec.element, uid);
  2933. const me = {
  2934. uid,
  2935. getSystem: systemApi.get,
  2936. config: Optional.none,
  2937. hasConfigured: never,
  2938. connect,
  2939. disconnect,
  2940. getApis: () => ({}),
  2941. element: extSpec.element,
  2942. spec,
  2943. readState: constant$1('No state'),
  2944. syncComponents: noop,
  2945. components: constant$1([]),
  2946. events: {}
  2947. };
  2948. return premade$1(me);
  2949. };
  2950. const uids = generate$5;
  2951. const isSketchSpec$1 = spec => has$2(spec, 'uid');
  2952. const buildOrPatch = (spec, obsoleted) => getPremade(spec).getOrThunk(() => {
  2953. const userSpecWithUid = isSketchSpec$1(spec) ? spec : {
  2954. uid: uids(''),
  2955. ...spec
  2956. };
  2957. return buildFromSpec(userSpecWithUid, obsoleted).getOrDie();
  2958. });
  2959. const build$1 = spec => buildOrPatch(spec, Optional.none());
  2960. const premade = premade$1;
  2961. var ClosestOrAncestor = (is, ancestor, scope, a, isRoot) => {
  2962. if (is(scope, a)) {
  2963. return Optional.some(scope);
  2964. } else if (isFunction(isRoot) && isRoot(scope)) {
  2965. return Optional.none();
  2966. } else {
  2967. return ancestor(scope, a, isRoot);
  2968. }
  2969. };
  2970. const ancestor$1 = (scope, predicate, isRoot) => {
  2971. let element = scope.dom;
  2972. const stop = isFunction(isRoot) ? isRoot : never;
  2973. while (element.parentNode) {
  2974. element = element.parentNode;
  2975. const el = SugarElement.fromDom(element);
  2976. if (predicate(el)) {
  2977. return Optional.some(el);
  2978. } else if (stop(el)) {
  2979. break;
  2980. }
  2981. }
  2982. return Optional.none();
  2983. };
  2984. const closest$3 = (scope, predicate, isRoot) => {
  2985. const is = (s, test) => test(s);
  2986. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  2987. };
  2988. const child$1 = (scope, predicate) => {
  2989. const pred = node => predicate(SugarElement.fromDom(node));
  2990. const result = find$5(scope.dom.childNodes, pred);
  2991. return result.map(SugarElement.fromDom);
  2992. };
  2993. const descendant$1 = (scope, predicate) => {
  2994. const descend = node => {
  2995. for (let i = 0; i < node.childNodes.length; i++) {
  2996. const child = SugarElement.fromDom(node.childNodes[i]);
  2997. if (predicate(child)) {
  2998. return Optional.some(child);
  2999. }
  3000. const res = descend(node.childNodes[i]);
  3001. if (res.isSome()) {
  3002. return res;
  3003. }
  3004. }
  3005. return Optional.none();
  3006. };
  3007. return descend(scope.dom);
  3008. };
  3009. const closest$2 = (scope, predicate, isRoot) => closest$3(scope, predicate, isRoot).isSome();
  3010. const ancestor = (scope, selector, isRoot) => ancestor$1(scope, e => is(e, selector), isRoot);
  3011. const child = (scope, selector) => child$1(scope, e => is(e, selector));
  3012. const descendant = (scope, selector) => one(selector, scope);
  3013. const closest$1 = (scope, selector, isRoot) => {
  3014. const is$1 = (element, selector) => is(element, selector);
  3015. return ClosestOrAncestor(is$1, ancestor, scope, selector, isRoot);
  3016. };
  3017. const attribute = 'aria-controls';
  3018. const find$1 = queryElem => {
  3019. const dependent = closest$3(queryElem, elem => {
  3020. if (!isElement$1(elem)) {
  3021. return false;
  3022. }
  3023. const id = get$f(elem, 'id');
  3024. return id !== undefined && id.indexOf(attribute) > -1;
  3025. });
  3026. return dependent.bind(dep => {
  3027. const id = get$f(dep, 'id');
  3028. const dos = getRootNode(dep);
  3029. return descendant(dos, `[${ attribute }="${ id }"]`);
  3030. });
  3031. };
  3032. const manager = () => {
  3033. const ariaId = generate$6(attribute);
  3034. const link = elem => {
  3035. set$9(elem, attribute, ariaId);
  3036. };
  3037. const unlink = elem => {
  3038. remove$7(elem, attribute);
  3039. };
  3040. return {
  3041. id: ariaId,
  3042. link,
  3043. unlink
  3044. };
  3045. };
  3046. const isAriaPartOf = (component, queryElem) => find$1(queryElem).exists(owner => isPartOf$1(component, owner));
  3047. const isPartOf$1 = (component, queryElem) => closest$2(queryElem, el => eq(el, component.element), never) || isAriaPartOf(component, queryElem);
  3048. const unknown = 'unknown';
  3049. var EventConfiguration;
  3050. (function (EventConfiguration) {
  3051. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3052. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3053. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3054. }(EventConfiguration || (EventConfiguration = {})));
  3055. const eventConfig = Cell({});
  3056. const makeEventLogger = (eventName, initialTarget) => {
  3057. const sequence = [];
  3058. const startTime = new Date().getTime();
  3059. return {
  3060. logEventCut: (_name, target, purpose) => {
  3061. sequence.push({
  3062. outcome: 'cut',
  3063. target,
  3064. purpose
  3065. });
  3066. },
  3067. logEventStopped: (_name, target, purpose) => {
  3068. sequence.push({
  3069. outcome: 'stopped',
  3070. target,
  3071. purpose
  3072. });
  3073. },
  3074. logNoParent: (_name, target, purpose) => {
  3075. sequence.push({
  3076. outcome: 'no-parent',
  3077. target,
  3078. purpose
  3079. });
  3080. },
  3081. logEventNoHandlers: (_name, target) => {
  3082. sequence.push({
  3083. outcome: 'no-handlers-left',
  3084. target
  3085. });
  3086. },
  3087. logEventResponse: (_name, target, purpose) => {
  3088. sequence.push({
  3089. outcome: 'response',
  3090. purpose,
  3091. target
  3092. });
  3093. },
  3094. write: () => {
  3095. const finishTime = new Date().getTime();
  3096. if (contains$2([
  3097. 'mousemove',
  3098. 'mouseover',
  3099. 'mouseout',
  3100. systemInit()
  3101. ], eventName)) {
  3102. return;
  3103. }
  3104. console.log(eventName, {
  3105. event: eventName,
  3106. time: finishTime - startTime,
  3107. target: initialTarget.dom,
  3108. sequence: map$2(sequence, s => {
  3109. if (!contains$2([
  3110. 'cut',
  3111. 'stopped',
  3112. 'response'
  3113. ], s.outcome)) {
  3114. return s.outcome;
  3115. } else {
  3116. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3117. }
  3118. })
  3119. });
  3120. }
  3121. };
  3122. };
  3123. const processEvent = (eventName, initialTarget, f) => {
  3124. const status = get$g(eventConfig.get(), eventName).orThunk(() => {
  3125. const patterns = keys(eventConfig.get());
  3126. return findMap(patterns, p => eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none());
  3127. }).getOr(EventConfiguration.NORMAL);
  3128. switch (status) {
  3129. case EventConfiguration.NORMAL:
  3130. return f(noLogger());
  3131. case EventConfiguration.LOGGING: {
  3132. const logger = makeEventLogger(eventName, initialTarget);
  3133. const output = f(logger);
  3134. logger.write();
  3135. return output;
  3136. }
  3137. case EventConfiguration.STOP:
  3138. return true;
  3139. }
  3140. };
  3141. const path = [
  3142. 'alloy/data/Fields',
  3143. 'alloy/debugging/Debugging'
  3144. ];
  3145. const getTrace = () => {
  3146. const err = new Error();
  3147. if (err.stack !== undefined) {
  3148. const lines = err.stack.split('\n');
  3149. return find$5(lines, line => line.indexOf('alloy') > 0 && !exists(path, p => line.indexOf(p) > -1)).getOr(unknown);
  3150. } else {
  3151. return unknown;
  3152. }
  3153. };
  3154. const ignoreEvent = {
  3155. logEventCut: noop,
  3156. logEventStopped: noop,
  3157. logNoParent: noop,
  3158. logEventNoHandlers: noop,
  3159. logEventResponse: noop,
  3160. write: noop
  3161. };
  3162. const monitorEvent = (eventName, initialTarget, f) => processEvent(eventName, initialTarget, f);
  3163. const noLogger = constant$1(ignoreEvent);
  3164. const menuFields = constant$1([
  3165. required$1('menu'),
  3166. required$1('selectedMenu')
  3167. ]);
  3168. const itemFields = constant$1([
  3169. required$1('item'),
  3170. required$1('selectedItem')
  3171. ]);
  3172. constant$1(objOf(itemFields().concat(menuFields())));
  3173. const itemSchema$3 = constant$1(objOf(itemFields()));
  3174. const _initSize = requiredObjOf('initSize', [
  3175. required$1('numColumns'),
  3176. required$1('numRows')
  3177. ]);
  3178. const itemMarkers = () => requiredOf('markers', itemSchema$3());
  3179. const tieredMenuMarkers = () => requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3180. const markers$1 = required => requiredObjOf('markers', map$2(required, required$1));
  3181. const onPresenceHandler = (label, fieldName, presence) => {
  3182. getTrace();
  3183. return field$1(fieldName, fieldName, presence, valueOf(f => Result.value((...args) => {
  3184. return f.apply(undefined, args);
  3185. })));
  3186. };
  3187. const onHandler = fieldName => onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  3188. const onKeyboardHandler = fieldName => onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  3189. const onStrictHandler = fieldName => onPresenceHandler('onHandler', fieldName, required$2());
  3190. const onStrictKeyboardHandler = fieldName => onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  3191. const output$1 = (name, value) => customField(name, constant$1(value));
  3192. const snapshot = name => customField(name, identity);
  3193. const initSize = constant$1(_initSize);
  3194. const nu$6 = (x, y, bubble, direction, placement, boundsRestriction, labelPrefix, alwaysFit = false) => ({
  3195. x,
  3196. y,
  3197. bubble,
  3198. direction,
  3199. placement,
  3200. restriction: boundsRestriction,
  3201. label: `${ labelPrefix }-${ placement }`,
  3202. alwaysFit
  3203. });
  3204. const adt$a = Adt.generate([
  3205. { southeast: [] },
  3206. { southwest: [] },
  3207. { northeast: [] },
  3208. { northwest: [] },
  3209. { south: [] },
  3210. { north: [] },
  3211. { east: [] },
  3212. { west: [] }
  3213. ]);
  3214. const cata$2 = (subject, southeast, southwest, northeast, northwest, south, north, east, west) => subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3215. const cataVertical = (subject, south, middle, north) => subject.fold(south, south, north, north, south, north, middle, middle);
  3216. const cataHorizontal = (subject, east, middle, west) => subject.fold(east, west, east, west, middle, middle, east, west);
  3217. const southeast$3 = adt$a.southeast;
  3218. const southwest$3 = adt$a.southwest;
  3219. const northeast$3 = adt$a.northeast;
  3220. const northwest$3 = adt$a.northwest;
  3221. const south$3 = adt$a.south;
  3222. const north$3 = adt$a.north;
  3223. const east$3 = adt$a.east;
  3224. const west$3 = adt$a.west;
  3225. const cycleBy = (value, delta, min, max) => {
  3226. const r = value + delta;
  3227. if (r > max) {
  3228. return min;
  3229. } else if (r < min) {
  3230. return max;
  3231. } else {
  3232. return r;
  3233. }
  3234. };
  3235. const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
  3236. const getRestriction = (anchor, restriction) => {
  3237. switch (restriction) {
  3238. case 1:
  3239. return anchor.x;
  3240. case 0:
  3241. return anchor.x + anchor.width;
  3242. case 2:
  3243. return anchor.y;
  3244. case 3:
  3245. return anchor.y + anchor.height;
  3246. }
  3247. };
  3248. const boundsRestriction = (anchor, restrictions) => mapToObject([
  3249. 'left',
  3250. 'right',
  3251. 'top',
  3252. 'bottom'
  3253. ], dir => get$g(restrictions, dir).map(restriction => getRestriction(anchor, restriction)));
  3254. const adjustBounds = (bounds$1, restriction, bubbleOffset) => {
  3255. const applyRestriction = (dir, current) => restriction[dir].map(pos => {
  3256. const isVerticalAxis = dir === 'top' || dir === 'bottom';
  3257. const offset = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
  3258. const comparator = dir === 'left' || dir === 'top' ? Math.max : Math.min;
  3259. const newPos = comparator(pos, current) + offset;
  3260. return isVerticalAxis ? clamp(newPos, bounds$1.y, bounds$1.bottom) : clamp(newPos, bounds$1.x, bounds$1.right);
  3261. }).getOr(current);
  3262. const adjustedLeft = applyRestriction('left', bounds$1.x);
  3263. const adjustedTop = applyRestriction('top', bounds$1.y);
  3264. const adjustedRight = applyRestriction('right', bounds$1.right);
  3265. const adjustedBottom = applyRestriction('bottom', bounds$1.bottom);
  3266. return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  3267. };
  3268. const labelPrefix$2 = 'layout';
  3269. const eastX$1 = anchor => anchor.x;
  3270. const middleX$1 = (anchor, element) => anchor.x + anchor.width / 2 - element.width / 2;
  3271. const westX$1 = (anchor, element) => anchor.x + anchor.width - element.width;
  3272. const northY$2 = (anchor, element) => anchor.y - element.height;
  3273. const southY$2 = anchor => anchor.y + anchor.height;
  3274. const centreY$1 = (anchor, element) => anchor.y + anchor.height / 2 - element.height / 2;
  3275. const eastEdgeX$1 = anchor => anchor.x + anchor.width;
  3276. const westEdgeX$1 = (anchor, element) => anchor.x - element.width;
  3277. const southeast$2 = (anchor, element, bubbles) => nu$6(eastX$1(anchor), southY$2(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  3278. left: 1,
  3279. top: 3
  3280. }), labelPrefix$2);
  3281. const southwest$2 = (anchor, element, bubbles) => nu$6(westX$1(anchor, element), southY$2(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  3282. right: 0,
  3283. top: 3
  3284. }), labelPrefix$2);
  3285. const northeast$2 = (anchor, element, bubbles) => nu$6(eastX$1(anchor), northY$2(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  3286. left: 1,
  3287. bottom: 2
  3288. }), labelPrefix$2);
  3289. const northwest$2 = (anchor, element, bubbles) => nu$6(westX$1(anchor, element), northY$2(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  3290. right: 0,
  3291. bottom: 2
  3292. }), labelPrefix$2);
  3293. const north$2 = (anchor, element, bubbles) => nu$6(middleX$1(anchor, element), northY$2(anchor, element), bubbles.north(), north$3(), 'north', boundsRestriction(anchor, { bottom: 2 }), labelPrefix$2);
  3294. const south$2 = (anchor, element, bubbles) => nu$6(middleX$1(anchor, element), southY$2(anchor), bubbles.south(), south$3(), 'south', boundsRestriction(anchor, { top: 3 }), labelPrefix$2);
  3295. const east$2 = (anchor, element, bubbles) => nu$6(eastEdgeX$1(anchor), centreY$1(anchor, element), bubbles.east(), east$3(), 'east', boundsRestriction(anchor, { left: 0 }), labelPrefix$2);
  3296. const west$2 = (anchor, element, bubbles) => nu$6(westEdgeX$1(anchor, element), centreY$1(anchor, element), bubbles.west(), west$3(), 'west', boundsRestriction(anchor, { right: 1 }), labelPrefix$2);
  3297. const all$1 = () => [
  3298. southeast$2,
  3299. southwest$2,
  3300. northeast$2,
  3301. northwest$2,
  3302. south$2,
  3303. north$2,
  3304. east$2,
  3305. west$2
  3306. ];
  3307. const allRtl$1 = () => [
  3308. southwest$2,
  3309. southeast$2,
  3310. northwest$2,
  3311. northeast$2,
  3312. south$2,
  3313. north$2,
  3314. east$2,
  3315. west$2
  3316. ];
  3317. const aboveOrBelow = () => [
  3318. northeast$2,
  3319. northwest$2,
  3320. southeast$2,
  3321. southwest$2,
  3322. north$2,
  3323. south$2
  3324. ];
  3325. const aboveOrBelowRtl = () => [
  3326. northwest$2,
  3327. northeast$2,
  3328. southwest$2,
  3329. southeast$2,
  3330. north$2,
  3331. south$2
  3332. ];
  3333. const belowOrAbove = () => [
  3334. southeast$2,
  3335. southwest$2,
  3336. northeast$2,
  3337. northwest$2,
  3338. south$2,
  3339. north$2
  3340. ];
  3341. const belowOrAboveRtl = () => [
  3342. southwest$2,
  3343. southeast$2,
  3344. northwest$2,
  3345. northeast$2,
  3346. south$2,
  3347. north$2
  3348. ];
  3349. const chooseChannels = (channels, message) => message.universal ? channels : filter$2(channels, ch => contains$2(message.channels, ch));
  3350. const events$h = receiveConfig => derive$2([run$1(receive(), (component, message) => {
  3351. const channelMap = receiveConfig.channels;
  3352. const channels = keys(channelMap);
  3353. const receivingData = message;
  3354. const targetChannels = chooseChannels(channels, receivingData);
  3355. each$1(targetChannels, ch => {
  3356. const channelInfo = channelMap[ch];
  3357. const channelSchema = channelInfo.schema;
  3358. const data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  3359. channelInfo.onReceive(component, data);
  3360. });
  3361. })]);
  3362. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3363. __proto__: null,
  3364. events: events$h
  3365. });
  3366. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  3367. onStrictHandler('onReceive'),
  3368. defaulted('schema', anyValue())
  3369. ])))];
  3370. const executeEvent = (bConfig, bState, executor) => runOnExecute$1(component => {
  3371. executor(component, bConfig, bState);
  3372. });
  3373. const loadEvent = (bConfig, bState, f) => runOnInit((component, _simulatedEvent) => {
  3374. f(component, bConfig, bState);
  3375. });
  3376. const create$4 = (schema, name, active, apis, extra, state) => {
  3377. const configSchema = objOfOnly(schema);
  3378. const schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  3379. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3380. };
  3381. const createModes$1 = (modes, name, active, apis, extra, state) => {
  3382. const configSchema = modes;
  3383. const schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  3384. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3385. };
  3386. const wrapApi = (bName, apiFunction, apiName) => {
  3387. const f = (component, ...rest) => {
  3388. const args = [component].concat(rest);
  3389. return component.config({ name: constant$1(bName) }).fold(() => {
  3390. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  3391. }, info => {
  3392. const rest = Array.prototype.slice.call(args, 1);
  3393. return apiFunction.apply(undefined, [
  3394. component,
  3395. info.config,
  3396. info.state
  3397. ].concat(rest));
  3398. });
  3399. };
  3400. return markAsBehaviourApi(f, apiName, apiFunction);
  3401. };
  3402. const revokeBehaviour = name => ({
  3403. key: name,
  3404. value: undefined
  3405. });
  3406. const doCreate = (configSchema, schemaSchema, name, active, apis, extra, state) => {
  3407. const getConfig = info => hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  3408. const wrappedApis = map$1(apis, (apiF, apiName) => wrapApi(name, apiF, apiName));
  3409. const wrappedExtra = map$1(extra, (extraF, extraName) => markAsExtraApi(extraF, extraName));
  3410. const me = {
  3411. ...wrappedExtra,
  3412. ...wrappedApis,
  3413. revoke: curry(revokeBehaviour, name),
  3414. config: spec => {
  3415. const prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  3416. return {
  3417. key: name,
  3418. value: {
  3419. config: prepared,
  3420. me,
  3421. configAsRaw: cached(() => asRawOrDie$1(name + '-config', configSchema, spec)),
  3422. initialConfig: spec,
  3423. state
  3424. }
  3425. };
  3426. },
  3427. schema: constant$1(schemaSchema),
  3428. exhibit: (info, base) => {
  3429. return lift2(getConfig(info), get$g(active, 'exhibit'), (behaviourInfo, exhibitor) => {
  3430. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  3431. }).getOrThunk(() => nu$7({}));
  3432. },
  3433. name: constant$1(name),
  3434. handlers: info => {
  3435. return getConfig(info).map(behaviourInfo => {
  3436. const getEvents = get$g(active, 'events').getOr(() => ({}));
  3437. return getEvents(behaviourInfo.config, behaviourInfo.state);
  3438. }).getOr({});
  3439. }
  3440. };
  3441. return me;
  3442. };
  3443. const derive$1 = capabilities => wrapAll(capabilities);
  3444. const simpleSchema = objOfOnly([
  3445. required$1('fields'),
  3446. required$1('name'),
  3447. defaulted('active', {}),
  3448. defaulted('apis', {}),
  3449. defaulted('state', NoState),
  3450. defaulted('extra', {})
  3451. ]);
  3452. const create$3 = data => {
  3453. const value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  3454. return create$4(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  3455. };
  3456. const modeSchema = objOfOnly([
  3457. required$1('branchKey'),
  3458. required$1('branches'),
  3459. required$1('name'),
  3460. defaulted('active', {}),
  3461. defaulted('apis', {}),
  3462. defaulted('state', NoState),
  3463. defaulted('extra', {})
  3464. ]);
  3465. const createModes = data => {
  3466. const value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  3467. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  3468. };
  3469. const revoke = constant$1(undefined);
  3470. const Receiving = create$3({
  3471. fields: ReceivingSchema,
  3472. name: 'receiving',
  3473. active: ActiveReceiving
  3474. });
  3475. const exhibit$6 = (base, posConfig) => nu$7({
  3476. classes: [],
  3477. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  3478. });
  3479. var ActivePosition = /*#__PURE__*/Object.freeze({
  3480. __proto__: null,
  3481. exhibit: exhibit$6
  3482. });
  3483. const focus$3 = element => element.dom.focus();
  3484. const blur$1 = element => element.dom.blur();
  3485. const hasFocus = element => {
  3486. const root = getRootNode(element).dom;
  3487. return element.dom === root.activeElement;
  3488. };
  3489. const active$1 = (root = getDocument()) => Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  3490. const search = element => active$1(getRootNode(element)).filter(e => element.dom.contains(e.dom));
  3491. const preserve$1 = (f, container) => {
  3492. const dos = getRootNode(container);
  3493. const refocus = active$1(dos).bind(focused => {
  3494. const hasFocus = elem => eq(focused, elem);
  3495. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  3496. });
  3497. const result = f(container);
  3498. refocus.each(oldFocus => {
  3499. active$1(dos).filter(newFocus => eq(newFocus, oldFocus)).fold(() => {
  3500. focus$3(oldFocus);
  3501. }, noop);
  3502. });
  3503. return result;
  3504. };
  3505. const NuPositionCss = (position, left, top, right, bottom) => {
  3506. const toPx = num => num + 'px';
  3507. return {
  3508. position,
  3509. left: left.map(toPx),
  3510. top: top.map(toPx),
  3511. right: right.map(toPx),
  3512. bottom: bottom.map(toPx)
  3513. };
  3514. };
  3515. const toOptions = position => ({
  3516. ...position,
  3517. position: Optional.some(position.position)
  3518. });
  3519. const applyPositionCss = (element, position) => {
  3520. setOptions(element, toOptions(position));
  3521. };
  3522. const adt$9 = Adt.generate([
  3523. { none: [] },
  3524. {
  3525. relative: [
  3526. 'x',
  3527. 'y',
  3528. 'width',
  3529. 'height'
  3530. ]
  3531. },
  3532. {
  3533. fixed: [
  3534. 'x',
  3535. 'y',
  3536. 'width',
  3537. 'height'
  3538. ]
  3539. }
  3540. ]);
  3541. const positionWithDirection = (posName, decision, x, y, width, height) => {
  3542. const decisionRect = decision.rect;
  3543. const decisionX = decisionRect.x - x;
  3544. const decisionY = decisionRect.y - y;
  3545. const decisionWidth = decisionRect.width;
  3546. const decisionHeight = decisionRect.height;
  3547. const decisionRight = width - (decisionX + decisionWidth);
  3548. const decisionBottom = height - (decisionY + decisionHeight);
  3549. const left = Optional.some(decisionX);
  3550. const top = Optional.some(decisionY);
  3551. const right = Optional.some(decisionRight);
  3552. const bottom = Optional.some(decisionBottom);
  3553. const none = Optional.none();
  3554. return cata$2(decision.direction, () => NuPositionCss(posName, left, top, none, none), () => NuPositionCss(posName, none, top, right, none), () => NuPositionCss(posName, left, none, none, bottom), () => NuPositionCss(posName, none, none, right, bottom), () => NuPositionCss(posName, left, top, none, none), () => NuPositionCss(posName, left, none, none, bottom), () => NuPositionCss(posName, left, top, none, none), () => NuPositionCss(posName, none, top, right, none));
  3555. };
  3556. const reposition = (origin, decision) => origin.fold(() => {
  3557. const decisionRect = decision.rect;
  3558. return NuPositionCss('absolute', Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
  3559. }, (x, y, width, height) => {
  3560. return positionWithDirection('absolute', decision, x, y, width, height);
  3561. }, (x, y, width, height) => {
  3562. return positionWithDirection('fixed', decision, x, y, width, height);
  3563. });
  3564. const toBox = (origin, element) => {
  3565. const rel = curry(find$2, element);
  3566. const position = origin.fold(rel, rel, () => {
  3567. const scroll = get$b();
  3568. return find$2(element).translate(-scroll.left, -scroll.top);
  3569. });
  3570. const width = getOuter$1(element);
  3571. const height = getOuter$2(element);
  3572. return bounds(position.left, position.top, width, height);
  3573. };
  3574. const viewport = (origin, getBounds) => getBounds.fold(() => origin.fold(win, win, bounds), b => origin.fold(b, b, () => {
  3575. const bounds$1 = b();
  3576. const pos = translate$2(origin, bounds$1.x, bounds$1.y);
  3577. return bounds(pos.left, pos.top, bounds$1.width, bounds$1.height);
  3578. }));
  3579. const translate$2 = (origin, x, y) => {
  3580. const pos = SugarPosition(x, y);
  3581. const removeScroll = () => {
  3582. const outerScroll = get$b();
  3583. return pos.translate(-outerScroll.left, -outerScroll.top);
  3584. };
  3585. return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
  3586. };
  3587. const cata$1 = (subject, onNone, onRelative, onFixed) => subject.fold(onNone, onRelative, onFixed);
  3588. adt$9.none;
  3589. const relative$1 = adt$9.relative;
  3590. const fixed$1 = adt$9.fixed;
  3591. const anchor = (anchorBox, origin) => ({
  3592. anchorBox,
  3593. origin
  3594. });
  3595. const box = (anchorBox, origin) => anchor(anchorBox, origin);
  3596. const placementAttribute = 'data-alloy-placement';
  3597. const setPlacement$1 = (element, placement) => {
  3598. set$9(element, placementAttribute, placement);
  3599. };
  3600. const getPlacement = element => getOpt(element, placementAttribute);
  3601. const reset$2 = element => remove$7(element, placementAttribute);
  3602. const adt$8 = Adt.generate([
  3603. { fit: ['reposition'] },
  3604. {
  3605. nofit: [
  3606. 'reposition',
  3607. 'visibleW',
  3608. 'visibleH',
  3609. 'isVisible'
  3610. ]
  3611. }
  3612. ]);
  3613. const determinePosition = (box, bounds) => {
  3614. const {
  3615. x: boundsX,
  3616. y: boundsY,
  3617. right: boundsRight,
  3618. bottom: boundsBottom
  3619. } = bounds;
  3620. const {x, y, right, bottom, width, height} = box;
  3621. const xInBounds = x >= boundsX && x <= boundsRight;
  3622. const yInBounds = y >= boundsY && y <= boundsBottom;
  3623. const originInBounds = xInBounds && yInBounds;
  3624. const rightInBounds = right <= boundsRight && right >= boundsX;
  3625. const bottomInBounds = bottom <= boundsBottom && bottom >= boundsY;
  3626. const sizeInBounds = rightInBounds && bottomInBounds;
  3627. const visibleW = Math.min(width, x >= boundsX ? boundsRight - x : right - boundsX);
  3628. const visibleH = Math.min(height, y >= boundsY ? boundsBottom - y : bottom - boundsY);
  3629. return {
  3630. originInBounds,
  3631. sizeInBounds,
  3632. visibleW,
  3633. visibleH
  3634. };
  3635. };
  3636. const calcReposition = (box, bounds$1) => {
  3637. const {
  3638. x: boundsX,
  3639. y: boundsY,
  3640. right: boundsRight,
  3641. bottom: boundsBottom
  3642. } = bounds$1;
  3643. const {x, y, width, height} = box;
  3644. const maxX = Math.max(boundsX, boundsRight - width);
  3645. const maxY = Math.max(boundsY, boundsBottom - height);
  3646. const restrictedX = clamp(x, boundsX, maxX);
  3647. const restrictedY = clamp(y, boundsY, maxY);
  3648. const restrictedWidth = Math.min(restrictedX + width, boundsRight) - restrictedX;
  3649. const restrictedHeight = Math.min(restrictedY + height, boundsBottom) - restrictedY;
  3650. return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
  3651. };
  3652. const calcMaxSizes = (direction, box, bounds) => {
  3653. const upAvailable = constant$1(box.bottom - bounds.y);
  3654. const downAvailable = constant$1(bounds.bottom - box.y);
  3655. const maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
  3656. const westAvailable = constant$1(box.right - bounds.x);
  3657. const eastAvailable = constant$1(bounds.right - box.x);
  3658. const maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
  3659. return {
  3660. maxWidth,
  3661. maxHeight
  3662. };
  3663. };
  3664. const attempt = (candidate, width, height, bounds$1) => {
  3665. const bubble = candidate.bubble;
  3666. const bubbleOffset = bubble.offset;
  3667. const adjustedBounds = adjustBounds(bounds$1, candidate.restriction, bubbleOffset);
  3668. const newX = candidate.x + bubbleOffset.left;
  3669. const newY = candidate.y + bubbleOffset.top;
  3670. const box = bounds(newX, newY, width, height);
  3671. const {originInBounds, sizeInBounds, visibleW, visibleH} = determinePosition(box, adjustedBounds);
  3672. const fits = originInBounds && sizeInBounds;
  3673. const fittedBox = fits ? box : calcReposition(box, adjustedBounds);
  3674. const isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
  3675. const {maxWidth, maxHeight} = calcMaxSizes(candidate.direction, fittedBox, bounds$1);
  3676. const reposition = {
  3677. rect: fittedBox,
  3678. maxHeight,
  3679. maxWidth,
  3680. direction: candidate.direction,
  3681. placement: candidate.placement,
  3682. classes: {
  3683. on: bubble.classesOn,
  3684. off: bubble.classesOff
  3685. },
  3686. layout: candidate.label,
  3687. testY: newY
  3688. };
  3689. return fits || candidate.alwaysFit ? adt$8.fit(reposition) : adt$8.nofit(reposition, visibleW, visibleH, isPartlyVisible);
  3690. };
  3691. const attempts = (element, candidates, anchorBox, elementBox, bubbles, bounds) => {
  3692. const panelWidth = elementBox.width;
  3693. const panelHeight = elementBox.height;
  3694. const attemptBestFit = (layout, reposition, visibleW, visibleH, isVisible) => {
  3695. const next = layout(anchorBox, elementBox, bubbles, element, bounds);
  3696. const attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  3697. return attemptLayout.fold(constant$1(attemptLayout), (newReposition, newVisibleW, newVisibleH, newIsVisible) => {
  3698. const improved = isVisible === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible && newIsVisible;
  3699. return improved ? attemptLayout : adt$8.nofit(reposition, visibleW, visibleH, isVisible);
  3700. });
  3701. };
  3702. const abc = foldl(candidates, (b, a) => {
  3703. const bestNext = curry(attemptBestFit, a);
  3704. return b.fold(constant$1(b), bestNext);
  3705. }, adt$8.nofit({
  3706. rect: anchorBox,
  3707. maxHeight: elementBox.height,
  3708. maxWidth: elementBox.width,
  3709. direction: southeast$3(),
  3710. placement: 'southeast',
  3711. classes: {
  3712. on: [],
  3713. off: []
  3714. },
  3715. layout: 'none',
  3716. testY: anchorBox.y
  3717. }, -1, -1, false));
  3718. return abc.fold(identity, identity);
  3719. };
  3720. const singleton = doRevoke => {
  3721. const subject = Cell(Optional.none());
  3722. const revoke = () => subject.get().each(doRevoke);
  3723. const clear = () => {
  3724. revoke();
  3725. subject.set(Optional.none());
  3726. };
  3727. const isSet = () => subject.get().isSome();
  3728. const get = () => subject.get();
  3729. const set = s => {
  3730. revoke();
  3731. subject.set(Optional.some(s));
  3732. };
  3733. return {
  3734. clear,
  3735. isSet,
  3736. get,
  3737. set
  3738. };
  3739. };
  3740. const destroyable = () => singleton(s => s.destroy());
  3741. const unbindable = () => singleton(s => s.unbind());
  3742. const value$2 = () => {
  3743. const subject = singleton(noop);
  3744. const on = f => subject.get().each(f);
  3745. return {
  3746. ...subject,
  3747. on
  3748. };
  3749. };
  3750. const filter = always;
  3751. const bind = (element, event, handler) => bind$2(element, event, filter, handler);
  3752. const capture = (element, event, handler) => capture$1(element, event, filter, handler);
  3753. const fromRawEvent = fromRawEvent$1;
  3754. const properties = [
  3755. 'top',
  3756. 'bottom',
  3757. 'right',
  3758. 'left'
  3759. ];
  3760. const timerAttr = 'data-alloy-transition-timer';
  3761. const isTransitioning$1 = (element, transition) => hasAll(element, transition.classes);
  3762. const shouldApplyTransitionCss = (transition, decision, lastPlacement) => {
  3763. return lastPlacement.exists(placer => {
  3764. const mode = transition.mode;
  3765. return mode === 'all' ? true : placer[mode] !== decision[mode];
  3766. });
  3767. };
  3768. const hasChanges = (position, intermediate) => {
  3769. const round = value => parseFloat(value).toFixed(3);
  3770. return find$4(intermediate, (value, key) => {
  3771. const newValue = position[key].map(round);
  3772. const val = value.map(round);
  3773. return !equals(newValue, val);
  3774. }).isSome();
  3775. };
  3776. const getTransitionDuration = element => {
  3777. const get = name => {
  3778. const style = get$e(element, name);
  3779. const times = style.split(/\s*,\s*/);
  3780. return filter$2(times, isNotEmpty);
  3781. };
  3782. const parse = value => {
  3783. if (isString(value) && /^[\d.]+/.test(value)) {
  3784. const num = parseFloat(value);
  3785. return endsWith(value, 'ms') ? num : num * 1000;
  3786. } else {
  3787. return 0;
  3788. }
  3789. };
  3790. const delay = get('transition-delay');
  3791. const duration = get('transition-duration');
  3792. return foldl(duration, (acc, dur, i) => {
  3793. const time = parse(delay[i]) + parse(dur);
  3794. return Math.max(acc, time);
  3795. }, 0);
  3796. };
  3797. const setupTransitionListeners = (element, transition) => {
  3798. const transitionEnd = unbindable();
  3799. const transitionCancel = unbindable();
  3800. let timer;
  3801. const isSourceTransition = e => {
  3802. var _a;
  3803. const pseudoElement = (_a = e.raw.pseudoElement) !== null && _a !== void 0 ? _a : '';
  3804. return eq(e.target, element) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName);
  3805. };
  3806. const transitionDone = e => {
  3807. if (isNullable(e) || isSourceTransition(e)) {
  3808. transitionEnd.clear();
  3809. transitionCancel.clear();
  3810. const type = e === null || e === void 0 ? void 0 : e.raw.type;
  3811. if (isNullable(type) || type === transitionend()) {
  3812. clearTimeout(timer);
  3813. remove$7(element, timerAttr);
  3814. remove$1(element, transition.classes);
  3815. }
  3816. }
  3817. };
  3818. const transitionStart = bind(element, transitionstart(), e => {
  3819. if (isSourceTransition(e)) {
  3820. transitionStart.unbind();
  3821. transitionEnd.set(bind(element, transitionend(), transitionDone));
  3822. transitionCancel.set(bind(element, transitioncancel(), transitionDone));
  3823. }
  3824. });
  3825. const duration = getTransitionDuration(element);
  3826. requestAnimationFrame(() => {
  3827. timer = setTimeout(transitionDone, duration + 17);
  3828. set$9(element, timerAttr, timer);
  3829. });
  3830. };
  3831. const startTransitioning = (element, transition) => {
  3832. add$1(element, transition.classes);
  3833. getOpt(element, timerAttr).each(timerId => {
  3834. clearTimeout(parseInt(timerId, 10));
  3835. remove$7(element, timerAttr);
  3836. });
  3837. setupTransitionListeners(element, transition);
  3838. };
  3839. const applyTransitionCss = (element, origin, position, transition, decision, lastPlacement) => {
  3840. const shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
  3841. if (shouldTransition || isTransitioning$1(element, transition)) {
  3842. set$8(element, 'position', position.position);
  3843. const rect = toBox(origin, element);
  3844. const intermediatePosition = reposition(origin, {
  3845. ...decision,
  3846. rect
  3847. });
  3848. const intermediateCssOptions = mapToObject(properties, prop => intermediatePosition[prop]);
  3849. if (hasChanges(position, intermediateCssOptions)) {
  3850. setOptions(element, intermediateCssOptions);
  3851. if (shouldTransition) {
  3852. startTransitioning(element, transition);
  3853. }
  3854. reflow(element);
  3855. }
  3856. } else {
  3857. remove$1(element, transition.classes);
  3858. }
  3859. };
  3860. const elementSize = p => ({
  3861. width: getOuter$1(p),
  3862. height: getOuter$2(p)
  3863. });
  3864. const layout = (anchorBox, element, bubbles, options) => {
  3865. remove$6(element, 'max-height');
  3866. remove$6(element, 'max-width');
  3867. const elementBox = elementSize(element);
  3868. return attempts(element, options.preference, anchorBox, elementBox, bubbles, options.bounds);
  3869. };
  3870. const setClasses = (element, decision) => {
  3871. const classInfo = decision.classes;
  3872. remove$1(element, classInfo.off);
  3873. add$1(element, classInfo.on);
  3874. };
  3875. const setHeight = (element, decision, options) => {
  3876. const maxHeightFunction = options.maxHeightFunction;
  3877. maxHeightFunction(element, decision.maxHeight);
  3878. };
  3879. const setWidth = (element, decision, options) => {
  3880. const maxWidthFunction = options.maxWidthFunction;
  3881. maxWidthFunction(element, decision.maxWidth);
  3882. };
  3883. const position$2 = (element, decision, options) => {
  3884. const positionCss = reposition(options.origin, decision);
  3885. options.transition.each(transition => {
  3886. applyTransitionCss(element, options.origin, positionCss, transition, decision, options.lastPlacement);
  3887. });
  3888. applyPositionCss(element, positionCss);
  3889. };
  3890. const setPlacement = (element, decision) => {
  3891. setPlacement$1(element, decision.placement);
  3892. };
  3893. const setMaxHeight = (element, maxHeight) => {
  3894. setMax$1(element, Math.floor(maxHeight));
  3895. };
  3896. const anchored = constant$1((element, available) => {
  3897. setMaxHeight(element, available);
  3898. setAll(element, {
  3899. 'overflow-x': 'hidden',
  3900. 'overflow-y': 'auto'
  3901. });
  3902. });
  3903. const expandable$1 = constant$1((element, available) => {
  3904. setMaxHeight(element, available);
  3905. });
  3906. const defaultOr = (options, key, dephault) => options[key] === undefined ? dephault : options[key];
  3907. const simple = (anchor, element, bubble, layouts, lastPlacement, getBounds, overrideOptions, transition) => {
  3908. const maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  3909. const maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  3910. const anchorBox = anchor.anchorBox;
  3911. const origin = anchor.origin;
  3912. const options = {
  3913. bounds: viewport(origin, getBounds),
  3914. origin,
  3915. preference: layouts,
  3916. maxHeightFunction,
  3917. maxWidthFunction,
  3918. lastPlacement,
  3919. transition
  3920. };
  3921. return go(anchorBox, element, bubble, options);
  3922. };
  3923. const go = (anchorBox, element, bubble, options) => {
  3924. const decision = layout(anchorBox, element, bubble, options);
  3925. position$2(element, decision, options);
  3926. setPlacement(element, decision);
  3927. setClasses(element, decision);
  3928. setHeight(element, decision, options);
  3929. setWidth(element, decision, options);
  3930. return {
  3931. layout: decision.layout,
  3932. placement: decision.placement
  3933. };
  3934. };
  3935. const allAlignments = [
  3936. 'valignCentre',
  3937. 'alignLeft',
  3938. 'alignRight',
  3939. 'alignCentre',
  3940. 'top',
  3941. 'bottom',
  3942. 'left',
  3943. 'right',
  3944. 'inset'
  3945. ];
  3946. const nu$5 = (xOffset, yOffset, classes, insetModifier = 1) => {
  3947. const insetXOffset = xOffset * insetModifier;
  3948. const insetYOffset = yOffset * insetModifier;
  3949. const getClasses = prop => get$g(classes, prop).getOr([]);
  3950. const make = (xDelta, yDelta, alignmentsOn) => {
  3951. const alignmentsOff = difference(allAlignments, alignmentsOn);
  3952. return {
  3953. offset: SugarPosition(xDelta, yDelta),
  3954. classesOn: bind$3(alignmentsOn, getClasses),
  3955. classesOff: bind$3(alignmentsOff, getClasses)
  3956. };
  3957. };
  3958. return {
  3959. southeast: () => make(-xOffset, yOffset, [
  3960. 'top',
  3961. 'alignLeft'
  3962. ]),
  3963. southwest: () => make(xOffset, yOffset, [
  3964. 'top',
  3965. 'alignRight'
  3966. ]),
  3967. south: () => make(-xOffset / 2, yOffset, [
  3968. 'top',
  3969. 'alignCentre'
  3970. ]),
  3971. northeast: () => make(-xOffset, -yOffset, [
  3972. 'bottom',
  3973. 'alignLeft'
  3974. ]),
  3975. northwest: () => make(xOffset, -yOffset, [
  3976. 'bottom',
  3977. 'alignRight'
  3978. ]),
  3979. north: () => make(-xOffset / 2, -yOffset, [
  3980. 'bottom',
  3981. 'alignCentre'
  3982. ]),
  3983. east: () => make(xOffset, -yOffset / 2, [
  3984. 'valignCentre',
  3985. 'left'
  3986. ]),
  3987. west: () => make(-xOffset, -yOffset / 2, [
  3988. 'valignCentre',
  3989. 'right'
  3990. ]),
  3991. insetNortheast: () => make(insetXOffset, insetYOffset, [
  3992. 'top',
  3993. 'alignLeft',
  3994. 'inset'
  3995. ]),
  3996. insetNorthwest: () => make(-insetXOffset, insetYOffset, [
  3997. 'top',
  3998. 'alignRight',
  3999. 'inset'
  4000. ]),
  4001. insetNorth: () => make(-insetXOffset / 2, insetYOffset, [
  4002. 'top',
  4003. 'alignCentre',
  4004. 'inset'
  4005. ]),
  4006. insetSoutheast: () => make(insetXOffset, -insetYOffset, [
  4007. 'bottom',
  4008. 'alignLeft',
  4009. 'inset'
  4010. ]),
  4011. insetSouthwest: () => make(-insetXOffset, -insetYOffset, [
  4012. 'bottom',
  4013. 'alignRight',
  4014. 'inset'
  4015. ]),
  4016. insetSouth: () => make(-insetXOffset / 2, -insetYOffset, [
  4017. 'bottom',
  4018. 'alignCentre',
  4019. 'inset'
  4020. ]),
  4021. insetEast: () => make(-insetXOffset, -insetYOffset / 2, [
  4022. 'valignCentre',
  4023. 'right',
  4024. 'inset'
  4025. ]),
  4026. insetWest: () => make(insetXOffset, -insetYOffset / 2, [
  4027. 'valignCentre',
  4028. 'left',
  4029. 'inset'
  4030. ])
  4031. };
  4032. };
  4033. const fallback = () => nu$5(0, 0, {});
  4034. const nu$4 = identity;
  4035. const onDirection = (isLtr, isRtl) => element => getDirection(element) === 'rtl' ? isRtl : isLtr;
  4036. const getDirection = element => get$e(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4037. var AttributeValue;
  4038. (function (AttributeValue) {
  4039. AttributeValue['TopToBottom'] = 'toptobottom';
  4040. AttributeValue['BottomToTop'] = 'bottomtotop';
  4041. }(AttributeValue || (AttributeValue = {})));
  4042. const Attribute = 'data-alloy-vertical-dir';
  4043. const isBottomToTopDir = el => closest$2(el, current => isElement$1(current) && get$f(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop);
  4044. const schema$y = () => optionObjOf('layouts', [
  4045. required$1('onLtr'),
  4046. required$1('onRtl'),
  4047. option$3('onBottomLtr'),
  4048. option$3('onBottomRtl')
  4049. ]);
  4050. const get$5 = (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) => {
  4051. const isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4052. const customLtr = info.layouts.map(ls => ls.onLtr(elem));
  4053. const customRtl = info.layouts.map(ls => ls.onRtl(elem));
  4054. const ltr = isBottomToTop ? info.layouts.bind(ls => ls.onBottomLtr.map(f => f(elem))).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4055. const rtl = isBottomToTop ? info.layouts.bind(ls => ls.onBottomRtl.map(f => f(elem))).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4056. const f = onDirection(ltr, rtl);
  4057. return f(elem);
  4058. };
  4059. const placement$4 = (component, anchorInfo, origin) => {
  4060. const hotspot = anchorInfo.hotspot;
  4061. const anchorBox = toBox(origin, hotspot.element);
  4062. const layouts = get$5(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
  4063. return Optional.some(nu$4({
  4064. anchorBox,
  4065. bubble: anchorInfo.bubble.getOr(fallback()),
  4066. overrides: anchorInfo.overrides,
  4067. layouts,
  4068. placer: Optional.none()
  4069. }));
  4070. };
  4071. var HotspotAnchor = [
  4072. required$1('hotspot'),
  4073. option$3('bubble'),
  4074. defaulted('overrides', {}),
  4075. schema$y(),
  4076. output$1('placement', placement$4)
  4077. ];
  4078. const placement$3 = (component, anchorInfo, origin) => {
  4079. const pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
  4080. const anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
  4081. const layouts = get$5(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
  4082. return Optional.some(nu$4({
  4083. anchorBox,
  4084. bubble: anchorInfo.bubble,
  4085. overrides: anchorInfo.overrides,
  4086. layouts,
  4087. placer: Optional.none()
  4088. }));
  4089. };
  4090. var MakeshiftAnchor = [
  4091. required$1('x'),
  4092. required$1('y'),
  4093. defaulted('height', 0),
  4094. defaulted('width', 0),
  4095. defaulted('bubble', fallback()),
  4096. defaulted('overrides', {}),
  4097. schema$y(),
  4098. output$1('placement', placement$3)
  4099. ];
  4100. const adt$7 = Adt.generate([
  4101. { screen: ['point'] },
  4102. {
  4103. absolute: [
  4104. 'point',
  4105. 'scrollLeft',
  4106. 'scrollTop'
  4107. ]
  4108. }
  4109. ]);
  4110. const toFixed = pos => pos.fold(identity, (point, scrollLeft, scrollTop) => point.translate(-scrollLeft, -scrollTop));
  4111. const toAbsolute = pos => pos.fold(identity, identity);
  4112. const sum = points => foldl(points, (b, a) => b.translate(a.left, a.top), SugarPosition(0, 0));
  4113. const sumAsFixed = positions => {
  4114. const points = map$2(positions, toFixed);
  4115. return sum(points);
  4116. };
  4117. const sumAsAbsolute = positions => {
  4118. const points = map$2(positions, toAbsolute);
  4119. return sum(points);
  4120. };
  4121. const screen = adt$7.screen;
  4122. const absolute$1 = adt$7.absolute;
  4123. const getOffset = (component, origin, anchorInfo) => {
  4124. const win = defaultView(anchorInfo.root).dom;
  4125. const hasSameOwner = frame => {
  4126. const frameOwner = owner$4(frame);
  4127. const compOwner = owner$4(component.element);
  4128. return eq(frameOwner, compOwner);
  4129. };
  4130. return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
  4131. };
  4132. const getRootPoint = (component, origin, anchorInfo) => {
  4133. const doc = owner$4(component.element);
  4134. const outerScroll = get$b(doc);
  4135. const offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4136. return absolute$1(offset, outerScroll.left, outerScroll.top);
  4137. };
  4138. const getBox = (left, top, width, height) => {
  4139. const point = screen(SugarPosition(left, top));
  4140. return Optional.some(pointed(point, width, height));
  4141. };
  4142. const calcNewAnchor = (optBox, rootPoint, anchorInfo, origin, elem) => optBox.map(box => {
  4143. const points = [
  4144. rootPoint,
  4145. box.point
  4146. ];
  4147. const topLeft = cata$1(origin, () => sumAsAbsolute(points), () => sumAsAbsolute(points), () => sumAsFixed(points));
  4148. const anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height);
  4149. const layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  4150. const layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
  4151. const layouts = get$5(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
  4152. return nu$4({
  4153. anchorBox,
  4154. bubble: anchorInfo.bubble.getOr(fallback()),
  4155. overrides: anchorInfo.overrides,
  4156. layouts,
  4157. placer: Optional.none()
  4158. });
  4159. });
  4160. const placement$2 = (component, anchorInfo, origin) => {
  4161. const rootPoint = getRootPoint(component, origin, anchorInfo);
  4162. return anchorInfo.node.filter(inBody).bind(target => {
  4163. const rect = target.dom.getBoundingClientRect();
  4164. const nodeBox = getBox(rect.left, rect.top, rect.width, rect.height);
  4165. const elem = anchorInfo.node.getOr(component.element);
  4166. return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  4167. });
  4168. };
  4169. var NodeAnchor = [
  4170. required$1('node'),
  4171. required$1('root'),
  4172. option$3('bubble'),
  4173. schema$y(),
  4174. defaulted('overrides', {}),
  4175. defaulted('showAbove', false),
  4176. output$1('placement', placement$2)
  4177. ];
  4178. const zeroWidth = '\uFEFF';
  4179. const nbsp = '\xA0';
  4180. const create$2 = (start, soffset, finish, foffset) => ({
  4181. start,
  4182. soffset,
  4183. finish,
  4184. foffset
  4185. });
  4186. const SimRange = { create: create$2 };
  4187. const adt$6 = Adt.generate([
  4188. { before: ['element'] },
  4189. {
  4190. on: [
  4191. 'element',
  4192. 'offset'
  4193. ]
  4194. },
  4195. { after: ['element'] }
  4196. ]);
  4197. const cata = (subject, onBefore, onOn, onAfter) => subject.fold(onBefore, onOn, onAfter);
  4198. const getStart$1 = situ => situ.fold(identity, identity, identity);
  4199. const before = adt$6.before;
  4200. const on$1 = adt$6.on;
  4201. const after$1 = adt$6.after;
  4202. const Situ = {
  4203. before,
  4204. on: on$1,
  4205. after: after$1,
  4206. cata,
  4207. getStart: getStart$1
  4208. };
  4209. const adt$5 = Adt.generate([
  4210. { domRange: ['rng'] },
  4211. {
  4212. relative: [
  4213. 'startSitu',
  4214. 'finishSitu'
  4215. ]
  4216. },
  4217. {
  4218. exact: [
  4219. 'start',
  4220. 'soffset',
  4221. 'finish',
  4222. 'foffset'
  4223. ]
  4224. }
  4225. ]);
  4226. const exactFromRange = simRange => adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  4227. const getStart = selection => selection.match({
  4228. domRange: rng => SugarElement.fromDom(rng.startContainer),
  4229. relative: (startSitu, _finishSitu) => Situ.getStart(startSitu),
  4230. exact: (start, _soffset, _finish, _foffset) => start
  4231. });
  4232. const domRange = adt$5.domRange;
  4233. const relative = adt$5.relative;
  4234. const exact = adt$5.exact;
  4235. const getWin = selection => {
  4236. const start = getStart(selection);
  4237. return defaultView(start);
  4238. };
  4239. const range$1 = SimRange.create;
  4240. const SimSelection = {
  4241. domRange,
  4242. relative,
  4243. exact,
  4244. exactFromRange,
  4245. getWin,
  4246. range: range$1
  4247. };
  4248. const setStart = (rng, situ) => {
  4249. situ.fold(e => {
  4250. rng.setStartBefore(e.dom);
  4251. }, (e, o) => {
  4252. rng.setStart(e.dom, o);
  4253. }, e => {
  4254. rng.setStartAfter(e.dom);
  4255. });
  4256. };
  4257. const setFinish = (rng, situ) => {
  4258. situ.fold(e => {
  4259. rng.setEndBefore(e.dom);
  4260. }, (e, o) => {
  4261. rng.setEnd(e.dom, o);
  4262. }, e => {
  4263. rng.setEndAfter(e.dom);
  4264. });
  4265. };
  4266. const relativeToNative = (win, startSitu, finishSitu) => {
  4267. const range = win.document.createRange();
  4268. setStart(range, startSitu);
  4269. setFinish(range, finishSitu);
  4270. return range;
  4271. };
  4272. const exactToNative = (win, start, soffset, finish, foffset) => {
  4273. const rng = win.document.createRange();
  4274. rng.setStart(start.dom, soffset);
  4275. rng.setEnd(finish.dom, foffset);
  4276. return rng;
  4277. };
  4278. const toRect = rect => ({
  4279. left: rect.left,
  4280. top: rect.top,
  4281. right: rect.right,
  4282. bottom: rect.bottom,
  4283. width: rect.width,
  4284. height: rect.height
  4285. });
  4286. const getFirstRect$1 = rng => {
  4287. const rects = rng.getClientRects();
  4288. const rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  4289. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  4290. };
  4291. const getBounds$2 = rng => {
  4292. const rect = rng.getBoundingClientRect();
  4293. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  4294. };
  4295. const adt$4 = Adt.generate([
  4296. {
  4297. ltr: [
  4298. 'start',
  4299. 'soffset',
  4300. 'finish',
  4301. 'foffset'
  4302. ]
  4303. },
  4304. {
  4305. rtl: [
  4306. 'start',
  4307. 'soffset',
  4308. 'finish',
  4309. 'foffset'
  4310. ]
  4311. }
  4312. ]);
  4313. const fromRange = (win, type, range) => type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  4314. const getRanges = (win, selection) => selection.match({
  4315. domRange: rng => {
  4316. return {
  4317. ltr: constant$1(rng),
  4318. rtl: Optional.none
  4319. };
  4320. },
  4321. relative: (startSitu, finishSitu) => {
  4322. return {
  4323. ltr: cached(() => relativeToNative(win, startSitu, finishSitu)),
  4324. rtl: cached(() => Optional.some(relativeToNative(win, finishSitu, startSitu)))
  4325. };
  4326. },
  4327. exact: (start, soffset, finish, foffset) => {
  4328. return {
  4329. ltr: cached(() => exactToNative(win, start, soffset, finish, foffset)),
  4330. rtl: cached(() => Optional.some(exactToNative(win, finish, foffset, start, soffset)))
  4331. };
  4332. }
  4333. });
  4334. const doDiagnose = (win, ranges) => {
  4335. const rng = ranges.ltr();
  4336. if (rng.collapsed) {
  4337. const reversed = ranges.rtl().filter(rev => rev.collapsed === false);
  4338. return reversed.map(rev => adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset)).getOrThunk(() => fromRange(win, adt$4.ltr, rng));
  4339. } else {
  4340. return fromRange(win, adt$4.ltr, rng);
  4341. }
  4342. };
  4343. const diagnose = (win, selection) => {
  4344. const ranges = getRanges(win, selection);
  4345. return doDiagnose(win, ranges);
  4346. };
  4347. const asLtrRange = (win, selection) => {
  4348. const diagnosis = diagnose(win, selection);
  4349. return diagnosis.match({
  4350. ltr: (start, soffset, finish, foffset) => {
  4351. const rng = win.document.createRange();
  4352. rng.setStart(start.dom, soffset);
  4353. rng.setEnd(finish.dom, foffset);
  4354. return rng;
  4355. },
  4356. rtl: (start, soffset, finish, foffset) => {
  4357. const rng = win.document.createRange();
  4358. rng.setStart(finish.dom, foffset);
  4359. rng.setEnd(start.dom, soffset);
  4360. return rng;
  4361. }
  4362. });
  4363. };
  4364. adt$4.ltr;
  4365. adt$4.rtl;
  4366. const descendants = (scope, selector) => all$3(selector, scope);
  4367. const makeRange = (start, soffset, finish, foffset) => {
  4368. const doc = owner$4(start);
  4369. const rng = doc.dom.createRange();
  4370. rng.setStart(start.dom, soffset);
  4371. rng.setEnd(finish.dom, foffset);
  4372. return rng;
  4373. };
  4374. const after = (start, soffset, finish, foffset) => {
  4375. const r = makeRange(start, soffset, finish, foffset);
  4376. const same = eq(start, finish) && soffset === foffset;
  4377. return r.collapsed && !same;
  4378. };
  4379. const getNativeSelection = win => Optional.from(win.getSelection());
  4380. const readRange = selection => {
  4381. if (selection.rangeCount > 0) {
  4382. const firstRng = selection.getRangeAt(0);
  4383. const lastRng = selection.getRangeAt(selection.rangeCount - 1);
  4384. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  4385. } else {
  4386. return Optional.none();
  4387. }
  4388. };
  4389. const doGetExact = selection => {
  4390. if (selection.anchorNode === null || selection.focusNode === null) {
  4391. return readRange(selection);
  4392. } else {
  4393. const anchor = SugarElement.fromDom(selection.anchorNode);
  4394. const focus = SugarElement.fromDom(selection.focusNode);
  4395. return after(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  4396. }
  4397. };
  4398. const getExact = win => getNativeSelection(win).filter(sel => sel.rangeCount > 0).bind(doGetExact);
  4399. const getFirstRect = (win, selection) => {
  4400. const rng = asLtrRange(win, selection);
  4401. return getFirstRect$1(rng);
  4402. };
  4403. const getBounds$1 = (win, selection) => {
  4404. const rng = asLtrRange(win, selection);
  4405. return getBounds$2(rng);
  4406. };
  4407. const NodeValue = (is, name) => {
  4408. const get = element => {
  4409. if (!is(element)) {
  4410. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  4411. }
  4412. return getOption(element).getOr('');
  4413. };
  4414. const getOption = element => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  4415. const set = (element, value) => {
  4416. if (!is(element)) {
  4417. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  4418. }
  4419. element.dom.nodeValue = value;
  4420. };
  4421. return {
  4422. get,
  4423. getOption,
  4424. set
  4425. };
  4426. };
  4427. const api = NodeValue(isText, 'text');
  4428. const get$4 = element => api.get(element);
  4429. const point = (element, offset) => ({
  4430. element,
  4431. offset
  4432. });
  4433. const descendOnce$1 = (element, offset) => {
  4434. const children$1 = children(element);
  4435. if (children$1.length === 0) {
  4436. return point(element, offset);
  4437. } else if (offset < children$1.length) {
  4438. return point(children$1[offset], 0);
  4439. } else {
  4440. const last = children$1[children$1.length - 1];
  4441. const len = isText(last) ? get$4(last).length : children(last).length;
  4442. return point(last, len);
  4443. }
  4444. };
  4445. const descendOnce = (element, offset) => isText(element) ? point(element, offset) : descendOnce$1(element, offset);
  4446. const getAnchorSelection = (win, anchorInfo) => {
  4447. const getSelection = anchorInfo.getSelection.getOrThunk(() => () => getExact(win));
  4448. return getSelection().map(sel => {
  4449. const modStart = descendOnce(sel.start, sel.soffset);
  4450. const modFinish = descendOnce(sel.finish, sel.foffset);
  4451. return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  4452. });
  4453. };
  4454. const placement$1 = (component, anchorInfo, origin) => {
  4455. const win = defaultView(anchorInfo.root).dom;
  4456. const rootPoint = getRootPoint(component, origin, anchorInfo);
  4457. const selectionBox = getAnchorSelection(win, anchorInfo).bind(sel => {
  4458. const optRect = getBounds$1(win, SimSelection.exactFromRange(sel)).orThunk(() => {
  4459. const x = SugarElement.fromText(zeroWidth);
  4460. before$1(sel.start, x);
  4461. const rect = getFirstRect(win, SimSelection.exact(x, 0, x, 1));
  4462. remove$5(x);
  4463. return rect;
  4464. });
  4465. return optRect.bind(rawRect => getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height));
  4466. });
  4467. const targetElement = getAnchorSelection(win, anchorInfo).bind(sel => isElement$1(sel.start) ? Optional.some(sel.start) : parentElement(sel.start));
  4468. const elem = targetElement.getOr(component.element);
  4469. return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  4470. };
  4471. var SelectionAnchor = [
  4472. option$3('getSelection'),
  4473. required$1('root'),
  4474. option$3('bubble'),
  4475. schema$y(),
  4476. defaulted('overrides', {}),
  4477. defaulted('showAbove', false),
  4478. output$1('placement', placement$1)
  4479. ];
  4480. const labelPrefix$1 = 'link-layout';
  4481. const eastX = anchor => anchor.x + anchor.width;
  4482. const westX = (anchor, element) => anchor.x - element.width;
  4483. const northY$1 = (anchor, element) => anchor.y - element.height + anchor.height;
  4484. const southY$1 = anchor => anchor.y;
  4485. const southeast$1 = (anchor, element, bubbles) => nu$6(eastX(anchor), southY$1(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  4486. left: 0,
  4487. top: 2
  4488. }), labelPrefix$1);
  4489. const southwest$1 = (anchor, element, bubbles) => nu$6(westX(anchor, element), southY$1(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  4490. right: 1,
  4491. top: 2
  4492. }), labelPrefix$1);
  4493. const northeast$1 = (anchor, element, bubbles) => nu$6(eastX(anchor), northY$1(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  4494. left: 0,
  4495. bottom: 3
  4496. }), labelPrefix$1);
  4497. const northwest$1 = (anchor, element, bubbles) => nu$6(westX(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  4498. right: 1,
  4499. bottom: 3
  4500. }), labelPrefix$1);
  4501. const all = () => [
  4502. southeast$1,
  4503. southwest$1,
  4504. northeast$1,
  4505. northwest$1
  4506. ];
  4507. const allRtl = () => [
  4508. southwest$1,
  4509. southeast$1,
  4510. northwest$1,
  4511. northeast$1
  4512. ];
  4513. const placement = (component, submenuInfo, origin) => {
  4514. const anchorBox = toBox(origin, submenuInfo.item.element);
  4515. const layouts = get$5(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
  4516. return Optional.some(nu$4({
  4517. anchorBox,
  4518. bubble: fallback(),
  4519. overrides: submenuInfo.overrides,
  4520. layouts,
  4521. placer: Optional.none()
  4522. }));
  4523. };
  4524. var SubmenuAnchor = [
  4525. required$1('item'),
  4526. schema$y(),
  4527. defaulted('overrides', {}),
  4528. output$1('placement', placement)
  4529. ];
  4530. var AnchorSchema = choose$1('type', {
  4531. selection: SelectionAnchor,
  4532. node: NodeAnchor,
  4533. hotspot: HotspotAnchor,
  4534. submenu: SubmenuAnchor,
  4535. makeshift: MakeshiftAnchor
  4536. });
  4537. const TransitionSchema = [
  4538. requiredArrayOf('classes', string),
  4539. defaultedStringEnum('mode', 'all', [
  4540. 'all',
  4541. 'layout',
  4542. 'placement'
  4543. ])
  4544. ];
  4545. const PositionSchema = [
  4546. defaulted('useFixed', never),
  4547. option$3('getBounds')
  4548. ];
  4549. const PlacementSchema = [
  4550. requiredOf('anchor', AnchorSchema),
  4551. optionObjOf('transition', TransitionSchema)
  4552. ];
  4553. const getFixedOrigin = () => {
  4554. const html = document.documentElement;
  4555. return fixed$1(0, 0, html.clientWidth, html.clientHeight);
  4556. };
  4557. const getRelativeOrigin = component => {
  4558. const position = absolute$3(component.element);
  4559. const bounds = component.element.dom.getBoundingClientRect();
  4560. return relative$1(position.left, position.top, bounds.width, bounds.height);
  4561. };
  4562. const place = (component, origin, anchoring, getBounds, placee, lastPlace, transition) => {
  4563. const anchor = box(anchoring.anchorBox, origin);
  4564. return simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds, anchoring.overrides, transition);
  4565. };
  4566. const position$1 = (component, posConfig, posState, placee, placementSpec) => {
  4567. positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
  4568. };
  4569. const positionWithin = (component, posConfig, posState, placee, placementSpec, boxElement) => {
  4570. const boundsBox = boxElement.map(box$1);
  4571. return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
  4572. };
  4573. const positionWithinBounds = (component, posConfig, posState, placee, placementSpec, bounds) => {
  4574. const placeeDetail = asRawOrDie$1('placement.info', objOf(PlacementSchema), placementSpec);
  4575. const anchorage = placeeDetail.anchor;
  4576. const element = placee.element;
  4577. const placeeState = posState.get(placee.uid);
  4578. preserve$1(() => {
  4579. set$8(element, 'position', 'fixed');
  4580. const oldVisibility = getRaw(element, 'visibility');
  4581. set$8(element, 'visibility', 'hidden');
  4582. const origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  4583. const placer = anchorage.placement;
  4584. const getBounds = bounds.map(constant$1).or(posConfig.getBounds);
  4585. placer(component, anchorage, origin).each(anchoring => {
  4586. const doPlace = anchoring.placer.getOr(place);
  4587. const newState = doPlace(component, origin, anchoring, getBounds, placee, placeeState, placeeDetail.transition);
  4588. posState.set(placee.uid, newState);
  4589. });
  4590. oldVisibility.fold(() => {
  4591. remove$6(element, 'visibility');
  4592. }, vis => {
  4593. set$8(element, 'visibility', vis);
  4594. });
  4595. if (getRaw(element, 'left').isNone() && getRaw(element, 'top').isNone() && getRaw(element, 'right').isNone() && getRaw(element, 'bottom').isNone() && is$1(getRaw(element, 'position'), 'fixed')) {
  4596. remove$6(element, 'position');
  4597. }
  4598. }, element);
  4599. };
  4600. const getMode = (component, pConfig, _pState) => pConfig.useFixed() ? 'fixed' : 'absolute';
  4601. const reset$1 = (component, pConfig, posState, placee) => {
  4602. const element = placee.element;
  4603. each$1([
  4604. 'position',
  4605. 'left',
  4606. 'right',
  4607. 'top',
  4608. 'bottom'
  4609. ], prop => remove$6(element, prop));
  4610. reset$2(element);
  4611. posState.clear(placee.uid);
  4612. };
  4613. var PositionApis = /*#__PURE__*/Object.freeze({
  4614. __proto__: null,
  4615. position: position$1,
  4616. positionWithin: positionWithin,
  4617. positionWithinBounds: positionWithinBounds,
  4618. getMode: getMode,
  4619. reset: reset$1
  4620. });
  4621. const init$g = () => {
  4622. let state = {};
  4623. const set = (id, data) => {
  4624. state[id] = data;
  4625. };
  4626. const get = id => get$g(state, id);
  4627. const clear = id => {
  4628. if (isNonNullable(id)) {
  4629. delete state[id];
  4630. } else {
  4631. state = {};
  4632. }
  4633. };
  4634. return nu$8({
  4635. readState: () => state,
  4636. clear,
  4637. set,
  4638. get
  4639. });
  4640. };
  4641. var PositioningState = /*#__PURE__*/Object.freeze({
  4642. __proto__: null,
  4643. init: init$g
  4644. });
  4645. const Positioning = create$3({
  4646. fields: PositionSchema,
  4647. name: 'positioning',
  4648. active: ActivePosition,
  4649. apis: PositionApis,
  4650. state: PositioningState
  4651. });
  4652. const isConnected = comp => comp.getSystem().isConnected();
  4653. const fireDetaching = component => {
  4654. emit(component, detachedFromDom());
  4655. const children = component.components();
  4656. each$1(children, fireDetaching);
  4657. };
  4658. const fireAttaching = component => {
  4659. const children = component.components();
  4660. each$1(children, fireAttaching);
  4661. emit(component, attachedToDom());
  4662. };
  4663. const virtualAttach = (parent, child) => {
  4664. parent.getSystem().addToWorld(child);
  4665. if (inBody(parent.element)) {
  4666. fireAttaching(child);
  4667. }
  4668. };
  4669. const virtualDetach = comp => {
  4670. fireDetaching(comp);
  4671. comp.getSystem().removeFromWorld(comp);
  4672. };
  4673. const attach$1 = (parent, child) => {
  4674. append$2(parent.element, child.element);
  4675. };
  4676. const detachChildren$1 = component => {
  4677. each$1(component.components(), childComp => remove$5(childComp.element));
  4678. empty(component.element);
  4679. component.syncComponents();
  4680. };
  4681. const replaceChildren = (component, newSpecs, buildNewChildren) => {
  4682. const subs = component.components();
  4683. detachChildren$1(component);
  4684. const newChildren = buildNewChildren(newSpecs);
  4685. const deleted = difference(subs, newChildren);
  4686. each$1(deleted, comp => {
  4687. fireDetaching(comp);
  4688. component.getSystem().removeFromWorld(comp);
  4689. });
  4690. each$1(newChildren, childComp => {
  4691. if (!isConnected(childComp)) {
  4692. component.getSystem().addToWorld(childComp);
  4693. attach$1(component, childComp);
  4694. if (inBody(component.element)) {
  4695. fireAttaching(childComp);
  4696. }
  4697. } else {
  4698. attach$1(component, childComp);
  4699. }
  4700. });
  4701. component.syncComponents();
  4702. };
  4703. const virtualReplaceChildren = (component, newSpecs, buildNewChildren) => {
  4704. const subs = component.components();
  4705. const existingComps = bind$3(newSpecs, spec => getPremade(spec).toArray());
  4706. each$1(subs, childComp => {
  4707. if (!contains$2(existingComps, childComp)) {
  4708. virtualDetach(childComp);
  4709. }
  4710. });
  4711. const newChildren = buildNewChildren(newSpecs);
  4712. const deleted = difference(subs, newChildren);
  4713. each$1(deleted, deletedComp => {
  4714. if (isConnected(deletedComp)) {
  4715. virtualDetach(deletedComp);
  4716. }
  4717. });
  4718. each$1(newChildren, childComp => {
  4719. if (!isConnected(childComp)) {
  4720. virtualAttach(component, childComp);
  4721. }
  4722. });
  4723. component.syncComponents();
  4724. };
  4725. const attach = (parent, child) => {
  4726. attachWith(parent, child, append$2);
  4727. };
  4728. const attachWith = (parent, child, insertion) => {
  4729. parent.getSystem().addToWorld(child);
  4730. insertion(parent.element, child.element);
  4731. if (inBody(parent.element)) {
  4732. fireAttaching(child);
  4733. }
  4734. parent.syncComponents();
  4735. };
  4736. const doDetach = component => {
  4737. fireDetaching(component);
  4738. remove$5(component.element);
  4739. component.getSystem().removeFromWorld(component);
  4740. };
  4741. const detach = component => {
  4742. const parent$1 = parent(component.element).bind(p => component.getSystem().getByDom(p).toOptional());
  4743. doDetach(component);
  4744. parent$1.each(p => {
  4745. p.syncComponents();
  4746. });
  4747. };
  4748. const detachChildren = component => {
  4749. const subs = component.components();
  4750. each$1(subs, doDetach);
  4751. empty(component.element);
  4752. component.syncComponents();
  4753. };
  4754. const attachSystem = (element, guiSystem) => {
  4755. attachSystemWith(element, guiSystem, append$2);
  4756. };
  4757. const attachSystemAfter = (element, guiSystem) => {
  4758. attachSystemWith(element, guiSystem, after$2);
  4759. };
  4760. const attachSystemWith = (element, guiSystem, inserter) => {
  4761. inserter(element, guiSystem.element);
  4762. const children$1 = children(guiSystem.element);
  4763. each$1(children$1, child => {
  4764. guiSystem.getByDom(child).each(fireAttaching);
  4765. });
  4766. };
  4767. const detachSystem = guiSystem => {
  4768. const children$1 = children(guiSystem.element);
  4769. each$1(children$1, child => {
  4770. guiSystem.getByDom(child).each(fireDetaching);
  4771. });
  4772. remove$5(guiSystem.element);
  4773. };
  4774. const rebuild = (sandbox, sConfig, sState, data) => {
  4775. sState.get().each(_data => {
  4776. detachChildren(sandbox);
  4777. });
  4778. const point = sConfig.getAttachPoint(sandbox);
  4779. attach(point, sandbox);
  4780. const built = sandbox.getSystem().build(data);
  4781. attach(sandbox, built);
  4782. sState.set(built);
  4783. return built;
  4784. };
  4785. const open$1 = (sandbox, sConfig, sState, data) => {
  4786. const newState = rebuild(sandbox, sConfig, sState, data);
  4787. sConfig.onOpen(sandbox, newState);
  4788. return newState;
  4789. };
  4790. const setContent = (sandbox, sConfig, sState, data) => sState.get().map(() => rebuild(sandbox, sConfig, sState, data));
  4791. const openWhileCloaked = (sandbox, sConfig, sState, data, transaction) => {
  4792. cloak(sandbox, sConfig);
  4793. open$1(sandbox, sConfig, sState, data);
  4794. transaction();
  4795. decloak(sandbox, sConfig);
  4796. };
  4797. const close$1 = (sandbox, sConfig, sState) => {
  4798. sState.get().each(data => {
  4799. detachChildren(sandbox);
  4800. detach(sandbox);
  4801. sConfig.onClose(sandbox, data);
  4802. sState.clear();
  4803. });
  4804. };
  4805. const isOpen$1 = (_sandbox, _sConfig, sState) => sState.isOpen();
  4806. const isPartOf = (sandbox, sConfig, sState, queryElem) => isOpen$1(sandbox, sConfig, sState) && sState.get().exists(data => sConfig.isPartOf(sandbox, data, queryElem));
  4807. const getState$2 = (_sandbox, _sConfig, sState) => sState.get();
  4808. const store = (sandbox, cssKey, attr, newValue) => {
  4809. getRaw(sandbox.element, cssKey).fold(() => {
  4810. remove$7(sandbox.element, attr);
  4811. }, v => {
  4812. set$9(sandbox.element, attr, v);
  4813. });
  4814. set$8(sandbox.element, cssKey, newValue);
  4815. };
  4816. const restore = (sandbox, cssKey, attr) => {
  4817. getOpt(sandbox.element, attr).fold(() => remove$6(sandbox.element, cssKey), oldValue => set$8(sandbox.element, cssKey, oldValue));
  4818. };
  4819. const cloak = (sandbox, sConfig, _sState) => {
  4820. const sink = sConfig.getAttachPoint(sandbox);
  4821. set$8(sandbox.element, 'position', Positioning.getMode(sink));
  4822. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  4823. };
  4824. const hasPosition = element => exists([
  4825. 'top',
  4826. 'left',
  4827. 'right',
  4828. 'bottom'
  4829. ], pos => getRaw(element, pos).isSome());
  4830. const decloak = (sandbox, sConfig, _sState) => {
  4831. if (!hasPosition(sandbox.element)) {
  4832. remove$6(sandbox.element, 'position');
  4833. }
  4834. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  4835. };
  4836. var SandboxApis = /*#__PURE__*/Object.freeze({
  4837. __proto__: null,
  4838. cloak: cloak,
  4839. decloak: decloak,
  4840. open: open$1,
  4841. openWhileCloaked: openWhileCloaked,
  4842. close: close$1,
  4843. isOpen: isOpen$1,
  4844. isPartOf: isPartOf,
  4845. getState: getState$2,
  4846. setContent: setContent
  4847. });
  4848. const events$g = (sandboxConfig, sandboxState) => derive$2([run$1(sandboxClose(), (sandbox, _simulatedEvent) => {
  4849. close$1(sandbox, sandboxConfig, sandboxState);
  4850. })]);
  4851. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  4852. __proto__: null,
  4853. events: events$g
  4854. });
  4855. var SandboxSchema = [
  4856. onHandler('onOpen'),
  4857. onHandler('onClose'),
  4858. required$1('isPartOf'),
  4859. required$1('getAttachPoint'),
  4860. defaulted('cloakVisibilityAttr', 'data-precloak-visibility')
  4861. ];
  4862. const init$f = () => {
  4863. const contents = value$2();
  4864. const readState = constant$1('not-implemented');
  4865. return nu$8({
  4866. readState,
  4867. isOpen: contents.isSet,
  4868. clear: contents.clear,
  4869. set: contents.set,
  4870. get: contents.get
  4871. });
  4872. };
  4873. var SandboxState = /*#__PURE__*/Object.freeze({
  4874. __proto__: null,
  4875. init: init$f
  4876. });
  4877. const Sandboxing = create$3({
  4878. fields: SandboxSchema,
  4879. name: 'sandboxing',
  4880. active: ActiveSandbox,
  4881. apis: SandboxApis,
  4882. state: SandboxState
  4883. });
  4884. const dismissPopups = constant$1('dismiss.popups');
  4885. const repositionPopups = constant$1('reposition.popups');
  4886. const mouseReleased = constant$1('mouse.released');
  4887. const schema$x = objOfOnly([
  4888. defaulted('isExtraPart', never),
  4889. optionObjOf('fireEventInstead', [defaulted('event', dismissRequested())])
  4890. ]);
  4891. const receivingChannel$1 = rawSpec => {
  4892. const detail = asRawOrDie$1('Dismissal', schema$x, rawSpec);
  4893. return {
  4894. [dismissPopups()]: {
  4895. schema: objOfOnly([required$1('target')]),
  4896. onReceive: (sandbox, data) => {
  4897. if (Sandboxing.isOpen(sandbox)) {
  4898. const isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  4899. if (!isPart) {
  4900. detail.fireEventInstead.fold(() => Sandboxing.close(sandbox), fe => emit(sandbox, fe.event));
  4901. }
  4902. }
  4903. }
  4904. }
  4905. };
  4906. };
  4907. const schema$w = objOfOnly([
  4908. optionObjOf('fireEventInstead', [defaulted('event', repositionRequested())]),
  4909. requiredFunction('doReposition')
  4910. ]);
  4911. const receivingChannel = rawSpec => {
  4912. const detail = asRawOrDie$1('Reposition', schema$w, rawSpec);
  4913. return {
  4914. [repositionPopups()]: {
  4915. onReceive: sandbox => {
  4916. if (Sandboxing.isOpen(sandbox)) {
  4917. detail.fireEventInstead.fold(() => detail.doReposition(sandbox), fe => emit(sandbox, fe.event));
  4918. }
  4919. }
  4920. }
  4921. };
  4922. };
  4923. const onLoad$5 = (component, repConfig, repState) => {
  4924. repConfig.store.manager.onLoad(component, repConfig, repState);
  4925. };
  4926. const onUnload$2 = (component, repConfig, repState) => {
  4927. repConfig.store.manager.onUnload(component, repConfig, repState);
  4928. };
  4929. const setValue$3 = (component, repConfig, repState, data) => {
  4930. repConfig.store.manager.setValue(component, repConfig, repState, data);
  4931. };
  4932. const getValue$3 = (component, repConfig, repState) => repConfig.store.manager.getValue(component, repConfig, repState);
  4933. const getState$1 = (component, repConfig, repState) => repState;
  4934. var RepresentApis = /*#__PURE__*/Object.freeze({
  4935. __proto__: null,
  4936. onLoad: onLoad$5,
  4937. onUnload: onUnload$2,
  4938. setValue: setValue$3,
  4939. getValue: getValue$3,
  4940. getState: getState$1
  4941. });
  4942. const events$f = (repConfig, repState) => {
  4943. const es = repConfig.resetOnDom ? [
  4944. runOnAttached((comp, _se) => {
  4945. onLoad$5(comp, repConfig, repState);
  4946. }),
  4947. runOnDetached((comp, _se) => {
  4948. onUnload$2(comp, repConfig, repState);
  4949. })
  4950. ] : [loadEvent(repConfig, repState, onLoad$5)];
  4951. return derive$2(es);
  4952. };
  4953. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  4954. __proto__: null,
  4955. events: events$f
  4956. });
  4957. const memory$1 = () => {
  4958. const data = Cell(null);
  4959. const readState = () => ({
  4960. mode: 'memory',
  4961. value: data.get()
  4962. });
  4963. const isNotSet = () => data.get() === null;
  4964. const clear = () => {
  4965. data.set(null);
  4966. };
  4967. return nu$8({
  4968. set: data.set,
  4969. get: data.get,
  4970. isNotSet,
  4971. clear,
  4972. readState
  4973. });
  4974. };
  4975. const manual = () => {
  4976. const readState = noop;
  4977. return nu$8({ readState });
  4978. };
  4979. const dataset = () => {
  4980. const dataByValue = Cell({});
  4981. const dataByText = Cell({});
  4982. const readState = () => ({
  4983. mode: 'dataset',
  4984. dataByValue: dataByValue.get(),
  4985. dataByText: dataByText.get()
  4986. });
  4987. const clear = () => {
  4988. dataByValue.set({});
  4989. dataByText.set({});
  4990. };
  4991. const lookup = itemString => get$g(dataByValue.get(), itemString).orThunk(() => get$g(dataByText.get(), itemString));
  4992. const update = items => {
  4993. const currentDataByValue = dataByValue.get();
  4994. const currentDataByText = dataByText.get();
  4995. const newDataByValue = {};
  4996. const newDataByText = {};
  4997. each$1(items, item => {
  4998. newDataByValue[item.value] = item;
  4999. get$g(item, 'meta').each(meta => {
  5000. get$g(meta, 'text').each(text => {
  5001. newDataByText[text] = item;
  5002. });
  5003. });
  5004. });
  5005. dataByValue.set({
  5006. ...currentDataByValue,
  5007. ...newDataByValue
  5008. });
  5009. dataByText.set({
  5010. ...currentDataByText,
  5011. ...newDataByText
  5012. });
  5013. };
  5014. return nu$8({
  5015. readState,
  5016. lookup,
  5017. update,
  5018. clear
  5019. });
  5020. };
  5021. const init$e = spec => spec.store.manager.state(spec);
  5022. var RepresentState = /*#__PURE__*/Object.freeze({
  5023. __proto__: null,
  5024. memory: memory$1,
  5025. dataset: dataset,
  5026. manual: manual,
  5027. init: init$e
  5028. });
  5029. const setValue$2 = (component, repConfig, repState, data) => {
  5030. const store = repConfig.store;
  5031. repState.update([data]);
  5032. store.setValue(component, data);
  5033. repConfig.onSetValue(component, data);
  5034. };
  5035. const getValue$2 = (component, repConfig, repState) => {
  5036. const store = repConfig.store;
  5037. const key = store.getDataKey(component);
  5038. return repState.lookup(key).getOrThunk(() => store.getFallbackEntry(key));
  5039. };
  5040. const onLoad$4 = (component, repConfig, repState) => {
  5041. const store = repConfig.store;
  5042. store.initialValue.each(data => {
  5043. setValue$2(component, repConfig, repState, data);
  5044. });
  5045. };
  5046. const onUnload$1 = (component, repConfig, repState) => {
  5047. repState.clear();
  5048. };
  5049. var DatasetStore = [
  5050. option$3('initialValue'),
  5051. required$1('getFallbackEntry'),
  5052. required$1('getDataKey'),
  5053. required$1('setValue'),
  5054. output$1('manager', {
  5055. setValue: setValue$2,
  5056. getValue: getValue$2,
  5057. onLoad: onLoad$4,
  5058. onUnload: onUnload$1,
  5059. state: dataset
  5060. })
  5061. ];
  5062. const getValue$1 = (component, repConfig, _repState) => repConfig.store.getValue(component);
  5063. const setValue$1 = (component, repConfig, _repState, data) => {
  5064. repConfig.store.setValue(component, data);
  5065. repConfig.onSetValue(component, data);
  5066. };
  5067. const onLoad$3 = (component, repConfig, _repState) => {
  5068. repConfig.store.initialValue.each(data => {
  5069. repConfig.store.setValue(component, data);
  5070. });
  5071. };
  5072. var ManualStore = [
  5073. required$1('getValue'),
  5074. defaulted('setValue', noop),
  5075. option$3('initialValue'),
  5076. output$1('manager', {
  5077. setValue: setValue$1,
  5078. getValue: getValue$1,
  5079. onLoad: onLoad$3,
  5080. onUnload: noop,
  5081. state: NoState.init
  5082. })
  5083. ];
  5084. const setValue = (component, repConfig, repState, data) => {
  5085. repState.set(data);
  5086. repConfig.onSetValue(component, data);
  5087. };
  5088. const getValue = (component, repConfig, repState) => repState.get();
  5089. const onLoad$2 = (component, repConfig, repState) => {
  5090. repConfig.store.initialValue.each(initVal => {
  5091. if (repState.isNotSet()) {
  5092. repState.set(initVal);
  5093. }
  5094. });
  5095. };
  5096. const onUnload = (component, repConfig, repState) => {
  5097. repState.clear();
  5098. };
  5099. var MemoryStore = [
  5100. option$3('initialValue'),
  5101. output$1('manager', {
  5102. setValue,
  5103. getValue,
  5104. onLoad: onLoad$2,
  5105. onUnload,
  5106. state: memory$1
  5107. })
  5108. ];
  5109. var RepresentSchema = [
  5110. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5111. memory: MemoryStore,
  5112. manual: ManualStore,
  5113. dataset: DatasetStore
  5114. })),
  5115. onHandler('onSetValue'),
  5116. defaulted('resetOnDom', false)
  5117. ];
  5118. const Representing = create$3({
  5119. fields: RepresentSchema,
  5120. name: 'representing',
  5121. active: ActiveRepresenting,
  5122. apis: RepresentApis,
  5123. extra: {
  5124. setValueFrom: (component, source) => {
  5125. const value = Representing.getValue(source);
  5126. Representing.setValue(component, value);
  5127. }
  5128. },
  5129. state: RepresentState
  5130. });
  5131. const field = (name, forbidden) => defaultedObjOf(name, {}, map$2(forbidden, f => forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name)).concat([customField('dump', identity)]));
  5132. const get$3 = data => data.dump;
  5133. const augment = (data, original) => ({
  5134. ...derive$1(original),
  5135. ...data.dump
  5136. });
  5137. const SketchBehaviours = {
  5138. field,
  5139. augment,
  5140. get: get$3
  5141. };
  5142. const _placeholder = 'placeholder';
  5143. const adt$3 = Adt.generate([
  5144. {
  5145. single: [
  5146. 'required',
  5147. 'valueThunk'
  5148. ]
  5149. },
  5150. {
  5151. multiple: [
  5152. 'required',
  5153. 'valueThunks'
  5154. ]
  5155. }
  5156. ]);
  5157. const isSubstituted = spec => has$2(spec, 'uiType');
  5158. const subPlaceholder = (owner, detail, compSpec, placeholders) => {
  5159. if (owner.exists(o => o !== compSpec.owner)) {
  5160. return adt$3.single(true, constant$1(compSpec));
  5161. }
  5162. return get$g(placeholders, compSpec.name).fold(() => {
  5163. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  5164. }, newSpec => newSpec.replace());
  5165. };
  5166. const scan = (owner, detail, compSpec, placeholders) => {
  5167. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  5168. return subPlaceholder(owner, detail, compSpec, placeholders);
  5169. } else {
  5170. return adt$3.single(false, constant$1(compSpec));
  5171. }
  5172. };
  5173. const substitute = (owner, detail, compSpec, placeholders) => {
  5174. const base = scan(owner, detail, compSpec, placeholders);
  5175. return base.fold((req, valueThunk) => {
  5176. const value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  5177. const childSpecs = get$g(value, 'components').getOr([]);
  5178. const substituted = bind$3(childSpecs, c => substitute(owner, detail, c, placeholders));
  5179. return [{
  5180. ...value,
  5181. components: substituted
  5182. }];
  5183. }, (req, valuesThunk) => {
  5184. if (isSubstituted(compSpec)) {
  5185. const values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5186. const preprocessor = compSpec.validated.preprocess.getOr(identity);
  5187. return preprocessor(values);
  5188. } else {
  5189. return valuesThunk(detail);
  5190. }
  5191. });
  5192. };
  5193. const substituteAll = (owner, detail, components, placeholders) => bind$3(components, c => substitute(owner, detail, c, placeholders));
  5194. const oneReplace = (label, replacements) => {
  5195. let called = false;
  5196. const used = () => called;
  5197. const replace = () => {
  5198. if (called) {
  5199. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5200. }
  5201. called = true;
  5202. return replacements;
  5203. };
  5204. const required = () => replacements.fold((req, _) => req, (req, _) => req);
  5205. return {
  5206. name: constant$1(label),
  5207. required,
  5208. used,
  5209. replace
  5210. };
  5211. };
  5212. const substitutePlaces = (owner, detail, components, placeholders) => {
  5213. const ps = map$1(placeholders, (ph, name) => oneReplace(name, ph));
  5214. const outcome = substituteAll(owner, detail, components, ps);
  5215. each(ps, p => {
  5216. if (p.used() === false && p.required()) {
  5217. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  5218. }
  5219. });
  5220. return outcome;
  5221. };
  5222. const single$2 = adt$3.single;
  5223. const multiple = adt$3.multiple;
  5224. const placeholder = constant$1(_placeholder);
  5225. const adt$2 = Adt.generate([
  5226. { required: ['data'] },
  5227. { external: ['data'] },
  5228. { optional: ['data'] },
  5229. { group: ['data'] }
  5230. ]);
  5231. const fFactory = defaulted('factory', { sketch: identity });
  5232. const fSchema = defaulted('schema', []);
  5233. const fName = required$1('name');
  5234. const fPname = field$1('pname', 'pname', defaultedThunk(typeSpec => '<alloy.' + generate$6(typeSpec.name) + '>'), anyValue());
  5235. const fGroupSchema = customField('schema', () => [option$3('preprocess')]);
  5236. const fDefaults = defaulted('defaults', constant$1({}));
  5237. const fOverrides = defaulted('overrides', constant$1({}));
  5238. const requiredSpec = objOf([
  5239. fFactory,
  5240. fSchema,
  5241. fName,
  5242. fPname,
  5243. fDefaults,
  5244. fOverrides
  5245. ]);
  5246. const externalSpec = objOf([
  5247. fFactory,
  5248. fSchema,
  5249. fName,
  5250. fDefaults,
  5251. fOverrides
  5252. ]);
  5253. const optionalSpec = objOf([
  5254. fFactory,
  5255. fSchema,
  5256. fName,
  5257. fPname,
  5258. fDefaults,
  5259. fOverrides
  5260. ]);
  5261. const groupSpec = objOf([
  5262. fFactory,
  5263. fGroupSchema,
  5264. fName,
  5265. required$1('unit'),
  5266. fPname,
  5267. fDefaults,
  5268. fOverrides
  5269. ]);
  5270. const asNamedPart = part => {
  5271. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  5272. };
  5273. const name$2 = part => {
  5274. const get = data => data.name;
  5275. return part.fold(get, get, get, get);
  5276. };
  5277. const asCommon = part => {
  5278. return part.fold(identity, identity, identity, identity);
  5279. };
  5280. const convert = (adtConstructor, partSchema) => spec => {
  5281. const data = asRawOrDie$1('Converting part type', partSchema, spec);
  5282. return adtConstructor(data);
  5283. };
  5284. const required = convert(adt$2.required, requiredSpec);
  5285. const external = convert(adt$2.external, externalSpec);
  5286. const optional = convert(adt$2.optional, optionalSpec);
  5287. const group = convert(adt$2.group, groupSpec);
  5288. const original = constant$1('entirety');
  5289. var PartType = /*#__PURE__*/Object.freeze({
  5290. __proto__: null,
  5291. required: required,
  5292. external: external,
  5293. optional: optional,
  5294. group: group,
  5295. asNamedPart: asNamedPart,
  5296. name: name$2,
  5297. asCommon: asCommon,
  5298. original: original
  5299. });
  5300. const combine = (detail, data, partSpec, partValidated) => deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5301. const subs = (owner, detail, parts) => {
  5302. const internals = {};
  5303. const externals = {};
  5304. each$1(parts, part => {
  5305. part.fold(data => {
  5306. internals[data.pname] = single$2(true, (detail, partSpec, partValidated) => data.factory.sketch(combine(detail, data, partSpec, partValidated)));
  5307. }, data => {
  5308. const partSpec = detail.parts[data.name];
  5309. externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  5310. }, data => {
  5311. internals[data.pname] = single$2(false, (detail, partSpec, partValidated) => data.factory.sketch(combine(detail, data, partSpec, partValidated)));
  5312. }, data => {
  5313. internals[data.pname] = multiple(true, (detail, _partSpec, _partValidated) => {
  5314. const units = detail[data.name];
  5315. return map$2(units, u => data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u))));
  5316. });
  5317. });
  5318. });
  5319. return {
  5320. internals: constant$1(internals),
  5321. externals: constant$1(externals)
  5322. };
  5323. };
  5324. const generate$3 = (owner, parts) => {
  5325. const r = {};
  5326. each$1(parts, part => {
  5327. asNamedPart(part).each(np => {
  5328. const g = doGenerateOne(owner, np.pname);
  5329. r[np.name] = config => {
  5330. const validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  5331. return {
  5332. ...g,
  5333. config,
  5334. validated
  5335. };
  5336. };
  5337. });
  5338. });
  5339. return r;
  5340. };
  5341. const doGenerateOne = (owner, pname) => ({
  5342. uiType: placeholder(),
  5343. owner,
  5344. name: pname
  5345. });
  5346. const generateOne$1 = (owner, pname, config) => ({
  5347. uiType: placeholder(),
  5348. owner,
  5349. name: pname,
  5350. config,
  5351. validated: {}
  5352. });
  5353. const schemas = parts => bind$3(parts, part => part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(data => requiredObjOf(data.name, data.schema.concat([snapshot(original())]))).toArray());
  5354. const names = parts => map$2(parts, name$2);
  5355. const substitutes = (owner, detail, parts) => subs(owner, detail, parts);
  5356. const components$1 = (owner, detail, internals) => substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  5357. const getPart = (component, detail, partKey) => {
  5358. const uid = detail.partUids[partKey];
  5359. return component.getSystem().getByUid(uid).toOptional();
  5360. };
  5361. const getPartOrDie = (component, detail, partKey) => getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  5362. const getParts = (component, detail, partKeys) => {
  5363. const r = {};
  5364. const uids = detail.partUids;
  5365. const system = component.getSystem();
  5366. each$1(partKeys, pk => {
  5367. r[pk] = constant$1(system.getByUid(uids[pk]));
  5368. });
  5369. return r;
  5370. };
  5371. const getAllParts = (component, detail) => {
  5372. const system = component.getSystem();
  5373. return map$1(detail.partUids, (pUid, _k) => constant$1(system.getByUid(pUid)));
  5374. };
  5375. const getAllPartNames = detail => keys(detail.partUids);
  5376. const getPartsOrDie = (component, detail, partKeys) => {
  5377. const r = {};
  5378. const uids = detail.partUids;
  5379. const system = component.getSystem();
  5380. each$1(partKeys, pk => {
  5381. r[pk] = constant$1(system.getByUid(uids[pk]).getOrDie());
  5382. });
  5383. return r;
  5384. };
  5385. const defaultUids = (baseUid, partTypes) => {
  5386. const partNames = names(partTypes);
  5387. return wrapAll(map$2(partNames, pn => ({
  5388. key: pn,
  5389. value: baseUid + '-' + pn
  5390. })));
  5391. };
  5392. const defaultUidsSchema = partTypes => field$1('partUids', 'partUids', mergeWithThunk(spec => defaultUids(spec.uid, partTypes)), anyValue());
  5393. var AlloyParts = /*#__PURE__*/Object.freeze({
  5394. __proto__: null,
  5395. generate: generate$3,
  5396. generateOne: generateOne$1,
  5397. schemas: schemas,
  5398. names: names,
  5399. substitutes: substitutes,
  5400. components: components$1,
  5401. defaultUids: defaultUids,
  5402. defaultUidsSchema: defaultUidsSchema,
  5403. getAllParts: getAllParts,
  5404. getAllPartNames: getAllPartNames,
  5405. getPart: getPart,
  5406. getPartOrDie: getPartOrDie,
  5407. getParts: getParts,
  5408. getPartsOrDie: getPartsOrDie
  5409. });
  5410. const base = (partSchemas, partUidsSchemas) => {
  5411. const ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  5412. return ps.concat([
  5413. required$1('uid'),
  5414. defaulted('dom', {}),
  5415. defaulted('components', []),
  5416. snapshot('originalSpec'),
  5417. defaulted('debug.sketcher', {})
  5418. ]).concat(partUidsSchemas);
  5419. };
  5420. const asRawOrDie = (label, schema, spec, partSchemas, partUidsSchemas) => {
  5421. const baseS = base(partSchemas, partUidsSchemas);
  5422. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  5423. };
  5424. const single$1 = (owner, schema, factory, spec) => {
  5425. const specWithUid = supplyUid(spec);
  5426. const detail = asRawOrDie(owner, schema, specWithUid, [], []);
  5427. return factory(detail, specWithUid);
  5428. };
  5429. const composite$1 = (owner, schema, partTypes, factory, spec) => {
  5430. const specWithUid = supplyUid(spec);
  5431. const partSchemas = schemas(partTypes);
  5432. const partUidsSchema = defaultUidsSchema(partTypes);
  5433. const detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  5434. const subs = substitutes(owner, detail, partTypes);
  5435. const components = components$1(owner, detail, subs.internals());
  5436. return factory(detail, components, specWithUid, subs.externals());
  5437. };
  5438. const hasUid = spec => has$2(spec, 'uid');
  5439. const supplyUid = spec => {
  5440. return hasUid(spec) ? spec : {
  5441. ...spec,
  5442. uid: generate$5('uid')
  5443. };
  5444. };
  5445. const isSketchSpec = spec => {
  5446. return spec.uid !== undefined;
  5447. };
  5448. const singleSchema = objOfOnly([
  5449. required$1('name'),
  5450. required$1('factory'),
  5451. required$1('configFields'),
  5452. defaulted('apis', {}),
  5453. defaulted('extraApis', {})
  5454. ]);
  5455. const compositeSchema = objOfOnly([
  5456. required$1('name'),
  5457. required$1('factory'),
  5458. required$1('configFields'),
  5459. required$1('partFields'),
  5460. defaulted('apis', {}),
  5461. defaulted('extraApis', {})
  5462. ]);
  5463. const single = rawConfig => {
  5464. const config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  5465. const sketch = spec => single$1(config.name, config.configFields, config.factory, spec);
  5466. const apis = map$1(config.apis, makeApi);
  5467. const extraApis = map$1(config.extraApis, (f, k) => markAsExtraApi(f, k));
  5468. return {
  5469. name: config.name,
  5470. configFields: config.configFields,
  5471. sketch,
  5472. ...apis,
  5473. ...extraApis
  5474. };
  5475. };
  5476. const composite = rawConfig => {
  5477. const config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  5478. const sketch = spec => composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  5479. const parts = generate$3(config.name, config.partFields);
  5480. const apis = map$1(config.apis, makeApi);
  5481. const extraApis = map$1(config.extraApis, (f, k) => markAsExtraApi(f, k));
  5482. return {
  5483. name: config.name,
  5484. partFields: config.partFields,
  5485. configFields: config.configFields,
  5486. sketch,
  5487. parts,
  5488. ...apis,
  5489. ...extraApis
  5490. };
  5491. };
  5492. const inside = target => isTag('input')(target) && get$f(target, 'type') !== 'radio' || isTag('textarea')(target);
  5493. const getCurrent = (component, composeConfig, _composeState) => composeConfig.find(component);
  5494. var ComposeApis = /*#__PURE__*/Object.freeze({
  5495. __proto__: null,
  5496. getCurrent: getCurrent
  5497. });
  5498. const ComposeSchema = [required$1('find')];
  5499. const Composing = create$3({
  5500. fields: ComposeSchema,
  5501. name: 'composing',
  5502. apis: ComposeApis
  5503. });
  5504. const nativeDisabled = [
  5505. 'input',
  5506. 'button',
  5507. 'textarea',
  5508. 'select'
  5509. ];
  5510. const onLoad$1 = (component, disableConfig, disableState) => {
  5511. const f = disableConfig.disabled() ? disable : enable;
  5512. f(component, disableConfig);
  5513. };
  5514. const hasNative = (component, config) => config.useNative === true && contains$2(nativeDisabled, name$3(component.element));
  5515. const nativeIsDisabled = component => has$1(component.element, 'disabled');
  5516. const nativeDisable = component => {
  5517. set$9(component.element, 'disabled', 'disabled');
  5518. };
  5519. const nativeEnable = component => {
  5520. remove$7(component.element, 'disabled');
  5521. };
  5522. const ariaIsDisabled = component => get$f(component.element, 'aria-disabled') === 'true';
  5523. const ariaDisable = component => {
  5524. set$9(component.element, 'aria-disabled', 'true');
  5525. };
  5526. const ariaEnable = component => {
  5527. set$9(component.element, 'aria-disabled', 'false');
  5528. };
  5529. const disable = (component, disableConfig, _disableState) => {
  5530. disableConfig.disableClass.each(disableClass => {
  5531. add$2(component.element, disableClass);
  5532. });
  5533. const f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  5534. f(component);
  5535. disableConfig.onDisabled(component);
  5536. };
  5537. const enable = (component, disableConfig, _disableState) => {
  5538. disableConfig.disableClass.each(disableClass => {
  5539. remove$2(component.element, disableClass);
  5540. });
  5541. const f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  5542. f(component);
  5543. disableConfig.onEnabled(component);
  5544. };
  5545. const isDisabled = (component, disableConfig) => hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  5546. const set$4 = (component, disableConfig, disableState, disabled) => {
  5547. const f = disabled ? disable : enable;
  5548. f(component, disableConfig);
  5549. };
  5550. var DisableApis = /*#__PURE__*/Object.freeze({
  5551. __proto__: null,
  5552. enable: enable,
  5553. disable: disable,
  5554. isDisabled: isDisabled,
  5555. onLoad: onLoad$1,
  5556. set: set$4
  5557. });
  5558. const exhibit$5 = (base, disableConfig) => nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  5559. const events$e = (disableConfig, disableState) => derive$2([
  5560. abort(execute$5(), (component, _simulatedEvent) => isDisabled(component, disableConfig)),
  5561. loadEvent(disableConfig, disableState, onLoad$1)
  5562. ]);
  5563. var ActiveDisable = /*#__PURE__*/Object.freeze({
  5564. __proto__: null,
  5565. exhibit: exhibit$5,
  5566. events: events$e
  5567. });
  5568. var DisableSchema = [
  5569. defaultedFunction('disabled', never),
  5570. defaulted('useNative', true),
  5571. option$3('disableClass'),
  5572. onHandler('onDisabled'),
  5573. onHandler('onEnabled')
  5574. ];
  5575. const Disabling = create$3({
  5576. fields: DisableSchema,
  5577. name: 'disabling',
  5578. active: ActiveDisable,
  5579. apis: DisableApis
  5580. });
  5581. const dehighlightAllExcept = (component, hConfig, hState, skip) => {
  5582. const highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  5583. each$1(highlighted, h => {
  5584. if (!exists(skip, skipComp => skipComp.element === h)) {
  5585. remove$2(h, hConfig.highlightClass);
  5586. component.getSystem().getByDom(h).each(target => {
  5587. hConfig.onDehighlight(component, target);
  5588. emit(target, dehighlight$1());
  5589. });
  5590. }
  5591. });
  5592. };
  5593. const dehighlightAll = (component, hConfig, hState) => dehighlightAllExcept(component, hConfig, hState, []);
  5594. const dehighlight = (component, hConfig, hState, target) => {
  5595. if (isHighlighted(component, hConfig, hState, target)) {
  5596. remove$2(target.element, hConfig.highlightClass);
  5597. hConfig.onDehighlight(component, target);
  5598. emit(target, dehighlight$1());
  5599. }
  5600. };
  5601. const highlight = (component, hConfig, hState, target) => {
  5602. dehighlightAllExcept(component, hConfig, hState, [target]);
  5603. if (!isHighlighted(component, hConfig, hState, target)) {
  5604. add$2(target.element, hConfig.highlightClass);
  5605. hConfig.onHighlight(component, target);
  5606. emit(target, highlight$1());
  5607. }
  5608. };
  5609. const highlightFirst = (component, hConfig, hState) => {
  5610. getFirst(component, hConfig).each(firstComp => {
  5611. highlight(component, hConfig, hState, firstComp);
  5612. });
  5613. };
  5614. const highlightLast = (component, hConfig, hState) => {
  5615. getLast(component, hConfig).each(lastComp => {
  5616. highlight(component, hConfig, hState, lastComp);
  5617. });
  5618. };
  5619. const highlightAt = (component, hConfig, hState, index) => {
  5620. getByIndex(component, hConfig, hState, index).fold(err => {
  5621. throw err;
  5622. }, firstComp => {
  5623. highlight(component, hConfig, hState, firstComp);
  5624. });
  5625. };
  5626. const highlightBy = (component, hConfig, hState, predicate) => {
  5627. const candidates = getCandidates(component, hConfig);
  5628. const targetComp = find$5(candidates, predicate);
  5629. targetComp.each(c => {
  5630. highlight(component, hConfig, hState, c);
  5631. });
  5632. };
  5633. const isHighlighted = (component, hConfig, hState, queryTarget) => has(queryTarget.element, hConfig.highlightClass);
  5634. const getHighlighted = (component, hConfig, _hState) => descendant(component.element, '.' + hConfig.highlightClass).bind(e => component.getSystem().getByDom(e).toOptional());
  5635. const getByIndex = (component, hConfig, hState, index) => {
  5636. const items = descendants(component.element, '.' + hConfig.itemClass);
  5637. return Optional.from(items[index]).fold(() => Result.error(new Error('No element found with index ' + index)), component.getSystem().getByDom);
  5638. };
  5639. const getFirst = (component, hConfig, _hState) => descendant(component.element, '.' + hConfig.itemClass).bind(e => component.getSystem().getByDom(e).toOptional());
  5640. const getLast = (component, hConfig, _hState) => {
  5641. const items = descendants(component.element, '.' + hConfig.itemClass);
  5642. const last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  5643. return last.bind(c => component.getSystem().getByDom(c).toOptional());
  5644. };
  5645. const getDelta$2 = (component, hConfig, hState, delta) => {
  5646. const items = descendants(component.element, '.' + hConfig.itemClass);
  5647. const current = findIndex$1(items, item => has(item, hConfig.highlightClass));
  5648. return current.bind(selected => {
  5649. const dest = cycleBy(selected, delta, 0, items.length - 1);
  5650. return component.getSystem().getByDom(items[dest]).toOptional();
  5651. });
  5652. };
  5653. const getPrevious = (component, hConfig, hState) => getDelta$2(component, hConfig, hState, -1);
  5654. const getNext = (component, hConfig, hState) => getDelta$2(component, hConfig, hState, +1);
  5655. const getCandidates = (component, hConfig, _hState) => {
  5656. const items = descendants(component.element, '.' + hConfig.itemClass);
  5657. return cat(map$2(items, i => component.getSystem().getByDom(i).toOptional()));
  5658. };
  5659. var HighlightApis = /*#__PURE__*/Object.freeze({
  5660. __proto__: null,
  5661. dehighlightAll: dehighlightAll,
  5662. dehighlight: dehighlight,
  5663. highlight: highlight,
  5664. highlightFirst: highlightFirst,
  5665. highlightLast: highlightLast,
  5666. highlightAt: highlightAt,
  5667. highlightBy: highlightBy,
  5668. isHighlighted: isHighlighted,
  5669. getHighlighted: getHighlighted,
  5670. getFirst: getFirst,
  5671. getLast: getLast,
  5672. getPrevious: getPrevious,
  5673. getNext: getNext,
  5674. getCandidates: getCandidates
  5675. });
  5676. var HighlightSchema = [
  5677. required$1('highlightClass'),
  5678. required$1('itemClass'),
  5679. onHandler('onHighlight'),
  5680. onHandler('onDehighlight')
  5681. ];
  5682. const Highlighting = create$3({
  5683. fields: HighlightSchema,
  5684. name: 'highlighting',
  5685. apis: HighlightApis
  5686. });
  5687. const BACKSPACE = [8];
  5688. const TAB = [9];
  5689. const ENTER = [13];
  5690. const ESCAPE = [27];
  5691. const SPACE = [32];
  5692. const LEFT = [37];
  5693. const UP = [38];
  5694. const RIGHT = [39];
  5695. const DOWN = [40];
  5696. const cyclePrev = (values, index, predicate) => {
  5697. const before = reverse(values.slice(0, index));
  5698. const after = reverse(values.slice(index + 1));
  5699. return find$5(before.concat(after), predicate);
  5700. };
  5701. const tryPrev = (values, index, predicate) => {
  5702. const before = reverse(values.slice(0, index));
  5703. return find$5(before, predicate);
  5704. };
  5705. const cycleNext = (values, index, predicate) => {
  5706. const before = values.slice(0, index);
  5707. const after = values.slice(index + 1);
  5708. return find$5(after.concat(before), predicate);
  5709. };
  5710. const tryNext = (values, index, predicate) => {
  5711. const after = values.slice(index + 1);
  5712. return find$5(after, predicate);
  5713. };
  5714. const inSet = keys => event => {
  5715. const raw = event.raw;
  5716. return contains$2(keys, raw.which);
  5717. };
  5718. const and = preds => event => forall(preds, pred => pred(event));
  5719. const isShift = event => {
  5720. const raw = event.raw;
  5721. return raw.shiftKey === true;
  5722. };
  5723. const isControl = event => {
  5724. const raw = event.raw;
  5725. return raw.ctrlKey === true;
  5726. };
  5727. const isNotShift = not(isShift);
  5728. const rule = (matches, action) => ({
  5729. matches,
  5730. classification: action
  5731. });
  5732. const choose = (transitions, event) => {
  5733. const transition = find$5(transitions, t => t.matches(event));
  5734. return transition.map(t => t.classification);
  5735. };
  5736. const reportFocusShifting = (component, prevFocus, newFocus) => {
  5737. const noChange = prevFocus.exists(p => newFocus.exists(n => eq(n, p)));
  5738. if (!noChange) {
  5739. emitWith(component, focusShifted(), {
  5740. prevFocus,
  5741. newFocus
  5742. });
  5743. }
  5744. };
  5745. const dom$2 = () => {
  5746. const get = component => search(component.element);
  5747. const set = (component, focusee) => {
  5748. const prevFocus = get(component);
  5749. component.getSystem().triggerFocus(focusee, component.element);
  5750. const newFocus = get(component);
  5751. reportFocusShifting(component, prevFocus, newFocus);
  5752. };
  5753. return {
  5754. get,
  5755. set
  5756. };
  5757. };
  5758. const highlights = () => {
  5759. const get = component => Highlighting.getHighlighted(component).map(item => item.element);
  5760. const set = (component, element) => {
  5761. const prevFocus = get(component);
  5762. component.getSystem().getByDom(element).fold(noop, item => {
  5763. Highlighting.highlight(component, item);
  5764. });
  5765. const newFocus = get(component);
  5766. reportFocusShifting(component, prevFocus, newFocus);
  5767. };
  5768. return {
  5769. get,
  5770. set
  5771. };
  5772. };
  5773. var FocusInsideModes;
  5774. (function (FocusInsideModes) {
  5775. FocusInsideModes['OnFocusMode'] = 'onFocus';
  5776. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  5777. FocusInsideModes['OnApiMode'] = 'onApi';
  5778. }(FocusInsideModes || (FocusInsideModes = {})));
  5779. const typical = (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) => {
  5780. const schema = () => infoSchema.concat([
  5781. defaulted('focusManager', dom$2()),
  5782. defaultedOf('focusInside', 'onFocus', valueOf(val => contains$2([
  5783. 'onFocus',
  5784. 'onEnterOrSpace',
  5785. 'onApi'
  5786. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside'))),
  5787. output$1('handler', me),
  5788. output$1('state', stateInit),
  5789. output$1('sendFocusIn', optFocusIn)
  5790. ]);
  5791. const processKey = (component, simulatedEvent, getRules, keyingConfig, keyingState) => {
  5792. const rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  5793. return choose(rules, simulatedEvent.event).bind(rule => rule(component, simulatedEvent, keyingConfig, keyingState));
  5794. };
  5795. const toEvents = (keyingConfig, keyingState) => {
  5796. const onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(focusIn => run$1(focus$4(), (component, simulatedEvent) => {
  5797. focusIn(component, keyingConfig, keyingState);
  5798. simulatedEvent.stop();
  5799. }));
  5800. const tryGoInsideComponent = (component, simulatedEvent) => {
  5801. const isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  5802. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  5803. optFocusIn(keyingConfig).each(focusIn => {
  5804. focusIn(component, keyingConfig, keyingState);
  5805. simulatedEvent.stop();
  5806. });
  5807. }
  5808. };
  5809. const keyboardEvents = [
  5810. run$1(keydown(), (component, simulatedEvent) => {
  5811. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(() => {
  5812. tryGoInsideComponent(component, simulatedEvent);
  5813. }, _ => {
  5814. simulatedEvent.stop();
  5815. });
  5816. }),
  5817. run$1(keyup(), (component, simulatedEvent) => {
  5818. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(_ => {
  5819. simulatedEvent.stop();
  5820. });
  5821. })
  5822. ];
  5823. return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
  5824. };
  5825. const me = {
  5826. schema,
  5827. processKey,
  5828. toEvents
  5829. };
  5830. return me;
  5831. };
  5832. const create$1 = cyclicField => {
  5833. const schema = [
  5834. option$3('onEscape'),
  5835. option$3('onEnter'),
  5836. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  5837. defaulted('firstTabstop', 0),
  5838. defaulted('useTabstopAt', always),
  5839. option$3('visibilitySelector')
  5840. ].concat([cyclicField]);
  5841. const isVisible = (tabbingConfig, element) => {
  5842. const target = tabbingConfig.visibilitySelector.bind(sel => closest$1(element, sel)).getOr(element);
  5843. return get$d(target) > 0;
  5844. };
  5845. const findInitial = (component, tabbingConfig) => {
  5846. const tabstops = descendants(component.element, tabbingConfig.selector);
  5847. const visibles = filter$2(tabstops, elem => isVisible(tabbingConfig, elem));
  5848. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  5849. };
  5850. const findCurrent = (component, tabbingConfig) => tabbingConfig.focusManager.get(component).bind(elem => closest$1(elem, tabbingConfig.selector));
  5851. const isTabstop = (tabbingConfig, element) => isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  5852. const focusIn = (component, tabbingConfig, _tabbingState) => {
  5853. findInitial(component, tabbingConfig).each(target => {
  5854. tabbingConfig.focusManager.set(component, target);
  5855. });
  5856. };
  5857. const goFromTabstop = (component, tabstops, stopIndex, tabbingConfig, cycle) => cycle(tabstops, stopIndex, elem => isTabstop(tabbingConfig, elem)).fold(() => tabbingConfig.cyclic ? Optional.some(true) : Optional.none(), target => {
  5858. tabbingConfig.focusManager.set(component, target);
  5859. return Optional.some(true);
  5860. });
  5861. const go = (component, _simulatedEvent, tabbingConfig, cycle) => {
  5862. const tabstops = descendants(component.element, tabbingConfig.selector);
  5863. return findCurrent(component, tabbingConfig).bind(tabstop => {
  5864. const optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  5865. return optStopIndex.bind(stopIndex => goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle));
  5866. });
  5867. };
  5868. const goBackwards = (component, simulatedEvent, tabbingConfig) => {
  5869. const navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  5870. return go(component, simulatedEvent, tabbingConfig, navigate);
  5871. };
  5872. const goForwards = (component, simulatedEvent, tabbingConfig) => {
  5873. const navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  5874. return go(component, simulatedEvent, tabbingConfig, navigate);
  5875. };
  5876. const execute = (component, simulatedEvent, tabbingConfig) => tabbingConfig.onEnter.bind(f => f(component, simulatedEvent));
  5877. const exit = (component, simulatedEvent, tabbingConfig) => tabbingConfig.onEscape.bind(f => f(component, simulatedEvent));
  5878. const getKeydownRules = constant$1([
  5879. rule(and([
  5880. isShift,
  5881. inSet(TAB)
  5882. ]), goBackwards),
  5883. rule(inSet(TAB), goForwards),
  5884. rule(inSet(ESCAPE), exit),
  5885. rule(and([
  5886. isNotShift,
  5887. inSet(ENTER)
  5888. ]), execute)
  5889. ]);
  5890. const getKeyupRules = constant$1([]);
  5891. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, () => Optional.some(focusIn));
  5892. };
  5893. var AcyclicType = create$1(customField('cyclic', never));
  5894. var CyclicType = create$1(customField('cyclic', always));
  5895. const doDefaultExecute = (component, _simulatedEvent, focused) => {
  5896. dispatch(component, focused, execute$5());
  5897. return Optional.some(true);
  5898. };
  5899. const defaultExecute = (component, simulatedEvent, focused) => {
  5900. const isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  5901. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  5902. };
  5903. const stopEventForFirefox = (_component, _simulatedEvent) => Optional.some(true);
  5904. const schema$v = [
  5905. defaulted('execute', defaultExecute),
  5906. defaulted('useSpace', false),
  5907. defaulted('useEnter', true),
  5908. defaulted('useControlEnter', false),
  5909. defaulted('useDown', false)
  5910. ];
  5911. const execute$4 = (component, simulatedEvent, executeConfig) => executeConfig.execute(component, simulatedEvent, component.element);
  5912. const getKeydownRules$5 = (component, _simulatedEvent, executeConfig, _executeState) => {
  5913. const spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  5914. const enterExec = executeConfig.useEnter ? ENTER : [];
  5915. const downExec = executeConfig.useDown ? DOWN : [];
  5916. const execKeys = spaceExec.concat(enterExec).concat(downExec);
  5917. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  5918. isControl,
  5919. inSet(ENTER)
  5920. ]), execute$4)] : []);
  5921. };
  5922. const getKeyupRules$5 = (component, _simulatedEvent, executeConfig, _executeState) => executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  5923. var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, () => Optional.none());
  5924. const flatgrid$1 = () => {
  5925. const dimensions = value$2();
  5926. const setGridSize = (numRows, numColumns) => {
  5927. dimensions.set({
  5928. numRows,
  5929. numColumns
  5930. });
  5931. };
  5932. const getNumRows = () => dimensions.get().map(d => d.numRows);
  5933. const getNumColumns = () => dimensions.get().map(d => d.numColumns);
  5934. return nu$8({
  5935. readState: () => dimensions.get().map(d => ({
  5936. numRows: String(d.numRows),
  5937. numColumns: String(d.numColumns)
  5938. })).getOr({
  5939. numRows: '?',
  5940. numColumns: '?'
  5941. }),
  5942. setGridSize,
  5943. getNumRows,
  5944. getNumColumns
  5945. });
  5946. };
  5947. const init$d = spec => spec.state(spec);
  5948. var KeyingState = /*#__PURE__*/Object.freeze({
  5949. __proto__: null,
  5950. flatgrid: flatgrid$1,
  5951. init: init$d
  5952. });
  5953. const useH = movement => (component, simulatedEvent, config, state) => {
  5954. const move = movement(component.element);
  5955. return use(move, component, simulatedEvent, config, state);
  5956. };
  5957. const west$1 = (moveLeft, moveRight) => {
  5958. const movement = onDirection(moveLeft, moveRight);
  5959. return useH(movement);
  5960. };
  5961. const east$1 = (moveLeft, moveRight) => {
  5962. const movement = onDirection(moveRight, moveLeft);
  5963. return useH(movement);
  5964. };
  5965. const useV = move => (component, simulatedEvent, config, state) => use(move, component, simulatedEvent, config, state);
  5966. const use = (move, component, simulatedEvent, config, state) => {
  5967. const outcome = config.focusManager.get(component).bind(focused => move(component.element, focused, config, state));
  5968. return outcome.map(newFocus => {
  5969. config.focusManager.set(component, newFocus);
  5970. return true;
  5971. });
  5972. };
  5973. const north$1 = useV;
  5974. const south$1 = useV;
  5975. const move$1 = useV;
  5976. const isHidden$1 = dom => dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  5977. const isVisible = element => !isHidden$1(element.dom);
  5978. const locate = (candidates, predicate) => findIndex$1(candidates, predicate).map(index => ({
  5979. index,
  5980. candidates
  5981. }));
  5982. const locateVisible = (container, current, selector) => {
  5983. const predicate = x => eq(x, current);
  5984. const candidates = descendants(container, selector);
  5985. const visible = filter$2(candidates, isVisible);
  5986. return locate(visible, predicate);
  5987. };
  5988. const findIndex = (elements, target) => findIndex$1(elements, elem => eq(target, elem));
  5989. const withGrid = (values, index, numCols, f) => {
  5990. const oldRow = Math.floor(index / numCols);
  5991. const oldColumn = index % numCols;
  5992. return f(oldRow, oldColumn).bind(address => {
  5993. const newIndex = address.row * numCols + address.column;
  5994. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  5995. });
  5996. };
  5997. const cycleHorizontal$1 = (values, index, numRows, numCols, delta) => withGrid(values, index, numCols, (oldRow, oldColumn) => {
  5998. const onLastRow = oldRow === numRows - 1;
  5999. const colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  6000. const newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  6001. return Optional.some({
  6002. row: oldRow,
  6003. column: newColumn
  6004. });
  6005. });
  6006. const cycleVertical$1 = (values, index, numRows, numCols, delta) => withGrid(values, index, numCols, (oldRow, oldColumn) => {
  6007. const newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  6008. const onLastRow = newRow === numRows - 1;
  6009. const colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  6010. const newCol = clamp(oldColumn, 0, colsInRow - 1);
  6011. return Optional.some({
  6012. row: newRow,
  6013. column: newCol
  6014. });
  6015. });
  6016. const cycleRight$1 = (values, index, numRows, numCols) => cycleHorizontal$1(values, index, numRows, numCols, +1);
  6017. const cycleLeft$1 = (values, index, numRows, numCols) => cycleHorizontal$1(values, index, numRows, numCols, -1);
  6018. const cycleUp$1 = (values, index, numRows, numCols) => cycleVertical$1(values, index, numRows, numCols, -1);
  6019. const cycleDown$1 = (values, index, numRows, numCols) => cycleVertical$1(values, index, numRows, numCols, +1);
  6020. const schema$u = [
  6021. required$1('selector'),
  6022. defaulted('execute', defaultExecute),
  6023. onKeyboardHandler('onEscape'),
  6024. defaulted('captureTab', false),
  6025. initSize()
  6026. ];
  6027. const focusIn$3 = (component, gridConfig, _gridState) => {
  6028. descendant(component.element, gridConfig.selector).each(first => {
  6029. gridConfig.focusManager.set(component, first);
  6030. });
  6031. };
  6032. const findCurrent$1 = (component, gridConfig) => gridConfig.focusManager.get(component).bind(elem => closest$1(elem, gridConfig.selector));
  6033. const execute$3 = (component, simulatedEvent, gridConfig, _gridState) => findCurrent$1(component, gridConfig).bind(focused => gridConfig.execute(component, simulatedEvent, focused));
  6034. const doMove$2 = cycle => (element, focused, gridConfig, gridState) => locateVisible(element, focused, gridConfig.selector).bind(identified => cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns)));
  6035. const handleTab = (_component, _simulatedEvent, gridConfig) => gridConfig.captureTab ? Optional.some(true) : Optional.none();
  6036. const doEscape$1 = (component, simulatedEvent, gridConfig) => gridConfig.onEscape(component, simulatedEvent);
  6037. const moveLeft$3 = doMove$2(cycleLeft$1);
  6038. const moveRight$3 = doMove$2(cycleRight$1);
  6039. const moveNorth$1 = doMove$2(cycleUp$1);
  6040. const moveSouth$1 = doMove$2(cycleDown$1);
  6041. const getKeydownRules$4 = constant$1([
  6042. rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
  6043. rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
  6044. rule(inSet(UP), north$1(moveNorth$1)),
  6045. rule(inSet(DOWN), south$1(moveSouth$1)),
  6046. rule(and([
  6047. isShift,
  6048. inSet(TAB)
  6049. ]), handleTab),
  6050. rule(and([
  6051. isNotShift,
  6052. inSet(TAB)
  6053. ]), handleTab),
  6054. rule(inSet(ESCAPE), doEscape$1),
  6055. rule(inSet(SPACE.concat(ENTER)), execute$3)
  6056. ]);
  6057. const getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  6058. var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, () => Optional.some(focusIn$3));
  6059. const horizontal = (container, selector, current, delta) => {
  6060. const isDisabledButton = candidate => name$3(candidate) === 'button' && get$f(candidate, 'disabled') === 'disabled';
  6061. const tryCycle = (initial, index, candidates) => {
  6062. const newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  6063. if (newIndex === initial) {
  6064. return Optional.none();
  6065. } else {
  6066. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  6067. }
  6068. };
  6069. return locateVisible(container, current, selector).bind(identified => {
  6070. const index = identified.index;
  6071. const candidates = identified.candidates;
  6072. return tryCycle(index, index, candidates);
  6073. });
  6074. };
  6075. const schema$t = [
  6076. required$1('selector'),
  6077. defaulted('getInitial', Optional.none),
  6078. defaulted('execute', defaultExecute),
  6079. onKeyboardHandler('onEscape'),
  6080. defaulted('executeOnMove', false),
  6081. defaulted('allowVertical', true)
  6082. ];
  6083. const findCurrent = (component, flowConfig) => flowConfig.focusManager.get(component).bind(elem => closest$1(elem, flowConfig.selector));
  6084. const execute$2 = (component, simulatedEvent, flowConfig) => findCurrent(component, flowConfig).bind(focused => flowConfig.execute(component, simulatedEvent, focused));
  6085. const focusIn$2 = (component, flowConfig, _state) => {
  6086. flowConfig.getInitial(component).orThunk(() => descendant(component.element, flowConfig.selector)).each(first => {
  6087. flowConfig.focusManager.set(component, first);
  6088. });
  6089. };
  6090. const moveLeft$2 = (element, focused, info) => horizontal(element, info.selector, focused, -1);
  6091. const moveRight$2 = (element, focused, info) => horizontal(element, info.selector, focused, +1);
  6092. const doMove$1 = movement => (component, simulatedEvent, flowConfig, flowState) => movement(component, simulatedEvent, flowConfig, flowState).bind(() => flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true));
  6093. const doEscape = (component, simulatedEvent, flowConfig) => flowConfig.onEscape(component, simulatedEvent);
  6094. const getKeydownRules$3 = (_component, _se, flowConfig, _flowState) => {
  6095. const westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  6096. const eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  6097. return [
  6098. rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
  6099. rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
  6100. rule(inSet(ENTER), execute$2),
  6101. rule(inSet(SPACE), execute$2),
  6102. rule(inSet(ESCAPE), doEscape)
  6103. ];
  6104. };
  6105. const getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  6106. var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, () => Optional.some(focusIn$2));
  6107. const toCell = (matrix, rowIndex, columnIndex) => Optional.from(matrix[rowIndex]).bind(row => Optional.from(row[columnIndex]).map(cell => ({
  6108. rowIndex,
  6109. columnIndex,
  6110. cell
  6111. })));
  6112. const cycleHorizontal = (matrix, rowIndex, startCol, deltaCol) => {
  6113. const row = matrix[rowIndex];
  6114. const colsInRow = row.length;
  6115. const newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  6116. return toCell(matrix, rowIndex, newColIndex);
  6117. };
  6118. const cycleVertical = (matrix, colIndex, startRow, deltaRow) => {
  6119. const nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  6120. const colsInNextRow = matrix[nextRowIndex].length;
  6121. const nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6122. return toCell(matrix, nextRowIndex, nextColIndex);
  6123. };
  6124. const moveHorizontal = (matrix, rowIndex, startCol, deltaCol) => {
  6125. const row = matrix[rowIndex];
  6126. const colsInRow = row.length;
  6127. const newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  6128. return toCell(matrix, rowIndex, newColIndex);
  6129. };
  6130. const moveVertical = (matrix, colIndex, startRow, deltaRow) => {
  6131. const nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  6132. const colsInNextRow = matrix[nextRowIndex].length;
  6133. const nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6134. return toCell(matrix, nextRowIndex, nextColIndex);
  6135. };
  6136. const cycleRight = (matrix, startRow, startCol) => cycleHorizontal(matrix, startRow, startCol, +1);
  6137. const cycleLeft = (matrix, startRow, startCol) => cycleHorizontal(matrix, startRow, startCol, -1);
  6138. const cycleUp = (matrix, startRow, startCol) => cycleVertical(matrix, startCol, startRow, -1);
  6139. const cycleDown = (matrix, startRow, startCol) => cycleVertical(matrix, startCol, startRow, +1);
  6140. const moveLeft$1 = (matrix, startRow, startCol) => moveHorizontal(matrix, startRow, startCol, -1);
  6141. const moveRight$1 = (matrix, startRow, startCol) => moveHorizontal(matrix, startRow, startCol, +1);
  6142. const moveUp$1 = (matrix, startRow, startCol) => moveVertical(matrix, startCol, startRow, -1);
  6143. const moveDown$1 = (matrix, startRow, startCol) => moveVertical(matrix, startCol, startRow, +1);
  6144. const schema$s = [
  6145. requiredObjOf('selectors', [
  6146. required$1('row'),
  6147. required$1('cell')
  6148. ]),
  6149. defaulted('cycles', true),
  6150. defaulted('previousSelector', Optional.none),
  6151. defaulted('execute', defaultExecute)
  6152. ];
  6153. const focusIn$1 = (component, matrixConfig, _state) => {
  6154. const focused = matrixConfig.previousSelector(component).orThunk(() => {
  6155. const selectors = matrixConfig.selectors;
  6156. return descendant(component.element, selectors.cell);
  6157. });
  6158. focused.each(cell => {
  6159. matrixConfig.focusManager.set(component, cell);
  6160. });
  6161. };
  6162. const execute$1 = (component, simulatedEvent, matrixConfig) => search(component.element).bind(focused => matrixConfig.execute(component, simulatedEvent, focused));
  6163. const toMatrix = (rows, matrixConfig) => map$2(rows, row => descendants(row, matrixConfig.selectors.cell));
  6164. const doMove = (ifCycle, ifMove) => (element, focused, matrixConfig) => {
  6165. const move = matrixConfig.cycles ? ifCycle : ifMove;
  6166. return closest$1(focused, matrixConfig.selectors.row).bind(inRow => {
  6167. const cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  6168. return findIndex(cellsInRow, focused).bind(colIndex => {
  6169. const allRows = descendants(element, matrixConfig.selectors.row);
  6170. return findIndex(allRows, inRow).bind(rowIndex => {
  6171. const matrix = toMatrix(allRows, matrixConfig);
  6172. return move(matrix, rowIndex, colIndex).map(next => next.cell);
  6173. });
  6174. });
  6175. });
  6176. };
  6177. const moveLeft = doMove(cycleLeft, moveLeft$1);
  6178. const moveRight = doMove(cycleRight, moveRight$1);
  6179. const moveNorth = doMove(cycleUp, moveUp$1);
  6180. const moveSouth = doMove(cycleDown, moveDown$1);
  6181. const getKeydownRules$2 = constant$1([
  6182. rule(inSet(LEFT), west$1(moveLeft, moveRight)),
  6183. rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
  6184. rule(inSet(UP), north$1(moveNorth)),
  6185. rule(inSet(DOWN), south$1(moveSouth)),
  6186. rule(inSet(SPACE.concat(ENTER)), execute$1)
  6187. ]);
  6188. const getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  6189. var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, () => Optional.some(focusIn$1));
  6190. const schema$r = [
  6191. required$1('selector'),
  6192. defaulted('execute', defaultExecute),
  6193. defaulted('moveOnTab', false)
  6194. ];
  6195. const execute = (component, simulatedEvent, menuConfig) => menuConfig.focusManager.get(component).bind(focused => menuConfig.execute(component, simulatedEvent, focused));
  6196. const focusIn = (component, menuConfig, _state) => {
  6197. descendant(component.element, menuConfig.selector).each(first => {
  6198. menuConfig.focusManager.set(component, first);
  6199. });
  6200. };
  6201. const moveUp = (element, focused, info) => horizontal(element, info.selector, focused, -1);
  6202. const moveDown = (element, focused, info) => horizontal(element, info.selector, focused, +1);
  6203. const fireShiftTab = (component, simulatedEvent, menuConfig, menuState) => menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  6204. const fireTab = (component, simulatedEvent, menuConfig, menuState) => menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  6205. const getKeydownRules$1 = constant$1([
  6206. rule(inSet(UP), move$1(moveUp)),
  6207. rule(inSet(DOWN), move$1(moveDown)),
  6208. rule(and([
  6209. isShift,
  6210. inSet(TAB)
  6211. ]), fireShiftTab),
  6212. rule(and([
  6213. isNotShift,
  6214. inSet(TAB)
  6215. ]), fireTab),
  6216. rule(inSet(ENTER), execute),
  6217. rule(inSet(SPACE), execute)
  6218. ]);
  6219. const getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  6220. var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, () => Optional.some(focusIn));
  6221. const schema$q = [
  6222. onKeyboardHandler('onSpace'),
  6223. onKeyboardHandler('onEnter'),
  6224. onKeyboardHandler('onShiftEnter'),
  6225. onKeyboardHandler('onLeft'),
  6226. onKeyboardHandler('onRight'),
  6227. onKeyboardHandler('onTab'),
  6228. onKeyboardHandler('onShiftTab'),
  6229. onKeyboardHandler('onUp'),
  6230. onKeyboardHandler('onDown'),
  6231. onKeyboardHandler('onEscape'),
  6232. defaulted('stopSpaceKeyup', false),
  6233. option$3('focusIn')
  6234. ];
  6235. const getKeydownRules = (component, simulatedEvent, specialInfo) => [
  6236. rule(inSet(SPACE), specialInfo.onSpace),
  6237. rule(and([
  6238. isNotShift,
  6239. inSet(ENTER)
  6240. ]), specialInfo.onEnter),
  6241. rule(and([
  6242. isShift,
  6243. inSet(ENTER)
  6244. ]), specialInfo.onShiftEnter),
  6245. rule(and([
  6246. isShift,
  6247. inSet(TAB)
  6248. ]), specialInfo.onShiftTab),
  6249. rule(and([
  6250. isNotShift,
  6251. inSet(TAB)
  6252. ]), specialInfo.onTab),
  6253. rule(inSet(UP), specialInfo.onUp),
  6254. rule(inSet(DOWN), specialInfo.onDown),
  6255. rule(inSet(LEFT), specialInfo.onLeft),
  6256. rule(inSet(RIGHT), specialInfo.onRight),
  6257. rule(inSet(SPACE), specialInfo.onSpace),
  6258. rule(inSet(ESCAPE), specialInfo.onEscape)
  6259. ];
  6260. const getKeyupRules = (component, simulatedEvent, specialInfo) => specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  6261. var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, specialInfo => specialInfo.focusIn);
  6262. const acyclic = AcyclicType.schema();
  6263. const cyclic = CyclicType.schema();
  6264. const flow = FlowType.schema();
  6265. const flatgrid = FlatgridType.schema();
  6266. const matrix = MatrixType.schema();
  6267. const execution = ExecutionType.schema();
  6268. const menu = MenuType.schema();
  6269. const special = SpecialType.schema();
  6270. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  6271. __proto__: null,
  6272. acyclic: acyclic,
  6273. cyclic: cyclic,
  6274. flow: flow,
  6275. flatgrid: flatgrid,
  6276. matrix: matrix,
  6277. execution: execution,
  6278. menu: menu,
  6279. special: special
  6280. });
  6281. const isFlatgridState = keyState => hasNonNullableKey(keyState, 'setGridSize');
  6282. const Keying = createModes({
  6283. branchKey: 'mode',
  6284. branches: KeyboardBranches,
  6285. name: 'keying',
  6286. active: {
  6287. events: (keyingConfig, keyingState) => {
  6288. const handler = keyingConfig.handler;
  6289. return handler.toEvents(keyingConfig, keyingState);
  6290. }
  6291. },
  6292. apis: {
  6293. focusIn: (component, keyConfig, keyState) => {
  6294. keyConfig.sendFocusIn(keyConfig).fold(() => {
  6295. component.getSystem().triggerFocus(component.element, component.element);
  6296. }, sendFocusIn => {
  6297. sendFocusIn(component, keyConfig, keyState);
  6298. });
  6299. },
  6300. setGridSize: (component, keyConfig, keyState, numRows, numColumns) => {
  6301. if (!isFlatgridState(keyState)) {
  6302. console.error('Layout does not support setGridSize');
  6303. } else {
  6304. keyState.setGridSize(numRows, numColumns);
  6305. }
  6306. }
  6307. },
  6308. state: KeyingState
  6309. });
  6310. const withoutReuse = (parent, data) => {
  6311. preserve$1(() => {
  6312. replaceChildren(parent, data, () => map$2(data, parent.getSystem().build));
  6313. }, parent.element);
  6314. };
  6315. const withReuse = (parent, data) => {
  6316. preserve$1(() => {
  6317. virtualReplaceChildren(parent, data, () => {
  6318. return patchSpecChildren(parent.element, data, parent.getSystem().buildOrPatch);
  6319. });
  6320. }, parent.element);
  6321. };
  6322. const virtualReplace = (component, replacee, replaceeIndex, childSpec) => {
  6323. virtualDetach(replacee);
  6324. const child = patchSpecChild(component.element, replaceeIndex, childSpec, component.getSystem().buildOrPatch);
  6325. virtualAttach(component, child);
  6326. component.syncComponents();
  6327. };
  6328. const insert = (component, insertion, childSpec) => {
  6329. const child = component.getSystem().build(childSpec);
  6330. attachWith(component, child, insertion);
  6331. };
  6332. const replace = (component, replacee, replaceeIndex, childSpec) => {
  6333. detach(replacee);
  6334. insert(component, (p, c) => appendAt(p, c, replaceeIndex), childSpec);
  6335. };
  6336. const set$3 = (component, replaceConfig, replaceState, data) => {
  6337. const replacer = replaceConfig.reuseDom ? withReuse : withoutReuse;
  6338. return replacer(component, data);
  6339. };
  6340. const append = (component, replaceConfig, replaceState, appendee) => {
  6341. insert(component, append$2, appendee);
  6342. };
  6343. const prepend = (component, replaceConfig, replaceState, prependee) => {
  6344. insert(component, prepend$1, prependee);
  6345. };
  6346. const remove = (component, replaceConfig, replaceState, removee) => {
  6347. const children = contents(component);
  6348. const foundChild = find$5(children, child => eq(removee.element, child.element));
  6349. foundChild.each(detach);
  6350. };
  6351. const contents = (component, _replaceConfig) => component.components();
  6352. const replaceAt = (component, replaceConfig, replaceState, replaceeIndex, replacer) => {
  6353. const children = contents(component);
  6354. return Optional.from(children[replaceeIndex]).map(replacee => {
  6355. replacer.fold(() => detach(replacee), r => {
  6356. const replacer = replaceConfig.reuseDom ? virtualReplace : replace;
  6357. replacer(component, replacee, replaceeIndex, r);
  6358. });
  6359. return replacee;
  6360. });
  6361. };
  6362. const replaceBy = (component, replaceConfig, replaceState, replaceePred, replacer) => {
  6363. const children = contents(component);
  6364. return findIndex$1(children, replaceePred).bind(replaceeIndex => replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer));
  6365. };
  6366. var ReplaceApis = /*#__PURE__*/Object.freeze({
  6367. __proto__: null,
  6368. append: append,
  6369. prepend: prepend,
  6370. remove: remove,
  6371. replaceAt: replaceAt,
  6372. replaceBy: replaceBy,
  6373. set: set$3,
  6374. contents: contents
  6375. });
  6376. const Replacing = create$3({
  6377. fields: [defaultedBoolean('reuseDom', true)],
  6378. name: 'replacing',
  6379. apis: ReplaceApis
  6380. });
  6381. const events$d = (name, eventHandlers) => {
  6382. const events = derive$2(eventHandlers);
  6383. return create$3({
  6384. fields: [required$1('enabled')],
  6385. name,
  6386. active: { events: constant$1(events) }
  6387. });
  6388. };
  6389. const config = (name, eventHandlers) => {
  6390. const me = events$d(name, eventHandlers);
  6391. return {
  6392. key: name,
  6393. value: {
  6394. config: {},
  6395. me,
  6396. configAsRaw: constant$1({}),
  6397. initialConfig: {},
  6398. state: NoState
  6399. }
  6400. };
  6401. };
  6402. const focus$2 = (component, focusConfig) => {
  6403. if (!focusConfig.ignore) {
  6404. focus$3(component.element);
  6405. focusConfig.onFocus(component);
  6406. }
  6407. };
  6408. const blur = (component, focusConfig) => {
  6409. if (!focusConfig.ignore) {
  6410. blur$1(component.element);
  6411. }
  6412. };
  6413. const isFocused = component => hasFocus(component.element);
  6414. var FocusApis = /*#__PURE__*/Object.freeze({
  6415. __proto__: null,
  6416. focus: focus$2,
  6417. blur: blur,
  6418. isFocused: isFocused
  6419. });
  6420. const exhibit$4 = (base, focusConfig) => {
  6421. const mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  6422. return nu$7(mod);
  6423. };
  6424. const events$c = focusConfig => derive$2([run$1(focus$4(), (component, simulatedEvent) => {
  6425. focus$2(component, focusConfig);
  6426. simulatedEvent.stop();
  6427. })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), (_, simulatedEvent) => {
  6428. simulatedEvent.event.prevent();
  6429. })] : []));
  6430. var ActiveFocus = /*#__PURE__*/Object.freeze({
  6431. __proto__: null,
  6432. exhibit: exhibit$4,
  6433. events: events$c
  6434. });
  6435. var FocusSchema = [
  6436. onHandler('onFocus'),
  6437. defaulted('stopMousedown', false),
  6438. defaulted('ignore', false)
  6439. ];
  6440. const Focusing = create$3({
  6441. fields: FocusSchema,
  6442. name: 'focusing',
  6443. active: ActiveFocus,
  6444. apis: FocusApis
  6445. });
  6446. const SetupBehaviourCellState = initialState => {
  6447. const init = () => {
  6448. const cell = Cell(initialState);
  6449. const get = () => cell.get();
  6450. const set = newState => cell.set(newState);
  6451. const clear = () => cell.set(initialState);
  6452. const readState = () => cell.get();
  6453. return {
  6454. get,
  6455. set,
  6456. clear,
  6457. readState
  6458. };
  6459. };
  6460. return { init };
  6461. };
  6462. const updateAriaState = (component, toggleConfig, toggleState) => {
  6463. const ariaInfo = toggleConfig.aria;
  6464. ariaInfo.update(component, ariaInfo, toggleState.get());
  6465. };
  6466. const updateClass = (component, toggleConfig, toggleState) => {
  6467. toggleConfig.toggleClass.each(toggleClass => {
  6468. if (toggleState.get()) {
  6469. add$2(component.element, toggleClass);
  6470. } else {
  6471. remove$2(component.element, toggleClass);
  6472. }
  6473. });
  6474. };
  6475. const toggle$2 = (component, toggleConfig, toggleState) => {
  6476. set$2(component, toggleConfig, toggleState, !toggleState.get());
  6477. };
  6478. const on = (component, toggleConfig, toggleState) => {
  6479. toggleState.set(true);
  6480. updateClass(component, toggleConfig, toggleState);
  6481. updateAriaState(component, toggleConfig, toggleState);
  6482. };
  6483. const off = (component, toggleConfig, toggleState) => {
  6484. toggleState.set(false);
  6485. updateClass(component, toggleConfig, toggleState);
  6486. updateAriaState(component, toggleConfig, toggleState);
  6487. };
  6488. const set$2 = (component, toggleConfig, toggleState, state) => {
  6489. const action = state ? on : off;
  6490. action(component, toggleConfig, toggleState);
  6491. };
  6492. const isOn = (component, toggleConfig, toggleState) => toggleState.get();
  6493. const onLoad = (component, toggleConfig, toggleState) => {
  6494. set$2(component, toggleConfig, toggleState, toggleConfig.selected);
  6495. };
  6496. var ToggleApis = /*#__PURE__*/Object.freeze({
  6497. __proto__: null,
  6498. onLoad: onLoad,
  6499. toggle: toggle$2,
  6500. isOn: isOn,
  6501. on: on,
  6502. off: off,
  6503. set: set$2
  6504. });
  6505. const exhibit$3 = () => nu$7({});
  6506. const events$b = (toggleConfig, toggleState) => {
  6507. const execute = executeEvent(toggleConfig, toggleState, toggle$2);
  6508. const load = loadEvent(toggleConfig, toggleState, onLoad);
  6509. return derive$2(flatten([
  6510. toggleConfig.toggleOnExecute ? [execute] : [],
  6511. [load]
  6512. ]));
  6513. };
  6514. var ActiveToggle = /*#__PURE__*/Object.freeze({
  6515. __proto__: null,
  6516. exhibit: exhibit$3,
  6517. events: events$b
  6518. });
  6519. const updatePressed = (component, ariaInfo, status) => {
  6520. set$9(component.element, 'aria-pressed', status);
  6521. if (ariaInfo.syncWithExpanded) {
  6522. updateExpanded(component, ariaInfo, status);
  6523. }
  6524. };
  6525. const updateSelected = (component, ariaInfo, status) => {
  6526. set$9(component.element, 'aria-selected', status);
  6527. };
  6528. const updateChecked = (component, ariaInfo, status) => {
  6529. set$9(component.element, 'aria-checked', status);
  6530. };
  6531. const updateExpanded = (component, ariaInfo, status) => {
  6532. set$9(component.element, 'aria-expanded', status);
  6533. };
  6534. var ToggleSchema = [
  6535. defaulted('selected', false),
  6536. option$3('toggleClass'),
  6537. defaulted('toggleOnExecute', true),
  6538. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  6539. pressed: [
  6540. defaulted('syncWithExpanded', false),
  6541. output$1('update', updatePressed)
  6542. ],
  6543. checked: [output$1('update', updateChecked)],
  6544. expanded: [output$1('update', updateExpanded)],
  6545. selected: [output$1('update', updateSelected)],
  6546. none: [output$1('update', noop)]
  6547. }))
  6548. ];
  6549. const Toggling = create$3({
  6550. fields: ToggleSchema,
  6551. name: 'toggling',
  6552. active: ActiveToggle,
  6553. apis: ToggleApis,
  6554. state: SetupBehaviourCellState(false)
  6555. });
  6556. const pointerEvents = () => {
  6557. const onClick = (component, simulatedEvent) => {
  6558. simulatedEvent.stop();
  6559. emitExecute(component);
  6560. };
  6561. return [
  6562. run$1(click(), onClick),
  6563. run$1(tap(), onClick),
  6564. cutter(touchstart()),
  6565. cutter(mousedown())
  6566. ];
  6567. };
  6568. const events$a = optAction => {
  6569. const executeHandler = action => runOnExecute$1((component, simulatedEvent) => {
  6570. action(component);
  6571. simulatedEvent.stop();
  6572. });
  6573. return derive$2(flatten([
  6574. optAction.map(executeHandler).toArray(),
  6575. pointerEvents()
  6576. ]));
  6577. };
  6578. const hoverEvent = 'alloy.item-hover';
  6579. const focusEvent = 'alloy.item-focus';
  6580. const onHover = item => {
  6581. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  6582. if (!Focusing.isFocused(item)) {
  6583. Focusing.focus(item);
  6584. }
  6585. emitWith(item, hoverEvent, { item });
  6586. }
  6587. };
  6588. const onFocus$1 = item => {
  6589. emitWith(item, focusEvent, { item });
  6590. };
  6591. const hover = constant$1(hoverEvent);
  6592. const focus$1 = constant$1(focusEvent);
  6593. const builder$2 = detail => ({
  6594. dom: detail.dom,
  6595. domModification: {
  6596. ...detail.domModification,
  6597. attributes: {
  6598. 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem',
  6599. ...detail.domModification.attributes,
  6600. 'aria-haspopup': detail.hasSubmenu,
  6601. ...detail.hasSubmenu ? { 'aria-expanded': false } : {}
  6602. }
  6603. },
  6604. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  6605. detail.toggling.fold(Toggling.revoke, tConfig => Toggling.config({
  6606. aria: { mode: 'checked' },
  6607. ...tConfig
  6608. })),
  6609. Focusing.config({
  6610. ignore: detail.ignoreFocus,
  6611. stopMousedown: detail.ignoreFocus,
  6612. onFocus: component => {
  6613. onFocus$1(component);
  6614. }
  6615. }),
  6616. Keying.config({ mode: 'execution' }),
  6617. Representing.config({
  6618. store: {
  6619. mode: 'memory',
  6620. initialValue: detail.data
  6621. }
  6622. }),
  6623. config('item-type-events', [
  6624. ...pointerEvents(),
  6625. run$1(mouseover(), onHover),
  6626. run$1(focusItem(), Focusing.focus)
  6627. ])
  6628. ]),
  6629. components: detail.components,
  6630. eventOrder: detail.eventOrder
  6631. });
  6632. const schema$p = [
  6633. required$1('data'),
  6634. required$1('components'),
  6635. required$1('dom'),
  6636. defaulted('hasSubmenu', false),
  6637. option$3('toggling'),
  6638. SketchBehaviours.field('itemBehaviours', [
  6639. Toggling,
  6640. Focusing,
  6641. Keying,
  6642. Representing
  6643. ]),
  6644. defaulted('ignoreFocus', false),
  6645. defaulted('domModification', {}),
  6646. output$1('builder', builder$2),
  6647. defaulted('eventOrder', {})
  6648. ];
  6649. const builder$1 = detail => ({
  6650. dom: detail.dom,
  6651. components: detail.components,
  6652. events: derive$2([stopper(focusItem())])
  6653. });
  6654. const schema$o = [
  6655. required$1('dom'),
  6656. required$1('components'),
  6657. output$1('builder', builder$1)
  6658. ];
  6659. const owner$2 = constant$1('item-widget');
  6660. const parts$h = constant$1([required({
  6661. name: 'widget',
  6662. overrides: detail => {
  6663. return {
  6664. behaviours: derive$1([Representing.config({
  6665. store: {
  6666. mode: 'manual',
  6667. getValue: _component => {
  6668. return detail.data;
  6669. },
  6670. setValue: noop
  6671. }
  6672. })])
  6673. };
  6674. }
  6675. })]);
  6676. const builder = detail => {
  6677. const subs = substitutes(owner$2(), detail, parts$h());
  6678. const components = components$1(owner$2(), detail, subs.internals());
  6679. const focusWidget = component => getPart(component, detail, 'widget').map(widget => {
  6680. Keying.focusIn(widget);
  6681. return widget;
  6682. });
  6683. const onHorizontalArrow = (component, simulatedEvent) => inside(simulatedEvent.event.target) ? Optional.none() : (() => {
  6684. if (detail.autofocus) {
  6685. simulatedEvent.setSource(component.element);
  6686. return Optional.none();
  6687. } else {
  6688. return Optional.none();
  6689. }
  6690. })();
  6691. return {
  6692. dom: detail.dom,
  6693. components,
  6694. domModification: detail.domModification,
  6695. events: derive$2([
  6696. runOnExecute$1((component, simulatedEvent) => {
  6697. focusWidget(component).each(_widget => {
  6698. simulatedEvent.stop();
  6699. });
  6700. }),
  6701. run$1(mouseover(), onHover),
  6702. run$1(focusItem(), (component, _simulatedEvent) => {
  6703. if (detail.autofocus) {
  6704. focusWidget(component);
  6705. } else {
  6706. Focusing.focus(component);
  6707. }
  6708. })
  6709. ]),
  6710. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  6711. Representing.config({
  6712. store: {
  6713. mode: 'memory',
  6714. initialValue: detail.data
  6715. }
  6716. }),
  6717. Focusing.config({
  6718. ignore: detail.ignoreFocus,
  6719. onFocus: component => {
  6720. onFocus$1(component);
  6721. }
  6722. }),
  6723. Keying.config({
  6724. mode: 'special',
  6725. focusIn: detail.autofocus ? component => {
  6726. focusWidget(component);
  6727. } : revoke(),
  6728. onLeft: onHorizontalArrow,
  6729. onRight: onHorizontalArrow,
  6730. onEscape: (component, simulatedEvent) => {
  6731. if (!Focusing.isFocused(component) && !detail.autofocus) {
  6732. Focusing.focus(component);
  6733. return Optional.some(true);
  6734. } else if (detail.autofocus) {
  6735. simulatedEvent.setSource(component.element);
  6736. return Optional.none();
  6737. } else {
  6738. return Optional.none();
  6739. }
  6740. }
  6741. })
  6742. ])
  6743. };
  6744. };
  6745. const schema$n = [
  6746. required$1('uid'),
  6747. required$1('data'),
  6748. required$1('components'),
  6749. required$1('dom'),
  6750. defaulted('autofocus', false),
  6751. defaulted('ignoreFocus', false),
  6752. SketchBehaviours.field('widgetBehaviours', [
  6753. Representing,
  6754. Focusing,
  6755. Keying
  6756. ]),
  6757. defaulted('domModification', {}),
  6758. defaultUidsSchema(parts$h()),
  6759. output$1('builder', builder)
  6760. ];
  6761. const itemSchema$2 = choose$1('type', {
  6762. widget: schema$n,
  6763. item: schema$p,
  6764. separator: schema$o
  6765. });
  6766. const configureGrid = (detail, movementInfo) => ({
  6767. mode: 'flatgrid',
  6768. selector: '.' + detail.markers.item,
  6769. initSize: {
  6770. numColumns: movementInfo.initSize.numColumns,
  6771. numRows: movementInfo.initSize.numRows
  6772. },
  6773. focusManager: detail.focusManager
  6774. });
  6775. const configureMatrix = (detail, movementInfo) => ({
  6776. mode: 'matrix',
  6777. selectors: {
  6778. row: movementInfo.rowSelector,
  6779. cell: '.' + detail.markers.item
  6780. },
  6781. focusManager: detail.focusManager
  6782. });
  6783. const configureMenu = (detail, movementInfo) => ({
  6784. mode: 'menu',
  6785. selector: '.' + detail.markers.item,
  6786. moveOnTab: movementInfo.moveOnTab,
  6787. focusManager: detail.focusManager
  6788. });
  6789. const parts$g = constant$1([group({
  6790. factory: {
  6791. sketch: spec => {
  6792. const itemInfo = asRawOrDie$1('menu.spec item', itemSchema$2, spec);
  6793. return itemInfo.builder(itemInfo);
  6794. }
  6795. },
  6796. name: 'items',
  6797. unit: 'item',
  6798. defaults: (detail, u) => {
  6799. return has$2(u, 'uid') ? u : {
  6800. ...u,
  6801. uid: generate$5('item')
  6802. };
  6803. },
  6804. overrides: (detail, u) => {
  6805. return {
  6806. type: u.type,
  6807. ignoreFocus: detail.fakeFocus,
  6808. domModification: { classes: [detail.markers.item] }
  6809. };
  6810. }
  6811. })]);
  6812. const schema$m = constant$1([
  6813. required$1('value'),
  6814. required$1('items'),
  6815. required$1('dom'),
  6816. required$1('components'),
  6817. defaulted('eventOrder', {}),
  6818. field('menuBehaviours', [
  6819. Highlighting,
  6820. Representing,
  6821. Composing,
  6822. Keying
  6823. ]),
  6824. defaultedOf('movement', {
  6825. mode: 'menu',
  6826. moveOnTab: true
  6827. }, choose$1('mode', {
  6828. grid: [
  6829. initSize(),
  6830. output$1('config', configureGrid)
  6831. ],
  6832. matrix: [
  6833. output$1('config', configureMatrix),
  6834. required$1('rowSelector')
  6835. ],
  6836. menu: [
  6837. defaulted('moveOnTab', true),
  6838. output$1('config', configureMenu)
  6839. ]
  6840. })),
  6841. itemMarkers(),
  6842. defaulted('fakeFocus', false),
  6843. defaulted('focusManager', dom$2()),
  6844. onHandler('onHighlight')
  6845. ]);
  6846. const focus = constant$1('alloy.menu-focus');
  6847. const make$7 = (detail, components, _spec, _externals) => ({
  6848. uid: detail.uid,
  6849. dom: detail.dom,
  6850. markers: detail.markers,
  6851. behaviours: augment(detail.menuBehaviours, [
  6852. Highlighting.config({
  6853. highlightClass: detail.markers.selectedItem,
  6854. itemClass: detail.markers.item,
  6855. onHighlight: detail.onHighlight
  6856. }),
  6857. Representing.config({
  6858. store: {
  6859. mode: 'memory',
  6860. initialValue: detail.value
  6861. }
  6862. }),
  6863. Composing.config({ find: Optional.some }),
  6864. Keying.config(detail.movement.config(detail, detail.movement))
  6865. ]),
  6866. events: derive$2([
  6867. run$1(focus$1(), (menu, simulatedEvent) => {
  6868. const event = simulatedEvent.event;
  6869. menu.getSystem().getByDom(event.target).each(item => {
  6870. Highlighting.highlight(menu, item);
  6871. simulatedEvent.stop();
  6872. emitWith(menu, focus(), {
  6873. menu,
  6874. item
  6875. });
  6876. });
  6877. }),
  6878. run$1(hover(), (menu, simulatedEvent) => {
  6879. const item = simulatedEvent.event.item;
  6880. Highlighting.highlight(menu, item);
  6881. })
  6882. ]),
  6883. components,
  6884. eventOrder: detail.eventOrder,
  6885. domModification: { attributes: { role: 'menu' } }
  6886. });
  6887. const Menu = composite({
  6888. name: 'Menu',
  6889. configFields: schema$m(),
  6890. partFields: parts$g(),
  6891. factory: make$7
  6892. });
  6893. const transpose$1 = obj => tupleMap(obj, (v, k) => ({
  6894. k: v,
  6895. v: k
  6896. }));
  6897. const trace = (items, byItem, byMenu, finish) => get$g(byMenu, finish).bind(triggerItem => get$g(items, triggerItem).bind(triggerMenu => {
  6898. const rest = trace(items, byItem, byMenu, triggerMenu);
  6899. return Optional.some([triggerMenu].concat(rest));
  6900. })).getOr([]);
  6901. const generate$2 = (menus, expansions) => {
  6902. const items = {};
  6903. each(menus, (menuItems, menu) => {
  6904. each$1(menuItems, item => {
  6905. items[item] = menu;
  6906. });
  6907. });
  6908. const byItem = expansions;
  6909. const byMenu = transpose$1(expansions);
  6910. const menuPaths = map$1(byMenu, (_triggerItem, submenu) => [submenu].concat(trace(items, byItem, byMenu, submenu)));
  6911. return map$1(items, menu => get$g(menuPaths, menu).getOr([menu]));
  6912. };
  6913. const init$c = () => {
  6914. const expansions = Cell({});
  6915. const menus = Cell({});
  6916. const paths = Cell({});
  6917. const primary = value$2();
  6918. const directory = Cell({});
  6919. const clear = () => {
  6920. expansions.set({});
  6921. menus.set({});
  6922. paths.set({});
  6923. primary.clear();
  6924. };
  6925. const isClear = () => primary.get().isNone();
  6926. const setMenuBuilt = (menuName, built) => {
  6927. menus.set({
  6928. ...menus.get(),
  6929. [menuName]: {
  6930. type: 'prepared',
  6931. menu: built
  6932. }
  6933. });
  6934. };
  6935. const setContents = (sPrimary, sMenus, sExpansions, dir) => {
  6936. primary.set(sPrimary);
  6937. expansions.set(sExpansions);
  6938. menus.set(sMenus);
  6939. directory.set(dir);
  6940. const sPaths = generate$2(dir, sExpansions);
  6941. paths.set(sPaths);
  6942. };
  6943. const getTriggeringItem = menuValue => find$4(expansions.get(), (v, _k) => v === menuValue);
  6944. const getTriggerData = (menuValue, getItemByValue, path) => getPreparedMenu(menuValue).bind(menu => getTriggeringItem(menuValue).bind(triggeringItemValue => getItemByValue(triggeringItemValue).map(triggeredItem => ({
  6945. triggeredMenu: menu,
  6946. triggeringItem: triggeredItem,
  6947. triggeringPath: path
  6948. }))));
  6949. const getTriggeringPath = (itemValue, getItemByValue) => {
  6950. const extraPath = filter$2(lookupItem(itemValue).toArray(), menuValue => getPreparedMenu(menuValue).isSome());
  6951. return get$g(paths.get(), itemValue).bind(path => {
  6952. const revPath = reverse(extraPath.concat(path));
  6953. const triggers = bind$3(revPath, (menuValue, menuIndex) => getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(() => is$1(primary.get(), menuValue) ? [] : [Optional.none()], data => [Optional.some(data)]));
  6954. return sequence(triggers);
  6955. });
  6956. };
  6957. const expand = itemValue => get$g(expansions.get(), itemValue).map(menu => {
  6958. const current = get$g(paths.get(), itemValue).getOr([]);
  6959. return [menu].concat(current);
  6960. });
  6961. const collapse = itemValue => get$g(paths.get(), itemValue).bind(path => path.length > 1 ? Optional.some(path.slice(1)) : Optional.none());
  6962. const refresh = itemValue => get$g(paths.get(), itemValue);
  6963. const getPreparedMenu = menuValue => lookupMenu(menuValue).bind(extractPreparedMenu);
  6964. const lookupMenu = menuValue => get$g(menus.get(), menuValue);
  6965. const lookupItem = itemValue => get$g(expansions.get(), itemValue);
  6966. const otherMenus = path => {
  6967. const menuValues = directory.get();
  6968. return difference(keys(menuValues), path);
  6969. };
  6970. const getPrimary = () => primary.get().bind(getPreparedMenu);
  6971. const getMenus = () => menus.get();
  6972. return {
  6973. setMenuBuilt,
  6974. setContents,
  6975. expand,
  6976. refresh,
  6977. collapse,
  6978. lookupMenu,
  6979. lookupItem,
  6980. otherMenus,
  6981. getPrimary,
  6982. getMenus,
  6983. clear,
  6984. isClear,
  6985. getTriggeringPath
  6986. };
  6987. };
  6988. const extractPreparedMenu = prep => prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  6989. const LayeredState = {
  6990. init: init$c,
  6991. extractPreparedMenu
  6992. };
  6993. const make$6 = (detail, _rawUiSpec) => {
  6994. const submenuParentItems = value$2();
  6995. const buildMenus = (container, primaryName, menus) => map$1(menus, (spec, name) => {
  6996. const makeSketch = () => Menu.sketch({
  6997. ...spec,
  6998. value: name,
  6999. markers: detail.markers,
  7000. fakeFocus: detail.fakeFocus,
  7001. onHighlight: detail.onHighlight,
  7002. focusManager: detail.fakeFocus ? highlights() : dom$2()
  7003. });
  7004. return name === primaryName ? {
  7005. type: 'prepared',
  7006. menu: container.getSystem().build(makeSketch())
  7007. } : {
  7008. type: 'notbuilt',
  7009. nbMenu: makeSketch
  7010. };
  7011. });
  7012. const layeredState = LayeredState.init();
  7013. const setup = container => {
  7014. const componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  7015. const directory = toDirectory();
  7016. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  7017. return layeredState.getPrimary();
  7018. };
  7019. const getItemValue = item => Representing.getValue(item).value;
  7020. const getItemByValue = (_container, menus, itemValue) => findMap(menus, menu => {
  7021. if (!menu.getSystem().isConnected()) {
  7022. return Optional.none();
  7023. }
  7024. const candidates = Highlighting.getCandidates(menu);
  7025. return find$5(candidates, c => getItemValue(c) === itemValue);
  7026. });
  7027. const toDirectory = _container => map$1(detail.data.menus, (data, _menuName) => bind$3(data.items, item => item.type === 'separator' ? [] : [item.data.value]));
  7028. const setActiveMenu = (container, menu) => {
  7029. Highlighting.highlight(container, menu);
  7030. Highlighting.getHighlighted(menu).orThunk(() => Highlighting.getFirst(menu)).each(item => {
  7031. dispatch(container, item.element, focusItem());
  7032. });
  7033. };
  7034. const getMenus = (state, menuValues) => cat(map$2(menuValues, mv => state.lookupMenu(mv).bind(prep => prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none())));
  7035. const closeOthers = (container, state, path) => {
  7036. const others = getMenus(state, state.otherMenus(path));
  7037. each$1(others, o => {
  7038. remove$1(o.element, [detail.markers.backgroundMenu]);
  7039. if (!detail.stayInDom) {
  7040. Replacing.remove(container, o);
  7041. }
  7042. });
  7043. };
  7044. const getSubmenuParents = container => submenuParentItems.get().getOrThunk(() => {
  7045. const r = {};
  7046. const items = descendants(container.element, `.${ detail.markers.item }`);
  7047. const parentItems = filter$2(items, i => get$f(i, 'aria-haspopup') === 'true');
  7048. each$1(parentItems, i => {
  7049. container.getSystem().getByDom(i).each(itemComp => {
  7050. const key = getItemValue(itemComp);
  7051. r[key] = itemComp;
  7052. });
  7053. });
  7054. submenuParentItems.set(r);
  7055. return r;
  7056. });
  7057. const updateAriaExpansions = (container, path) => {
  7058. const parentItems = getSubmenuParents(container);
  7059. each(parentItems, (v, k) => {
  7060. const expanded = contains$2(path, k);
  7061. set$9(v.element, 'aria-expanded', expanded);
  7062. });
  7063. };
  7064. const updateMenuPath = (container, state, path) => Optional.from(path[0]).bind(latestMenuName => state.lookupMenu(latestMenuName).bind(menuPrep => {
  7065. if (menuPrep.type === 'notbuilt') {
  7066. return Optional.none();
  7067. } else {
  7068. const activeMenu = menuPrep.menu;
  7069. const rest = getMenus(state, path.slice(1));
  7070. each$1(rest, r => {
  7071. add$2(r.element, detail.markers.backgroundMenu);
  7072. });
  7073. if (!inBody(activeMenu.element)) {
  7074. Replacing.append(container, premade(activeMenu));
  7075. }
  7076. remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  7077. setActiveMenu(container, activeMenu);
  7078. closeOthers(container, state, path);
  7079. return Optional.some(activeMenu);
  7080. }
  7081. }));
  7082. let ExpandHighlightDecision;
  7083. (function (ExpandHighlightDecision) {
  7084. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  7085. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  7086. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  7087. const buildIfRequired = (container, menuName, menuPrep) => {
  7088. if (menuPrep.type === 'notbuilt') {
  7089. const menu = container.getSystem().build(menuPrep.nbMenu());
  7090. layeredState.setMenuBuilt(menuName, menu);
  7091. return menu;
  7092. } else {
  7093. return menuPrep.menu;
  7094. }
  7095. };
  7096. const expandRight = (container, item, decision = ExpandHighlightDecision.HighlightSubmenu) => {
  7097. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  7098. return Optional.some(item);
  7099. } else {
  7100. const value = getItemValue(item);
  7101. return layeredState.expand(value).bind(path => {
  7102. updateAriaExpansions(container, path);
  7103. return Optional.from(path[0]).bind(menuName => layeredState.lookupMenu(menuName).bind(activeMenuPrep => {
  7104. const activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  7105. if (!inBody(activeMenu.element)) {
  7106. Replacing.append(container, premade(activeMenu));
  7107. }
  7108. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  7109. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  7110. Highlighting.highlightFirst(activeMenu);
  7111. return updateMenuPath(container, layeredState, path);
  7112. } else {
  7113. Highlighting.dehighlightAll(activeMenu);
  7114. return Optional.some(item);
  7115. }
  7116. }));
  7117. });
  7118. }
  7119. };
  7120. const collapseLeft = (container, item) => {
  7121. const value = getItemValue(item);
  7122. return layeredState.collapse(value).bind(path => {
  7123. updateAriaExpansions(container, path);
  7124. return updateMenuPath(container, layeredState, path).map(activeMenu => {
  7125. detail.onCollapseMenu(container, item, activeMenu);
  7126. return activeMenu;
  7127. });
  7128. });
  7129. };
  7130. const updateView = (container, item) => {
  7131. const value = getItemValue(item);
  7132. return layeredState.refresh(value).bind(path => {
  7133. updateAriaExpansions(container, path);
  7134. return updateMenuPath(container, layeredState, path);
  7135. });
  7136. };
  7137. const onRight = (container, item) => inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  7138. const onLeft = (container, item) => inside(item.element) ? Optional.none() : collapseLeft(container, item);
  7139. const onEscape = (container, item) => collapseLeft(container, item).orThunk(() => detail.onEscape(container, item).map(() => container));
  7140. const keyOnItem = f => (container, simulatedEvent) => closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(target => container.getSystem().getByDom(target).toOptional().bind(item => f(container, item).map(always)));
  7141. const events = derive$2([
  7142. run$1(focus(), (sandbox, simulatedEvent) => {
  7143. const item = simulatedEvent.event.item;
  7144. layeredState.lookupItem(getItemValue(item)).each(() => {
  7145. const menu = simulatedEvent.event.menu;
  7146. Highlighting.highlight(sandbox, menu);
  7147. const value = getItemValue(simulatedEvent.event.item);
  7148. layeredState.refresh(value).each(path => closeOthers(sandbox, layeredState, path));
  7149. });
  7150. }),
  7151. runOnExecute$1((component, simulatedEvent) => {
  7152. const target = simulatedEvent.event.target;
  7153. component.getSystem().getByDom(target).each(item => {
  7154. const itemValue = getItemValue(item);
  7155. if (itemValue.indexOf('collapse-item') === 0) {
  7156. collapseLeft(component, item);
  7157. }
  7158. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(() => {
  7159. detail.onExecute(component, item);
  7160. }, noop);
  7161. });
  7162. }),
  7163. runOnAttached((container, _simulatedEvent) => {
  7164. setup(container).each(primary => {
  7165. Replacing.append(container, premade(primary));
  7166. detail.onOpenMenu(container, primary);
  7167. if (detail.highlightImmediately) {
  7168. setActiveMenu(container, primary);
  7169. }
  7170. });
  7171. })
  7172. ].concat(detail.navigateOnHover ? [run$1(hover(), (sandbox, simulatedEvent) => {
  7173. const item = simulatedEvent.event.item;
  7174. updateView(sandbox, item);
  7175. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  7176. detail.onHover(sandbox, item);
  7177. })] : []));
  7178. const getActiveItem = container => Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  7179. const collapseMenuApi = container => {
  7180. getActiveItem(container).each(currentItem => {
  7181. collapseLeft(container, currentItem);
  7182. });
  7183. };
  7184. const highlightPrimary = container => {
  7185. layeredState.getPrimary().each(primary => {
  7186. setActiveMenu(container, primary);
  7187. });
  7188. };
  7189. const extractMenuFromContainer = container => Optional.from(container.components()[0]).filter(comp => get$f(comp.element, 'role') === 'menu');
  7190. const repositionMenus = container => {
  7191. const maybeActivePrimary = layeredState.getPrimary().bind(primary => getActiveItem(container).bind(currentItem => {
  7192. const itemValue = getItemValue(currentItem);
  7193. const allMenus = values(layeredState.getMenus());
  7194. const preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  7195. return layeredState.getTriggeringPath(itemValue, v => getItemByValue(container, preparedMenus, v));
  7196. }).map(triggeringPath => ({
  7197. primary,
  7198. triggeringPath
  7199. })));
  7200. maybeActivePrimary.fold(() => {
  7201. extractMenuFromContainer(container).each(primaryMenu => {
  7202. detail.onRepositionMenu(container, primaryMenu, []);
  7203. });
  7204. }, ({primary, triggeringPath}) => {
  7205. detail.onRepositionMenu(container, primary, triggeringPath);
  7206. });
  7207. };
  7208. const apis = {
  7209. collapseMenu: collapseMenuApi,
  7210. highlightPrimary,
  7211. repositionMenus
  7212. };
  7213. return {
  7214. uid: detail.uid,
  7215. dom: detail.dom,
  7216. markers: detail.markers,
  7217. behaviours: augment(detail.tmenuBehaviours, [
  7218. Keying.config({
  7219. mode: 'special',
  7220. onRight: keyOnItem(onRight),
  7221. onLeft: keyOnItem(onLeft),
  7222. onEscape: keyOnItem(onEscape),
  7223. focusIn: (container, _keyInfo) => {
  7224. layeredState.getPrimary().each(primary => {
  7225. dispatch(container, primary.element, focusItem());
  7226. });
  7227. }
  7228. }),
  7229. Highlighting.config({
  7230. highlightClass: detail.markers.selectedMenu,
  7231. itemClass: detail.markers.menu
  7232. }),
  7233. Composing.config({
  7234. find: container => {
  7235. return Highlighting.getHighlighted(container);
  7236. }
  7237. }),
  7238. Replacing.config({})
  7239. ]),
  7240. eventOrder: detail.eventOrder,
  7241. apis,
  7242. events
  7243. };
  7244. };
  7245. const collapseItem$1 = constant$1('collapse-item');
  7246. const tieredData = (primary, menus, expansions) => ({
  7247. primary,
  7248. menus,
  7249. expansions
  7250. });
  7251. const singleData = (name, menu) => ({
  7252. primary: name,
  7253. menus: wrap$1(name, menu),
  7254. expansions: {}
  7255. });
  7256. const collapseItem = text => ({
  7257. value: generate$6(collapseItem$1()),
  7258. meta: { text }
  7259. });
  7260. const tieredMenu = single({
  7261. name: 'TieredMenu',
  7262. configFields: [
  7263. onStrictKeyboardHandler('onExecute'),
  7264. onStrictKeyboardHandler('onEscape'),
  7265. onStrictHandler('onOpenMenu'),
  7266. onStrictHandler('onOpenSubmenu'),
  7267. onHandler('onRepositionMenu'),
  7268. onHandler('onCollapseMenu'),
  7269. defaulted('highlightImmediately', true),
  7270. requiredObjOf('data', [
  7271. required$1('primary'),
  7272. required$1('menus'),
  7273. required$1('expansions')
  7274. ]),
  7275. defaulted('fakeFocus', false),
  7276. onHandler('onHighlight'),
  7277. onHandler('onHover'),
  7278. tieredMenuMarkers(),
  7279. required$1('dom'),
  7280. defaulted('navigateOnHover', true),
  7281. defaulted('stayInDom', false),
  7282. field('tmenuBehaviours', [
  7283. Keying,
  7284. Highlighting,
  7285. Composing,
  7286. Replacing
  7287. ]),
  7288. defaulted('eventOrder', {})
  7289. ],
  7290. apis: {
  7291. collapseMenu: (apis, tmenu) => {
  7292. apis.collapseMenu(tmenu);
  7293. },
  7294. highlightPrimary: (apis, tmenu) => {
  7295. apis.highlightPrimary(tmenu);
  7296. },
  7297. repositionMenus: (apis, tmenu) => {
  7298. apis.repositionMenus(tmenu);
  7299. }
  7300. },
  7301. factory: make$6,
  7302. extraApis: {
  7303. tieredData,
  7304. singleData,
  7305. collapseItem
  7306. }
  7307. });
  7308. const makeMenu = (detail, menuSandbox, placementSpec, menuSpec, getBounds) => {
  7309. const lazySink = () => detail.lazySink(menuSandbox);
  7310. const layouts = menuSpec.type === 'horizontal' ? {
  7311. layouts: {
  7312. onLtr: () => belowOrAbove(),
  7313. onRtl: () => belowOrAboveRtl()
  7314. }
  7315. } : {};
  7316. const isFirstTierSubmenu = triggeringPaths => triggeringPaths.length === 2;
  7317. const getSubmenuLayouts = triggeringPaths => isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  7318. return tieredMenu.sketch({
  7319. dom: { tag: 'div' },
  7320. data: menuSpec.data,
  7321. markers: menuSpec.menu.markers,
  7322. highlightImmediately: menuSpec.menu.highlightImmediately,
  7323. onEscape: () => {
  7324. Sandboxing.close(menuSandbox);
  7325. detail.onEscape.map(handler => handler(menuSandbox));
  7326. return Optional.some(true);
  7327. },
  7328. onExecute: () => {
  7329. return Optional.some(true);
  7330. },
  7331. onOpenMenu: (tmenu, menu) => {
  7332. Positioning.positionWithinBounds(lazySink().getOrDie(), menu, placementSpec, getBounds());
  7333. },
  7334. onOpenSubmenu: (tmenu, item, submenu, triggeringPaths) => {
  7335. const sink = lazySink().getOrDie();
  7336. Positioning.position(sink, submenu, {
  7337. anchor: {
  7338. type: 'submenu',
  7339. item,
  7340. ...getSubmenuLayouts(triggeringPaths)
  7341. }
  7342. });
  7343. },
  7344. onRepositionMenu: (tmenu, primaryMenu, submenuTriggers) => {
  7345. const sink = lazySink().getOrDie();
  7346. Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds());
  7347. each$1(submenuTriggers, st => {
  7348. const submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  7349. Positioning.position(sink, st.triggeredMenu, {
  7350. anchor: {
  7351. type: 'submenu',
  7352. item: st.triggeringItem,
  7353. ...submenuLayouts
  7354. }
  7355. });
  7356. });
  7357. }
  7358. });
  7359. };
  7360. const factory$m = (detail, spec) => {
  7361. const isPartOfRelated = (sandbox, queryElem) => {
  7362. const related = detail.getRelated(sandbox);
  7363. return related.exists(rel => isPartOf$1(rel, queryElem));
  7364. };
  7365. const setContent = (sandbox, thing) => {
  7366. Sandboxing.setContent(sandbox, thing);
  7367. };
  7368. const showAt = (sandbox, thing, placementSpec) => {
  7369. showWithin(sandbox, thing, placementSpec, Optional.none());
  7370. };
  7371. const showWithin = (sandbox, thing, placementSpec, boxElement) => {
  7372. showWithinBounds(sandbox, thing, placementSpec, () => boxElement.map(elem => box$1(elem)));
  7373. };
  7374. const showWithinBounds = (sandbox, thing, placementSpec, getBounds) => {
  7375. const sink = detail.lazySink(sandbox).getOrDie();
  7376. Sandboxing.openWhileCloaked(sandbox, thing, () => Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds()));
  7377. Representing.setValue(sandbox, Optional.some({
  7378. mode: 'position',
  7379. config: placementSpec,
  7380. getBounds
  7381. }));
  7382. };
  7383. const showMenuAt = (sandbox, placementSpec, menuSpec) => {
  7384. showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
  7385. };
  7386. const showMenuWithinBounds = (sandbox, placementSpec, menuSpec, getBounds) => {
  7387. const menu = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds);
  7388. Sandboxing.open(sandbox, menu);
  7389. Representing.setValue(sandbox, Optional.some({
  7390. mode: 'menu',
  7391. menu
  7392. }));
  7393. };
  7394. const hide = sandbox => {
  7395. if (Sandboxing.isOpen(sandbox)) {
  7396. Representing.setValue(sandbox, Optional.none());
  7397. Sandboxing.close(sandbox);
  7398. }
  7399. };
  7400. const getContent = sandbox => Sandboxing.getState(sandbox);
  7401. const reposition = sandbox => {
  7402. if (Sandboxing.isOpen(sandbox)) {
  7403. Representing.getValue(sandbox).each(state => {
  7404. switch (state.mode) {
  7405. case 'menu':
  7406. Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
  7407. break;
  7408. case 'position':
  7409. const sink = detail.lazySink(sandbox).getOrDie();
  7410. Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
  7411. break;
  7412. }
  7413. });
  7414. }
  7415. };
  7416. const apis = {
  7417. setContent,
  7418. showAt,
  7419. showWithin,
  7420. showWithinBounds,
  7421. showMenuAt,
  7422. showMenuWithinBounds,
  7423. hide,
  7424. getContent,
  7425. reposition,
  7426. isOpen: Sandboxing.isOpen
  7427. };
  7428. return {
  7429. uid: detail.uid,
  7430. dom: detail.dom,
  7431. behaviours: augment(detail.inlineBehaviours, [
  7432. Sandboxing.config({
  7433. isPartOf: (sandbox, data, queryElem) => {
  7434. return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  7435. },
  7436. getAttachPoint: sandbox => {
  7437. return detail.lazySink(sandbox).getOrDie();
  7438. },
  7439. onOpen: sandbox => {
  7440. detail.onShow(sandbox);
  7441. },
  7442. onClose: sandbox => {
  7443. detail.onHide(sandbox);
  7444. }
  7445. }),
  7446. Representing.config({
  7447. store: {
  7448. mode: 'memory',
  7449. initialValue: Optional.none()
  7450. }
  7451. }),
  7452. Receiving.config({
  7453. channels: {
  7454. ...receivingChannel$1({
  7455. isExtraPart: spec.isExtraPart,
  7456. ...detail.fireDismissalEventInstead.map(fe => ({ fireEventInstead: { event: fe.event } })).getOr({})
  7457. }),
  7458. ...receivingChannel({
  7459. ...detail.fireRepositionEventInstead.map(fe => ({ fireEventInstead: { event: fe.event } })).getOr({}),
  7460. doReposition: reposition
  7461. })
  7462. }
  7463. })
  7464. ]),
  7465. eventOrder: detail.eventOrder,
  7466. apis
  7467. };
  7468. };
  7469. const InlineView = single({
  7470. name: 'InlineView',
  7471. configFields: [
  7472. required$1('lazySink'),
  7473. onHandler('onShow'),
  7474. onHandler('onHide'),
  7475. optionFunction('onEscape'),
  7476. field('inlineBehaviours', [
  7477. Sandboxing,
  7478. Representing,
  7479. Receiving
  7480. ]),
  7481. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  7482. optionObjOf('fireRepositionEventInstead', [defaulted('event', repositionRequested())]),
  7483. defaulted('getRelated', Optional.none),
  7484. defaulted('isExtraPart', never),
  7485. defaulted('eventOrder', Optional.none)
  7486. ],
  7487. factory: factory$m,
  7488. apis: {
  7489. showAt: (apis, component, anchor, thing) => {
  7490. apis.showAt(component, anchor, thing);
  7491. },
  7492. showWithin: (apis, component, anchor, thing, boxElement) => {
  7493. apis.showWithin(component, anchor, thing, boxElement);
  7494. },
  7495. showWithinBounds: (apis, component, anchor, thing, bounds) => {
  7496. apis.showWithinBounds(component, anchor, thing, bounds);
  7497. },
  7498. showMenuAt: (apis, component, anchor, menuSpec) => {
  7499. apis.showMenuAt(component, anchor, menuSpec);
  7500. },
  7501. showMenuWithinBounds: (apis, component, anchor, menuSpec, bounds) => {
  7502. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  7503. },
  7504. hide: (apis, component) => {
  7505. apis.hide(component);
  7506. },
  7507. isOpen: (apis, component) => apis.isOpen(component),
  7508. getContent: (apis, component) => apis.getContent(component),
  7509. setContent: (apis, component, thing) => {
  7510. apis.setContent(component, thing);
  7511. },
  7512. reposition: (apis, component) => {
  7513. apis.reposition(component);
  7514. }
  7515. }
  7516. });
  7517. var global$9 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  7518. const factory$l = detail => {
  7519. const events = events$a(detail.action);
  7520. const tag = detail.dom.tag;
  7521. const lookupAttr = attr => get$g(detail.dom, 'attributes').bind(attrs => get$g(attrs, attr));
  7522. const getModAttributes = () => {
  7523. if (tag === 'button') {
  7524. const type = lookupAttr('type').getOr('button');
  7525. const roleAttrs = lookupAttr('role').map(role => ({ role })).getOr({});
  7526. return {
  7527. type,
  7528. ...roleAttrs
  7529. };
  7530. } else {
  7531. const role = lookupAttr('role').getOr('button');
  7532. return { role };
  7533. }
  7534. };
  7535. return {
  7536. uid: detail.uid,
  7537. dom: detail.dom,
  7538. components: detail.components,
  7539. events,
  7540. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  7541. Focusing.config({}),
  7542. Keying.config({
  7543. mode: 'execution',
  7544. useSpace: true,
  7545. useEnter: true
  7546. })
  7547. ]),
  7548. domModification: { attributes: getModAttributes() },
  7549. eventOrder: detail.eventOrder
  7550. };
  7551. };
  7552. const Button = single({
  7553. name: 'Button',
  7554. factory: factory$l,
  7555. configFields: [
  7556. defaulted('uid', undefined),
  7557. required$1('dom'),
  7558. defaulted('components', []),
  7559. SketchBehaviours.field('buttonBehaviours', [
  7560. Focusing,
  7561. Keying
  7562. ]),
  7563. option$3('action'),
  7564. option$3('role'),
  7565. defaulted('eventOrder', {})
  7566. ]
  7567. });
  7568. const record = spec => {
  7569. const uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$5('memento');
  7570. const get = anyInSystem => anyInSystem.getSystem().getByUid(uid).getOrDie();
  7571. const getOpt = anyInSystem => anyInSystem.getSystem().getByUid(uid).toOptional();
  7572. const asSpec = () => ({
  7573. ...spec,
  7574. uid
  7575. });
  7576. return {
  7577. get,
  7578. getOpt,
  7579. asSpec
  7580. };
  7581. };
  7582. var global$8 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  7583. const rtlTransform = {
  7584. 'indent': true,
  7585. 'outdent': true,
  7586. 'table-insert-column-after': true,
  7587. 'table-insert-column-before': true,
  7588. 'paste-column-after': true,
  7589. 'paste-column-before': true,
  7590. 'unordered-list': true,
  7591. 'list-bull-circle': true,
  7592. 'list-bull-default': true,
  7593. 'list-bull-square': true
  7594. };
  7595. const defaultIconName = 'temporary-placeholder';
  7596. const defaultIcon = icons => () => get$g(icons, defaultIconName).getOr('!not found!');
  7597. const getIconName = (name, icons) => {
  7598. const lcName = name.toLowerCase();
  7599. if (global$8.isRtl()) {
  7600. const rtlName = ensureTrailing(lcName, '-rtl');
  7601. return has$2(icons, rtlName) ? rtlName : lcName;
  7602. } else {
  7603. return lcName;
  7604. }
  7605. };
  7606. const lookupIcon = (name, icons) => get$g(icons, getIconName(name, icons));
  7607. const get$2 = (name, iconProvider) => {
  7608. const icons = iconProvider();
  7609. return lookupIcon(name, icons).getOrThunk(defaultIcon(icons));
  7610. };
  7611. const getOr = (name, iconProvider, fallbackIcon) => {
  7612. const icons = iconProvider();
  7613. return lookupIcon(name, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  7614. };
  7615. const needsRtlTransform = iconName => global$8.isRtl() ? has$2(rtlTransform, iconName) : false;
  7616. const addFocusableBehaviour = () => config('add-focusable', [runOnAttached(comp => {
  7617. child(comp.element, 'svg').each(svg => set$9(svg, 'focusable', 'false'));
  7618. })]);
  7619. const renderIcon$2 = (spec, iconName, icons, fallbackIcon) => {
  7620. var _a, _b;
  7621. const rtlIconClasses = needsRtlTransform(iconName) ? ['tox-icon--flip'] : [];
  7622. const iconHtml = get$g(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  7623. return {
  7624. dom: {
  7625. tag: spec.tag,
  7626. attributes: (_a = spec.attributes) !== null && _a !== void 0 ? _a : {},
  7627. classes: spec.classes.concat(rtlIconClasses),
  7628. innerHtml: iconHtml
  7629. },
  7630. behaviours: derive$1([
  7631. ...(_b = spec.behaviours) !== null && _b !== void 0 ? _b : [],
  7632. addFocusableBehaviour()
  7633. ])
  7634. };
  7635. };
  7636. const render$3 = (iconName, spec, iconProvider, fallbackIcon = Optional.none()) => renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
  7637. const renderFirst = (iconNames, spec, iconProvider) => {
  7638. const icons = iconProvider();
  7639. const iconName = find$5(iconNames, name => has$2(icons, getIconName(name, icons)));
  7640. return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
  7641. };
  7642. const notificationIconMap = {
  7643. success: 'checkmark',
  7644. error: 'warning',
  7645. err: 'error',
  7646. warning: 'warning',
  7647. warn: 'warning',
  7648. info: 'info'
  7649. };
  7650. const factory$k = detail => {
  7651. const memBannerText = record({
  7652. dom: {
  7653. tag: 'p',
  7654. innerHtml: detail.translationProvider(detail.text)
  7655. },
  7656. behaviours: derive$1([Replacing.config({})])
  7657. });
  7658. const renderPercentBar = percent => ({
  7659. dom: {
  7660. tag: 'div',
  7661. classes: ['tox-bar'],
  7662. styles: { width: `${ percent }%` }
  7663. }
  7664. });
  7665. const renderPercentText = percent => ({
  7666. dom: {
  7667. tag: 'div',
  7668. classes: ['tox-text'],
  7669. innerHtml: `${ percent }%`
  7670. }
  7671. });
  7672. const memBannerProgress = record({
  7673. dom: {
  7674. tag: 'div',
  7675. classes: detail.progress ? [
  7676. 'tox-progress-bar',
  7677. 'tox-progress-indicator'
  7678. ] : ['tox-progress-bar']
  7679. },
  7680. components: [
  7681. {
  7682. dom: {
  7683. tag: 'div',
  7684. classes: ['tox-bar-container']
  7685. },
  7686. components: [renderPercentBar(0)]
  7687. },
  7688. renderPercentText(0)
  7689. ],
  7690. behaviours: derive$1([Replacing.config({})])
  7691. });
  7692. const updateProgress = (comp, percent) => {
  7693. if (comp.getSystem().isConnected()) {
  7694. memBannerProgress.getOpt(comp).each(progress => {
  7695. Replacing.set(progress, [
  7696. {
  7697. dom: {
  7698. tag: 'div',
  7699. classes: ['tox-bar-container']
  7700. },
  7701. components: [renderPercentBar(percent)]
  7702. },
  7703. renderPercentText(percent)
  7704. ]);
  7705. });
  7706. }
  7707. };
  7708. const updateText = (comp, text) => {
  7709. if (comp.getSystem().isConnected()) {
  7710. const banner = memBannerText.get(comp);
  7711. Replacing.set(banner, [text$1(text)]);
  7712. }
  7713. };
  7714. const apis = {
  7715. updateProgress,
  7716. updateText
  7717. };
  7718. const iconChoices = flatten([
  7719. detail.icon.toArray(),
  7720. detail.level.toArray(),
  7721. detail.level.bind(level => Optional.from(notificationIconMap[level])).toArray()
  7722. ]);
  7723. const memButton = record(Button.sketch({
  7724. dom: {
  7725. tag: 'button',
  7726. classes: [
  7727. 'tox-notification__dismiss',
  7728. 'tox-button',
  7729. 'tox-button--naked',
  7730. 'tox-button--icon'
  7731. ]
  7732. },
  7733. components: [render$3('close', {
  7734. tag: 'div',
  7735. classes: ['tox-icon'],
  7736. attributes: { 'aria-label': detail.translationProvider('Close') }
  7737. }, detail.iconProvider)],
  7738. action: comp => {
  7739. detail.onAction(comp);
  7740. }
  7741. }));
  7742. const notificationIconSpec = renderFirst(iconChoices, {
  7743. tag: 'div',
  7744. classes: ['tox-notification__icon']
  7745. }, detail.iconProvider);
  7746. const notificationBodySpec = {
  7747. dom: {
  7748. tag: 'div',
  7749. classes: ['tox-notification__body']
  7750. },
  7751. components: [memBannerText.asSpec()],
  7752. behaviours: derive$1([Replacing.config({})])
  7753. };
  7754. const components = [
  7755. notificationIconSpec,
  7756. notificationBodySpec
  7757. ];
  7758. return {
  7759. uid: detail.uid,
  7760. dom: {
  7761. tag: 'div',
  7762. attributes: { role: 'alert' },
  7763. classes: detail.level.map(level => [
  7764. 'tox-notification',
  7765. 'tox-notification--in',
  7766. `tox-notification--${ level }`
  7767. ]).getOr([
  7768. 'tox-notification',
  7769. 'tox-notification--in'
  7770. ])
  7771. },
  7772. behaviours: derive$1([
  7773. Focusing.config({}),
  7774. config('notification-events', [run$1(focusin(), comp => {
  7775. memButton.getOpt(comp).each(Focusing.focus);
  7776. })])
  7777. ]),
  7778. components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
  7779. apis
  7780. };
  7781. };
  7782. const Notification = single({
  7783. name: 'Notification',
  7784. factory: factory$k,
  7785. configFields: [
  7786. option$3('level'),
  7787. required$1('progress'),
  7788. required$1('icon'),
  7789. required$1('onAction'),
  7790. required$1('text'),
  7791. required$1('iconProvider'),
  7792. required$1('translationProvider'),
  7793. defaultedBoolean('closeButton', true)
  7794. ],
  7795. apis: {
  7796. updateProgress: (apis, comp, percent) => {
  7797. apis.updateProgress(comp, percent);
  7798. },
  7799. updateText: (apis, comp, text) => {
  7800. apis.updateText(comp, text);
  7801. }
  7802. }
  7803. });
  7804. var NotificationManagerImpl = (editor, extras, uiMothership) => {
  7805. const sharedBackstage = extras.backstage.shared;
  7806. const getBounds = () => {
  7807. const contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  7808. const win$1 = win();
  7809. const x = clamp(win$1.x, contentArea.x, contentArea.right);
  7810. const y = clamp(win$1.y, contentArea.y, contentArea.bottom);
  7811. const right = Math.max(contentArea.right, win$1.right);
  7812. const bottom = Math.max(contentArea.bottom, win$1.bottom);
  7813. return Optional.some(bounds(x, y, right - x, bottom - y));
  7814. };
  7815. const open = (settings, closeCallback) => {
  7816. const close = () => {
  7817. closeCallback();
  7818. InlineView.hide(notificationWrapper);
  7819. };
  7820. const notification = build$1(Notification.sketch({
  7821. text: settings.text,
  7822. level: contains$2([
  7823. 'success',
  7824. 'error',
  7825. 'warning',
  7826. 'warn',
  7827. 'info'
  7828. ], settings.type) ? settings.type : undefined,
  7829. progress: settings.progressBar === true,
  7830. icon: Optional.from(settings.icon),
  7831. closeButton: settings.closeButton,
  7832. onAction: close,
  7833. iconProvider: sharedBackstage.providers.icons,
  7834. translationProvider: sharedBackstage.providers.translate
  7835. }));
  7836. const notificationWrapper = build$1(InlineView.sketch({
  7837. dom: {
  7838. tag: 'div',
  7839. classes: ['tox-notifications-container']
  7840. },
  7841. lazySink: sharedBackstage.getSink,
  7842. fireDismissalEventInstead: {},
  7843. ...sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} }
  7844. }));
  7845. uiMothership.add(notificationWrapper);
  7846. if (settings.timeout > 0) {
  7847. global$9.setEditorTimeout(editor, () => {
  7848. close();
  7849. }, settings.timeout);
  7850. }
  7851. const reposition = () => {
  7852. const notificationSpec = premade(notification);
  7853. const anchorOverrides = { maxHeightFunction: expandable$1() };
  7854. const allNotifications = editor.notificationManager.getNotifications();
  7855. if (allNotifications[0] === thisNotification) {
  7856. const anchor = {
  7857. ...sharedBackstage.anchors.banner(),
  7858. overrides: anchorOverrides
  7859. };
  7860. InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor }, getBounds);
  7861. } else {
  7862. indexOf(allNotifications, thisNotification).each(idx => {
  7863. const previousNotification = allNotifications[idx - 1].getEl();
  7864. const nodeAnchor = {
  7865. type: 'node',
  7866. root: body(),
  7867. node: Optional.some(SugarElement.fromDom(previousNotification)),
  7868. overrides: anchorOverrides,
  7869. layouts: {
  7870. onRtl: () => [south$2],
  7871. onLtr: () => [south$2]
  7872. }
  7873. };
  7874. InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds);
  7875. });
  7876. }
  7877. };
  7878. const thisNotification = {
  7879. close,
  7880. reposition,
  7881. text: nuText => {
  7882. Notification.updateText(notification, nuText);
  7883. },
  7884. settings,
  7885. getEl: () => notification.element.dom,
  7886. progressBar: {
  7887. value: percent => {
  7888. Notification.updateProgress(notification, percent);
  7889. }
  7890. }
  7891. };
  7892. return thisNotification;
  7893. };
  7894. const close = notification => {
  7895. notification.close();
  7896. };
  7897. const getArgs = notification => {
  7898. return notification.settings;
  7899. };
  7900. return {
  7901. open,
  7902. close,
  7903. getArgs
  7904. };
  7905. };
  7906. var global$7 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  7907. var global$6 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  7908. var global$5 = tinymce.util.Tools.resolve('tinymce.Env');
  7909. var ToolbarMode$1;
  7910. (function (ToolbarMode) {
  7911. ToolbarMode['default'] = 'wrap';
  7912. ToolbarMode['floating'] = 'floating';
  7913. ToolbarMode['sliding'] = 'sliding';
  7914. ToolbarMode['scrolling'] = 'scrolling';
  7915. }(ToolbarMode$1 || (ToolbarMode$1 = {})));
  7916. var ToolbarLocation$1;
  7917. (function (ToolbarLocation) {
  7918. ToolbarLocation['auto'] = 'auto';
  7919. ToolbarLocation['top'] = 'top';
  7920. ToolbarLocation['bottom'] = 'bottom';
  7921. }(ToolbarLocation$1 || (ToolbarLocation$1 = {})));
  7922. const option$2 = name => editor => editor.options.get(name);
  7923. const wrapOptional = fn => editor => Optional.from(fn(editor));
  7924. const register$e = editor => {
  7925. const isPhone = global$5.deviceType.isPhone();
  7926. const isMobile = global$5.deviceType.isTablet() || isPhone;
  7927. const registerOption = editor.options.register;
  7928. const stringOrFalseProcessor = value => isString(value) || value === false;
  7929. const stringOrNumberProcessor = value => isString(value) || isNumber(value);
  7930. registerOption('skin', {
  7931. processor: value => isString(value) || value === false,
  7932. default: 'oxide'
  7933. });
  7934. registerOption('skin_url', { processor: 'string' });
  7935. registerOption('height', {
  7936. processor: stringOrNumberProcessor,
  7937. default: Math.max(editor.getElement().offsetHeight, 400)
  7938. });
  7939. registerOption('width', {
  7940. processor: stringOrNumberProcessor,
  7941. default: global$7.DOM.getStyle(editor.getElement(), 'width')
  7942. });
  7943. registerOption('min_height', {
  7944. processor: 'number',
  7945. default: 100
  7946. });
  7947. registerOption('min_width', { processor: 'number' });
  7948. registerOption('max_height', { processor: 'number' });
  7949. registerOption('max_width', { processor: 'number' });
  7950. registerOption('style_formats', { processor: 'object[]' });
  7951. registerOption('style_formats_merge', {
  7952. processor: 'boolean',
  7953. default: false
  7954. });
  7955. registerOption('style_formats_autohide', {
  7956. processor: 'boolean',
  7957. default: false
  7958. });
  7959. registerOption('line_height_formats', {
  7960. processor: 'string',
  7961. default: '1 1.1 1.2 1.3 1.4 1.5 2'
  7962. });
  7963. registerOption('font_family_formats', {
  7964. processor: 'string',
  7965. default: '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'
  7966. });
  7967. registerOption('font_size_formats', {
  7968. processor: 'string',
  7969. default: '8pt 10pt 12pt 14pt 18pt 24pt 36pt'
  7970. });
  7971. registerOption('block_formats', {
  7972. processor: 'string',
  7973. default: 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre'
  7974. });
  7975. registerOption('content_langs', { processor: 'object[]' });
  7976. registerOption('removed_menuitems', {
  7977. processor: 'string',
  7978. default: ''
  7979. });
  7980. registerOption('menubar', {
  7981. processor: value => isString(value) || isBoolean(value),
  7982. default: !isPhone
  7983. });
  7984. registerOption('menu', {
  7985. processor: 'object',
  7986. default: {}
  7987. });
  7988. registerOption('toolbar', {
  7989. processor: value => {
  7990. if (isBoolean(value) || isString(value) || isArray(value)) {
  7991. return {
  7992. value,
  7993. valid: true
  7994. };
  7995. } else {
  7996. return {
  7997. valid: false,
  7998. message: 'Must be a boolean, string or array.'
  7999. };
  8000. }
  8001. },
  8002. default: true
  8003. });
  8004. range$2(9, num => {
  8005. registerOption('toolbar' + (num + 1), { processor: 'string' });
  8006. });
  8007. registerOption('toolbar_mode', {
  8008. processor: 'string',
  8009. default: isMobile ? 'scrolling' : 'floating'
  8010. });
  8011. registerOption('toolbar_groups', {
  8012. processor: 'object',
  8013. default: {}
  8014. });
  8015. registerOption('toolbar_location', {
  8016. processor: 'string',
  8017. default: ToolbarLocation$1.auto
  8018. });
  8019. registerOption('toolbar_persist', {
  8020. processor: 'boolean',
  8021. default: false
  8022. });
  8023. registerOption('toolbar_sticky', {
  8024. processor: 'boolean',
  8025. default: editor.inline
  8026. });
  8027. registerOption('toolbar_sticky_offset', {
  8028. processor: 'number',
  8029. default: 0
  8030. });
  8031. registerOption('fixed_toolbar_container', {
  8032. processor: 'string',
  8033. default: ''
  8034. });
  8035. registerOption('fixed_toolbar_container_target', { processor: 'object' });
  8036. registerOption('file_picker_callback', { processor: 'function' });
  8037. registerOption('file_picker_validator_handler', { processor: 'function' });
  8038. registerOption('file_picker_types', { processor: 'string' });
  8039. registerOption('typeahead_urls', {
  8040. processor: 'boolean',
  8041. default: true
  8042. });
  8043. registerOption('anchor_top', {
  8044. processor: stringOrFalseProcessor,
  8045. default: '#top'
  8046. });
  8047. registerOption('anchor_bottom', {
  8048. processor: stringOrFalseProcessor,
  8049. default: '#bottom'
  8050. });
  8051. registerOption('draggable_modal', {
  8052. processor: 'boolean',
  8053. default: false
  8054. });
  8055. registerOption('statusbar', {
  8056. processor: 'boolean',
  8057. default: true
  8058. });
  8059. registerOption('elementpath', {
  8060. processor: 'boolean',
  8061. default: true
  8062. });
  8063. registerOption('branding', {
  8064. processor: 'boolean',
  8065. default: true
  8066. });
  8067. registerOption('resize', {
  8068. processor: value => value === 'both' || isBoolean(value),
  8069. default: !global$5.deviceType.isTouch()
  8070. });
  8071. };
  8072. const isReadOnly = option$2('readonly');
  8073. const getHeightOption = option$2('height');
  8074. const getWidthOption = option$2('width');
  8075. const getMinWidthOption = wrapOptional(option$2('min_width'));
  8076. const getMinHeightOption = wrapOptional(option$2('min_height'));
  8077. const getMaxWidthOption = wrapOptional(option$2('max_width'));
  8078. const getMaxHeightOption = wrapOptional(option$2('max_height'));
  8079. const getUserStyleFormats = wrapOptional(option$2('style_formats'));
  8080. const shouldMergeStyleFormats = option$2('style_formats_merge');
  8081. const shouldAutoHideStyleFormats = option$2('style_formats_autohide');
  8082. const getContentLanguages = option$2('content_langs');
  8083. const getRemovedMenuItems = option$2('removed_menuitems');
  8084. const getToolbarMode = option$2('toolbar_mode');
  8085. const getToolbarGroups = option$2('toolbar_groups');
  8086. const getToolbarLocation = option$2('toolbar_location');
  8087. const fixedContainerSelector = option$2('fixed_toolbar_container');
  8088. const fixedToolbarContainerTarget = option$2('fixed_toolbar_container_target');
  8089. const isToolbarPersist = option$2('toolbar_persist');
  8090. const getStickyToolbarOffset = option$2('toolbar_sticky_offset');
  8091. const getMenubar = option$2('menubar');
  8092. const getToolbar = option$2('toolbar');
  8093. const getFilePickerCallback = option$2('file_picker_callback');
  8094. const getFilePickerValidatorHandler = option$2('file_picker_validator_handler');
  8095. const getFilePickerTypes = option$2('file_picker_types');
  8096. const useTypeaheadUrls = option$2('typeahead_urls');
  8097. const getAnchorTop = option$2('anchor_top');
  8098. const getAnchorBottom = option$2('anchor_bottom');
  8099. const isDraggableModal$1 = option$2('draggable_modal');
  8100. const useStatusBar = option$2('statusbar');
  8101. const useElementPath = option$2('elementpath');
  8102. const useBranding = option$2('branding');
  8103. const getResize = option$2('resize');
  8104. const getPasteAsText = option$2('paste_as_text');
  8105. const isSkinDisabled = editor => editor.options.get('skin') === false;
  8106. const isMenubarEnabled = editor => editor.options.get('menubar') !== false;
  8107. const getSkinUrl = editor => {
  8108. const skinUrl = editor.options.get('skin_url');
  8109. if (isSkinDisabled(editor)) {
  8110. return skinUrl;
  8111. } else {
  8112. if (skinUrl) {
  8113. return editor.documentBaseURI.toAbsolute(skinUrl);
  8114. } else {
  8115. const skin = editor.options.get('skin');
  8116. return global$6.baseURL + '/skins/ui/' + skin;
  8117. }
  8118. }
  8119. };
  8120. const getLineHeightFormats = editor => editor.options.get('line_height_formats').split(' ');
  8121. const isToolbarEnabled = editor => {
  8122. const toolbar = getToolbar(editor);
  8123. const isToolbarString = isString(toolbar);
  8124. const isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  8125. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || toolbar === true);
  8126. };
  8127. const getMultipleToolbarsOption = editor => {
  8128. const toolbars = range$2(9, num => editor.options.get('toolbar' + (num + 1)));
  8129. const toolbarArray = filter$2(toolbars, isString);
  8130. return someIf(toolbarArray.length > 0, toolbarArray);
  8131. };
  8132. const isMultipleToolbars = editor => getMultipleToolbarsOption(editor).fold(() => {
  8133. const toolbar = getToolbar(editor);
  8134. return isArrayOf(toolbar, isString) && toolbar.length > 0;
  8135. }, always);
  8136. const isToolbarLocationBottom = editor => getToolbarLocation(editor) === ToolbarLocation$1.bottom;
  8137. const fixedContainerTarget = editor => {
  8138. if (!editor.inline) {
  8139. return Optional.none();
  8140. }
  8141. const selector = fixedContainerSelector(editor);
  8142. if (selector.length > 0) {
  8143. return descendant(body(), selector);
  8144. }
  8145. const element = fixedToolbarContainerTarget(editor);
  8146. if (isNonNullable(element)) {
  8147. return Optional.some(SugarElement.fromDom(element));
  8148. }
  8149. return Optional.none();
  8150. };
  8151. const useFixedContainer = editor => editor.inline && fixedContainerTarget(editor).isSome();
  8152. const getUiContainer = editor => {
  8153. const fixedContainer = fixedContainerTarget(editor);
  8154. return fixedContainer.getOrThunk(() => getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement()))));
  8155. };
  8156. const isDistractionFree = editor => editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  8157. const isStickyToolbar = editor => {
  8158. const isStickyToolbar = editor.options.get('toolbar_sticky');
  8159. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  8160. };
  8161. const getMenus = editor => {
  8162. const menu = editor.options.get('menu');
  8163. return map$1(menu, menu => ({
  8164. ...menu,
  8165. items: menu.items
  8166. }));
  8167. };
  8168. var Options = /*#__PURE__*/Object.freeze({
  8169. __proto__: null,
  8170. get ToolbarMode () { return ToolbarMode$1; },
  8171. get ToolbarLocation () { return ToolbarLocation$1; },
  8172. register: register$e,
  8173. getSkinUrl: getSkinUrl,
  8174. isReadOnly: isReadOnly,
  8175. isSkinDisabled: isSkinDisabled,
  8176. getHeightOption: getHeightOption,
  8177. getWidthOption: getWidthOption,
  8178. getMinWidthOption: getMinWidthOption,
  8179. getMinHeightOption: getMinHeightOption,
  8180. getMaxWidthOption: getMaxWidthOption,
  8181. getMaxHeightOption: getMaxHeightOption,
  8182. getUserStyleFormats: getUserStyleFormats,
  8183. shouldMergeStyleFormats: shouldMergeStyleFormats,
  8184. shouldAutoHideStyleFormats: shouldAutoHideStyleFormats,
  8185. getLineHeightFormats: getLineHeightFormats,
  8186. getContentLanguages: getContentLanguages,
  8187. getRemovedMenuItems: getRemovedMenuItems,
  8188. isMenubarEnabled: isMenubarEnabled,
  8189. isMultipleToolbars: isMultipleToolbars,
  8190. isToolbarEnabled: isToolbarEnabled,
  8191. isToolbarPersist: isToolbarPersist,
  8192. getMultipleToolbarsOption: getMultipleToolbarsOption,
  8193. getUiContainer: getUiContainer,
  8194. useFixedContainer: useFixedContainer,
  8195. getToolbarMode: getToolbarMode,
  8196. isDraggableModal: isDraggableModal$1,
  8197. isDistractionFree: isDistractionFree,
  8198. isStickyToolbar: isStickyToolbar,
  8199. getStickyToolbarOffset: getStickyToolbarOffset,
  8200. getToolbarLocation: getToolbarLocation,
  8201. isToolbarLocationBottom: isToolbarLocationBottom,
  8202. getToolbarGroups: getToolbarGroups,
  8203. getMenus: getMenus,
  8204. getMenubar: getMenubar,
  8205. getToolbar: getToolbar,
  8206. getFilePickerCallback: getFilePickerCallback,
  8207. getFilePickerTypes: getFilePickerTypes,
  8208. useTypeaheadUrls: useTypeaheadUrls,
  8209. getAnchorTop: getAnchorTop,
  8210. getAnchorBottom: getAnchorBottom,
  8211. getFilePickerValidatorHandler: getFilePickerValidatorHandler,
  8212. useStatusBar: useStatusBar,
  8213. useElementPath: useElementPath,
  8214. useBranding: useBranding,
  8215. getResize: getResize,
  8216. getPasteAsText: getPasteAsText
  8217. });
  8218. const autocompleteSelector = '[data-mce-autocompleter]';
  8219. const detect = elm => closest$1(elm, autocompleteSelector);
  8220. const findIn = elm => descendant(elm, autocompleteSelector);
  8221. const setup$e = (api, editor) => {
  8222. const redirectKeyToItem = (item, e) => {
  8223. emitWith(item, keydown(), { raw: e });
  8224. };
  8225. const getItem = () => api.getView().bind(Highlighting.getHighlighted);
  8226. editor.on('keydown', e => {
  8227. const keyCode = e.which;
  8228. if (!api.isActive()) {
  8229. return;
  8230. }
  8231. if (api.isMenuOpen()) {
  8232. if (keyCode === 13) {
  8233. getItem().each(emitExecute);
  8234. e.preventDefault();
  8235. } else if (keyCode === 40) {
  8236. getItem().fold(() => {
  8237. api.getView().each(Highlighting.highlightFirst);
  8238. }, item => {
  8239. redirectKeyToItem(item, e);
  8240. });
  8241. e.preventDefault();
  8242. e.stopImmediatePropagation();
  8243. } else if (keyCode === 37 || keyCode === 38 || keyCode === 39) {
  8244. getItem().each(item => {
  8245. redirectKeyToItem(item, e);
  8246. e.preventDefault();
  8247. e.stopImmediatePropagation();
  8248. });
  8249. }
  8250. } else {
  8251. if (keyCode === 13 || keyCode === 38 || keyCode === 40) {
  8252. api.cancelIfNecessary();
  8253. }
  8254. }
  8255. });
  8256. editor.on('NodeChange', e => {
  8257. if (api.isActive() && !api.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) {
  8258. api.cancelIfNecessary();
  8259. }
  8260. });
  8261. };
  8262. const AutocompleterEditorEvents = { setup: setup$e };
  8263. var ItemResponse;
  8264. (function (ItemResponse) {
  8265. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  8266. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  8267. }(ItemResponse || (ItemResponse = {})));
  8268. var ItemResponse$1 = ItemResponse;
  8269. const navClass = 'tox-menu-nav__js';
  8270. const selectableClass = 'tox-collection__item';
  8271. const colorClass = 'tox-swatch';
  8272. const presetClasses = {
  8273. normal: navClass,
  8274. color: colorClass
  8275. };
  8276. const tickedClass = 'tox-collection__item--enabled';
  8277. const groupHeadingClass = 'tox-collection__group-heading';
  8278. const iconClass = 'tox-collection__item-icon';
  8279. const textClass = 'tox-collection__item-label';
  8280. const accessoryClass = 'tox-collection__item-accessory';
  8281. const caretClass = 'tox-collection__item-caret';
  8282. const checkmarkClass = 'tox-collection__item-checkmark';
  8283. const activeClass = 'tox-collection__item--active';
  8284. const containerClass = 'tox-collection__item-container';
  8285. const containerColumnClass = 'tox-collection__item-container--column';
  8286. const containerRowClass = 'tox-collection__item-container--row';
  8287. const containerAlignRightClass = 'tox-collection__item-container--align-right';
  8288. const containerAlignLeftClass = 'tox-collection__item-container--align-left';
  8289. const containerValignTopClass = 'tox-collection__item-container--valign-top';
  8290. const containerValignMiddleClass = 'tox-collection__item-container--valign-middle';
  8291. const containerValignBottomClass = 'tox-collection__item-container--valign-bottom';
  8292. const classForPreset = presets => get$g(presetClasses, presets).getOr(navClass);
  8293. const forMenu = presets => {
  8294. if (presets === 'color') {
  8295. return 'tox-swatches';
  8296. } else {
  8297. return 'tox-menu';
  8298. }
  8299. };
  8300. const classes = presets => ({
  8301. backgroundMenu: 'tox-background-menu',
  8302. selectedMenu: 'tox-selected-menu',
  8303. selectedItem: 'tox-collection__item--active',
  8304. hasIcons: 'tox-menu--has-icons',
  8305. menu: forMenu(presets),
  8306. tieredMenu: 'tox-tiered-menu'
  8307. });
  8308. const markers = presets => {
  8309. const menuClasses = classes(presets);
  8310. return {
  8311. backgroundMenu: menuClasses.backgroundMenu,
  8312. selectedMenu: menuClasses.selectedMenu,
  8313. menu: menuClasses.menu,
  8314. selectedItem: menuClasses.selectedItem,
  8315. item: classForPreset(presets)
  8316. };
  8317. };
  8318. const dom$1 = (hasIcons, columns, presets) => {
  8319. const menuClasses = classes(presets);
  8320. return {
  8321. tag: 'div',
  8322. classes: flatten([
  8323. [
  8324. menuClasses.menu,
  8325. `tox-menu-${ columns }-column`
  8326. ],
  8327. hasIcons ? [menuClasses.hasIcons] : []
  8328. ])
  8329. };
  8330. };
  8331. const components = [Menu.parts.items({})];
  8332. const part = (hasIcons, columns, presets) => {
  8333. const menuClasses = classes(presets);
  8334. const d = {
  8335. tag: 'div',
  8336. classes: flatten([[menuClasses.tieredMenu]])
  8337. };
  8338. return {
  8339. dom: d,
  8340. markers: markers(presets)
  8341. };
  8342. };
  8343. const chunk = (rowDom, numColumns) => items => {
  8344. const chunks = chunk$1(items, numColumns);
  8345. return map$2(chunks, c => ({
  8346. dom: rowDom,
  8347. components: c
  8348. }));
  8349. };
  8350. const forSwatch = columns => ({
  8351. dom: {
  8352. tag: 'div',
  8353. classes: [
  8354. 'tox-menu',
  8355. 'tox-swatches-menu'
  8356. ]
  8357. },
  8358. components: [{
  8359. dom: {
  8360. tag: 'div',
  8361. classes: ['tox-swatches']
  8362. },
  8363. components: [Menu.parts.items({
  8364. preprocess: columns !== 'auto' ? chunk({
  8365. tag: 'div',
  8366. classes: ['tox-swatches__row']
  8367. }, columns) : identity
  8368. })]
  8369. }]
  8370. });
  8371. const forToolbar = columns => ({
  8372. dom: {
  8373. tag: 'div',
  8374. classes: [
  8375. 'tox-menu',
  8376. 'tox-collection',
  8377. 'tox-collection--toolbar',
  8378. 'tox-collection--toolbar-lg'
  8379. ]
  8380. },
  8381. components: [Menu.parts.items({
  8382. preprocess: chunk({
  8383. tag: 'div',
  8384. classes: ['tox-collection__group']
  8385. }, columns)
  8386. })]
  8387. });
  8388. const preprocessCollection = (items, isSeparator) => {
  8389. const allSplits = [];
  8390. let currentSplit = [];
  8391. each$1(items, (item, i) => {
  8392. if (isSeparator(item, i)) {
  8393. if (currentSplit.length > 0) {
  8394. allSplits.push(currentSplit);
  8395. }
  8396. currentSplit = [];
  8397. if (has$2(item.dom, 'innerHtml') || item.components.length > 0) {
  8398. currentSplit.push(item);
  8399. }
  8400. } else {
  8401. currentSplit.push(item);
  8402. }
  8403. });
  8404. if (currentSplit.length > 0) {
  8405. allSplits.push(currentSplit);
  8406. }
  8407. return map$2(allSplits, s => ({
  8408. dom: {
  8409. tag: 'div',
  8410. classes: ['tox-collection__group']
  8411. },
  8412. components: s
  8413. }));
  8414. };
  8415. const forCollection = (columns, initItems, _hasIcons = true) => ({
  8416. dom: {
  8417. tag: 'div',
  8418. classes: [
  8419. 'tox-menu',
  8420. 'tox-collection'
  8421. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  8422. },
  8423. components: [Menu.parts.items({
  8424. preprocess: items => {
  8425. if (columns !== 'auto' && columns > 1) {
  8426. return chunk({
  8427. tag: 'div',
  8428. classes: ['tox-collection__group']
  8429. }, columns)(items);
  8430. } else {
  8431. return preprocessCollection(items, (_item, i) => initItems[i].type === 'separator');
  8432. }
  8433. }
  8434. })]
  8435. });
  8436. const forHorizontalCollection = (initItems, _hasIcons = true) => ({
  8437. dom: {
  8438. tag: 'div',
  8439. classes: [
  8440. 'tox-collection',
  8441. 'tox-collection--horizontal'
  8442. ]
  8443. },
  8444. components: [Menu.parts.items({ preprocess: items => preprocessCollection(items, (_item, i) => initItems[i].type === 'separator') })]
  8445. });
  8446. const menuHasIcons = xs => exists(xs, item => 'icon' in item && item.icon !== undefined);
  8447. const handleError = error => {
  8448. console.error(formatError(error));
  8449. console.log(error);
  8450. return Optional.none();
  8451. };
  8452. const createHorizontalPartialMenuWithAlloyItems = (value, _hasIcons, items, _columns, _presets) => {
  8453. const structure = forHorizontalCollection(items);
  8454. return {
  8455. value,
  8456. dom: structure.dom,
  8457. components: structure.components,
  8458. items
  8459. };
  8460. };
  8461. const createPartialMenuWithAlloyItems = (value, hasIcons, items, columns, presets) => {
  8462. if (presets === 'color') {
  8463. const structure = forSwatch(columns);
  8464. return {
  8465. value,
  8466. dom: structure.dom,
  8467. components: structure.components,
  8468. items
  8469. };
  8470. }
  8471. if (presets === 'normal' && columns === 'auto') {
  8472. const structure = forCollection(columns, items);
  8473. return {
  8474. value,
  8475. dom: structure.dom,
  8476. components: structure.components,
  8477. items
  8478. };
  8479. }
  8480. if (presets === 'normal' && columns === 1) {
  8481. const structure = forCollection(1, items);
  8482. return {
  8483. value,
  8484. dom: structure.dom,
  8485. components: structure.components,
  8486. items
  8487. };
  8488. }
  8489. if (presets === 'normal') {
  8490. const structure = forCollection(columns, items);
  8491. return {
  8492. value,
  8493. dom: structure.dom,
  8494. components: structure.components,
  8495. items
  8496. };
  8497. }
  8498. if (presets === 'listpreview' && columns !== 'auto') {
  8499. const structure = forToolbar(columns);
  8500. return {
  8501. value,
  8502. dom: structure.dom,
  8503. components: structure.components,
  8504. items
  8505. };
  8506. }
  8507. return {
  8508. value,
  8509. dom: dom$1(hasIcons, columns, presets),
  8510. components: components,
  8511. items
  8512. };
  8513. };
  8514. const type = requiredString('type');
  8515. const name$1 = requiredString('name');
  8516. const label = requiredString('label');
  8517. const text = requiredString('text');
  8518. const title = requiredString('title');
  8519. const icon = requiredString('icon');
  8520. const value$1 = requiredString('value');
  8521. const fetch$1 = requiredFunction('fetch');
  8522. const getSubmenuItems = requiredFunction('getSubmenuItems');
  8523. const onAction = requiredFunction('onAction');
  8524. const onItemAction = requiredFunction('onItemAction');
  8525. const onSetup = defaultedFunction('onSetup', () => noop);
  8526. const optionalName = optionString('name');
  8527. const optionalText = optionString('text');
  8528. const optionalIcon = optionString('icon');
  8529. const optionalTooltip = optionString('tooltip');
  8530. const optionalLabel = optionString('label');
  8531. const optionalShortcut = optionString('shortcut');
  8532. const optionalSelect = optionFunction('select');
  8533. const active = defaultedBoolean('active', false);
  8534. const borderless = defaultedBoolean('borderless', false);
  8535. const enabled = defaultedBoolean('enabled', true);
  8536. const primary = defaultedBoolean('primary', false);
  8537. const defaultedColumns = num => defaulted('columns', num);
  8538. const defaultedMeta = defaulted('meta', {});
  8539. const defaultedOnAction = defaultedFunction('onAction', noop);
  8540. const defaultedType = type => defaultedString('type', type);
  8541. const generatedName = namePrefix => field$1('name', 'name', defaultedThunk(() => generate$6(`${ namePrefix }-name`)), string);
  8542. const generatedValue = valuePrefix => field$1('value', 'value', defaultedThunk(() => generate$6(`${ valuePrefix }-value`)), anyValue());
  8543. const separatorMenuItemSchema = objOf([
  8544. type,
  8545. optionalText
  8546. ]);
  8547. const createSeparatorMenuItem = spec => asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  8548. const autocompleterItemSchema = objOf([
  8549. defaultedType('autocompleteitem'),
  8550. active,
  8551. enabled,
  8552. defaultedMeta,
  8553. value$1,
  8554. optionalText,
  8555. optionalIcon
  8556. ]);
  8557. const createSeparatorItem = spec => asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  8558. const createAutocompleterItem = spec => asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  8559. const baseToolbarButtonFields = [
  8560. enabled,
  8561. optionalTooltip,
  8562. optionalIcon,
  8563. optionalText,
  8564. onSetup
  8565. ];
  8566. const toolbarButtonSchema = objOf([
  8567. type,
  8568. onAction
  8569. ].concat(baseToolbarButtonFields));
  8570. const createToolbarButton = spec => asRaw('toolbarbutton', toolbarButtonSchema, spec);
  8571. const baseToolbarToggleButtonFields = [active].concat(baseToolbarButtonFields);
  8572. const toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  8573. type,
  8574. onAction
  8575. ]));
  8576. const createToggleButton = spec => asRaw('ToggleButton', toggleButtonSchema, spec);
  8577. const contextBarFields = [
  8578. defaultedFunction('predicate', never),
  8579. defaultedStringEnum('scope', 'node', [
  8580. 'node',
  8581. 'editor'
  8582. ]),
  8583. defaultedStringEnum('position', 'selection', [
  8584. 'node',
  8585. 'selection',
  8586. 'line'
  8587. ])
  8588. ];
  8589. const contextButtonFields = baseToolbarButtonFields.concat([
  8590. defaultedType('contextformbutton'),
  8591. primary,
  8592. onAction,
  8593. customField('original', identity)
  8594. ]);
  8595. const contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  8596. defaultedType('contextformbutton'),
  8597. primary,
  8598. onAction,
  8599. customField('original', identity)
  8600. ]);
  8601. const launchButtonFields = baseToolbarButtonFields.concat([defaultedType('contextformbutton')]);
  8602. const launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaultedType('contextformtogglebutton')]);
  8603. const toggleOrNormal = choose$1('type', {
  8604. contextformbutton: contextButtonFields,
  8605. contextformtogglebutton: contextToggleButtonFields
  8606. });
  8607. const contextFormSchema = objOf([
  8608. defaultedType('contextform'),
  8609. defaultedFunction('initValue', constant$1('')),
  8610. optionalLabel,
  8611. requiredArrayOf('commands', toggleOrNormal),
  8612. optionOf('launch', choose$1('type', {
  8613. contextformbutton: launchButtonFields,
  8614. contextformtogglebutton: launchToggleButtonFields
  8615. }))
  8616. ].concat(contextBarFields));
  8617. const createContextForm = spec => asRaw('ContextForm', contextFormSchema, spec);
  8618. const contextToolbarSchema = objOf([
  8619. defaultedType('contexttoolbar'),
  8620. requiredString('items')
  8621. ].concat(contextBarFields));
  8622. const createContextToolbar = spec => asRaw('ContextToolbar', contextToolbarSchema, spec);
  8623. const cardImageFields = [
  8624. type,
  8625. requiredString('src'),
  8626. optionString('alt'),
  8627. defaultedArrayOf('classes', [], string)
  8628. ];
  8629. const cardImageSchema = objOf(cardImageFields);
  8630. const cardTextFields = [
  8631. type,
  8632. text,
  8633. optionalName,
  8634. defaultedArrayOf('classes', ['tox-collection__item-label'], string)
  8635. ];
  8636. const cardTextSchema = objOf(cardTextFields);
  8637. const itemSchema$1 = valueThunk(() => choose$2('type', {
  8638. cardimage: cardImageSchema,
  8639. cardtext: cardTextSchema,
  8640. cardcontainer: cardContainerSchema
  8641. }));
  8642. const cardContainerSchema = objOf([
  8643. type,
  8644. defaultedString('direction', 'horizontal'),
  8645. defaultedString('align', 'left'),
  8646. defaultedString('valign', 'middle'),
  8647. requiredArrayOf('items', itemSchema$1)
  8648. ]);
  8649. const commonMenuItemFields = [
  8650. enabled,
  8651. optionalText,
  8652. optionalShortcut,
  8653. generatedValue('menuitem'),
  8654. defaultedMeta
  8655. ];
  8656. const cardMenuItemSchema = objOf([
  8657. type,
  8658. optionalLabel,
  8659. requiredArrayOf('items', itemSchema$1),
  8660. onSetup,
  8661. defaultedOnAction
  8662. ].concat(commonMenuItemFields));
  8663. const createCardMenuItem = spec => asRaw('cardmenuitem', cardMenuItemSchema, spec);
  8664. const choiceMenuItemSchema = objOf([
  8665. type,
  8666. active,
  8667. optionalIcon
  8668. ].concat(commonMenuItemFields));
  8669. const createChoiceMenuItem = spec => asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  8670. const baseFields = [
  8671. type,
  8672. requiredString('fancytype'),
  8673. defaultedOnAction
  8674. ];
  8675. const insertTableFields = [defaulted('initData', {})].concat(baseFields);
  8676. const colorSwatchFields = [defaultedObjOf('initData', {}, [
  8677. defaultedBoolean('allowCustomColors', true),
  8678. optionArrayOf('colors', anyValue())
  8679. ])].concat(baseFields);
  8680. const fancyMenuItemSchema = choose$1('fancytype', {
  8681. inserttable: insertTableFields,
  8682. colorswatch: colorSwatchFields
  8683. });
  8684. const createFancyMenuItem = spec => asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  8685. const menuItemSchema = objOf([
  8686. type,
  8687. onSetup,
  8688. defaultedOnAction,
  8689. optionalIcon
  8690. ].concat(commonMenuItemFields));
  8691. const createMenuItem = spec => asRaw('menuitem', menuItemSchema, spec);
  8692. const nestedMenuItemSchema = objOf([
  8693. type,
  8694. getSubmenuItems,
  8695. onSetup,
  8696. optionalIcon
  8697. ].concat(commonMenuItemFields));
  8698. const createNestedMenuItem = spec => asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  8699. const toggleMenuItemSchema = objOf([
  8700. type,
  8701. optionalIcon,
  8702. active,
  8703. onSetup,
  8704. onAction
  8705. ].concat(commonMenuItemFields));
  8706. const createToggleMenuItem = spec => asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  8707. const detectSize = (comp, margin, selectorClass) => {
  8708. const descendants$1 = descendants(comp.element, '.' + selectorClass);
  8709. if (descendants$1.length > 0) {
  8710. const columnLength = findIndex$1(descendants$1, c => {
  8711. const thisTop = c.dom.getBoundingClientRect().top;
  8712. const cTop = descendants$1[0].dom.getBoundingClientRect().top;
  8713. return Math.abs(thisTop - cTop) > margin;
  8714. }).getOr(descendants$1.length);
  8715. return Optional.some({
  8716. numColumns: columnLength,
  8717. numRows: Math.ceil(descendants$1.length / columnLength)
  8718. });
  8719. } else {
  8720. return Optional.none();
  8721. }
  8722. };
  8723. const namedEvents = (name, handlers) => derive$1([config(name, handlers)]);
  8724. const unnamedEvents = handlers => namedEvents(generate$6('unnamed-events'), handlers);
  8725. const SimpleBehaviours = {
  8726. namedEvents,
  8727. unnamedEvents
  8728. };
  8729. const ExclusivityChannel = generate$6('tooltip.exclusive');
  8730. const ShowTooltipEvent = generate$6('tooltip.show');
  8731. const HideTooltipEvent = generate$6('tooltip.hide');
  8732. const hideAllExclusive = (component, _tConfig, _tState) => {
  8733. component.getSystem().broadcastOn([ExclusivityChannel], {});
  8734. };
  8735. const setComponents = (component, tConfig, tState, specs) => {
  8736. tState.getTooltip().each(tooltip => {
  8737. if (tooltip.getSystem().isConnected()) {
  8738. Replacing.set(tooltip, specs);
  8739. }
  8740. });
  8741. };
  8742. var TooltippingApis = /*#__PURE__*/Object.freeze({
  8743. __proto__: null,
  8744. hideAllExclusive: hideAllExclusive,
  8745. setComponents: setComponents
  8746. });
  8747. const events$9 = (tooltipConfig, state) => {
  8748. const hide = comp => {
  8749. state.getTooltip().each(p => {
  8750. detach(p);
  8751. tooltipConfig.onHide(comp, p);
  8752. state.clearTooltip();
  8753. });
  8754. state.clearTimer();
  8755. };
  8756. const show = comp => {
  8757. if (!state.isShowing()) {
  8758. hideAllExclusive(comp);
  8759. const sink = tooltipConfig.lazySink(comp).getOrDie();
  8760. const popup = comp.getSystem().build({
  8761. dom: tooltipConfig.tooltipDom,
  8762. components: tooltipConfig.tooltipComponents,
  8763. events: derive$2(tooltipConfig.mode === 'normal' ? [
  8764. run$1(mouseover(), _ => {
  8765. emit(comp, ShowTooltipEvent);
  8766. }),
  8767. run$1(mouseout(), _ => {
  8768. emit(comp, HideTooltipEvent);
  8769. })
  8770. ] : []),
  8771. behaviours: derive$1([Replacing.config({})])
  8772. });
  8773. state.setTooltip(popup);
  8774. attach(sink, popup);
  8775. tooltipConfig.onShow(comp, popup);
  8776. Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
  8777. }
  8778. };
  8779. return derive$2(flatten([
  8780. [
  8781. run$1(ShowTooltipEvent, comp => {
  8782. state.resetTimer(() => {
  8783. show(comp);
  8784. }, tooltipConfig.delay);
  8785. }),
  8786. run$1(HideTooltipEvent, comp => {
  8787. state.resetTimer(() => {
  8788. hide(comp);
  8789. }, tooltipConfig.delay);
  8790. }),
  8791. run$1(receive(), (comp, message) => {
  8792. const receivingData = message;
  8793. if (!receivingData.universal) {
  8794. if (contains$2(receivingData.channels, ExclusivityChannel)) {
  8795. hide(comp);
  8796. }
  8797. }
  8798. }),
  8799. runOnDetached(comp => {
  8800. hide(comp);
  8801. })
  8802. ],
  8803. tooltipConfig.mode === 'normal' ? [
  8804. run$1(focusin(), comp => {
  8805. emit(comp, ShowTooltipEvent);
  8806. }),
  8807. run$1(postBlur(), comp => {
  8808. emit(comp, HideTooltipEvent);
  8809. }),
  8810. run$1(mouseover(), comp => {
  8811. emit(comp, ShowTooltipEvent);
  8812. }),
  8813. run$1(mouseout(), comp => {
  8814. emit(comp, HideTooltipEvent);
  8815. })
  8816. ] : [
  8817. run$1(highlight$1(), (comp, _se) => {
  8818. emit(comp, ShowTooltipEvent);
  8819. }),
  8820. run$1(dehighlight$1(), comp => {
  8821. emit(comp, HideTooltipEvent);
  8822. })
  8823. ]
  8824. ]));
  8825. };
  8826. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  8827. __proto__: null,
  8828. events: events$9
  8829. });
  8830. var TooltippingSchema = [
  8831. required$1('lazySink'),
  8832. required$1('tooltipDom'),
  8833. defaulted('exclusive', true),
  8834. defaulted('tooltipComponents', []),
  8835. defaulted('delay', 300),
  8836. defaultedStringEnum('mode', 'normal', [
  8837. 'normal',
  8838. 'follow-highlight'
  8839. ]),
  8840. defaulted('anchor', comp => ({
  8841. type: 'hotspot',
  8842. hotspot: comp,
  8843. layouts: {
  8844. onLtr: constant$1([
  8845. south$2,
  8846. north$2,
  8847. southeast$2,
  8848. northeast$2,
  8849. southwest$2,
  8850. northwest$2
  8851. ]),
  8852. onRtl: constant$1([
  8853. south$2,
  8854. north$2,
  8855. southeast$2,
  8856. northeast$2,
  8857. southwest$2,
  8858. northwest$2
  8859. ])
  8860. }
  8861. })),
  8862. onHandler('onHide'),
  8863. onHandler('onShow')
  8864. ];
  8865. const init$b = () => {
  8866. const timer = value$2();
  8867. const popup = value$2();
  8868. const clearTimer = () => {
  8869. timer.on(clearTimeout);
  8870. };
  8871. const resetTimer = (f, delay) => {
  8872. clearTimer();
  8873. timer.set(setTimeout(f, delay));
  8874. };
  8875. const readState = constant$1('not-implemented');
  8876. return nu$8({
  8877. getTooltip: popup.get,
  8878. isShowing: popup.isSet,
  8879. setTooltip: popup.set,
  8880. clearTooltip: popup.clear,
  8881. clearTimer,
  8882. resetTimer,
  8883. readState
  8884. });
  8885. };
  8886. var TooltippingState = /*#__PURE__*/Object.freeze({
  8887. __proto__: null,
  8888. init: init$b
  8889. });
  8890. const Tooltipping = create$3({
  8891. fields: TooltippingSchema,
  8892. name: 'tooltipping',
  8893. active: ActiveTooltipping,
  8894. state: TooltippingState,
  8895. apis: TooltippingApis
  8896. });
  8897. const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  8898. const ReadOnlyChannel = 'silver.readonly';
  8899. const ReadOnlyDataSchema = objOf([requiredBoolean('readonly')]);
  8900. const broadcastReadonly = (uiComponents, readonly) => {
  8901. const outerContainer = uiComponents.outerContainer;
  8902. const target = outerContainer.element;
  8903. if (readonly) {
  8904. uiComponents.mothership.broadcastOn([dismissPopups()], { target });
  8905. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target });
  8906. }
  8907. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly });
  8908. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly });
  8909. };
  8910. const setupReadonlyModeSwitch = (editor, uiComponents) => {
  8911. editor.on('init', () => {
  8912. if (editor.mode.isReadOnly()) {
  8913. broadcastReadonly(uiComponents, true);
  8914. }
  8915. });
  8916. editor.on('SwitchMode', () => broadcastReadonly(uiComponents, editor.mode.isReadOnly()));
  8917. if (isReadOnly(editor)) {
  8918. editor.mode.set('readonly');
  8919. }
  8920. };
  8921. const receivingConfig = () => Receiving.config({
  8922. channels: {
  8923. [ReadOnlyChannel]: {
  8924. schema: ReadOnlyDataSchema,
  8925. onReceive: (comp, data) => {
  8926. Disabling.set(comp, data.readonly);
  8927. }
  8928. }
  8929. }
  8930. });
  8931. const item = disabled => Disabling.config({
  8932. disabled,
  8933. disableClass: 'tox-collection__item--state-disabled'
  8934. });
  8935. const button = disabled => Disabling.config({ disabled });
  8936. const splitButton = disabled => Disabling.config({
  8937. disabled,
  8938. disableClass: 'tox-tbtn--disabled'
  8939. });
  8940. const toolbarButton = disabled => Disabling.config({
  8941. disabled,
  8942. disableClass: 'tox-tbtn--disabled',
  8943. useNative: false
  8944. });
  8945. const DisablingConfigs = {
  8946. item,
  8947. button,
  8948. splitButton,
  8949. toolbarButton
  8950. };
  8951. const runWithApi = (info, comp) => {
  8952. const api = info.getApi(comp);
  8953. return f => {
  8954. f(api);
  8955. };
  8956. };
  8957. const onControlAttached = (info, editorOffCell) => runOnAttached(comp => {
  8958. const run = runWithApi(info, comp);
  8959. run(api => {
  8960. const onDestroy = info.onSetup(api);
  8961. if (isFunction(onDestroy)) {
  8962. editorOffCell.set(onDestroy);
  8963. }
  8964. });
  8965. });
  8966. const onControlDetached = (getApi, editorOffCell) => runOnDetached(comp => runWithApi(getApi, comp)(editorOffCell.get()));
  8967. const onMenuItemExecute = (info, itemResponse) => runOnExecute$1((comp, simulatedEvent) => {
  8968. runWithApi(info, comp)(info.onAction);
  8969. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  8970. if (comp.getSystem().isConnected()) {
  8971. emit(comp, sandboxClose());
  8972. }
  8973. simulatedEvent.stop();
  8974. }
  8975. });
  8976. const menuItemEventOrder = {
  8977. [execute$5()]: [
  8978. 'disabling',
  8979. 'alloy.base.behaviour',
  8980. 'toggling',
  8981. 'item-events'
  8982. ]
  8983. };
  8984. const componentRenderPipeline = cat;
  8985. const renderCommonItem = (spec, structure, itemResponse, providersbackstage) => {
  8986. const editorOffCell = Cell(noop);
  8987. return {
  8988. type: 'item',
  8989. dom: structure.dom,
  8990. components: componentRenderPipeline(structure.optComponents),
  8991. data: spec.data,
  8992. eventOrder: menuItemEventOrder,
  8993. hasSubmenu: spec.triggersSubmenu,
  8994. itemBehaviours: derive$1([
  8995. config('item-events', [
  8996. onMenuItemExecute(spec, itemResponse),
  8997. onControlAttached(spec, editorOffCell),
  8998. onControlDetached(spec, editorOffCell)
  8999. ]),
  9000. DisablingConfigs.item(() => !spec.enabled || providersbackstage.isDisabled()),
  9001. receivingConfig(),
  9002. Replacing.config({})
  9003. ].concat(spec.itemBehaviours))
  9004. };
  9005. };
  9006. const buildData = source => ({
  9007. value: source.value,
  9008. meta: {
  9009. text: source.text.getOr(''),
  9010. ...source.meta
  9011. }
  9012. });
  9013. const convertText = source => {
  9014. const isMac = global$5.os.isMacOS() || global$5.os.isiOS();
  9015. const mac = {
  9016. alt: '\u2325',
  9017. ctrl: '\u2303',
  9018. shift: '\u21E7',
  9019. meta: '\u2318',
  9020. access: '\u2303\u2325'
  9021. };
  9022. const other = {
  9023. meta: 'Ctrl',
  9024. access: 'Shift+Alt'
  9025. };
  9026. const replace = isMac ? mac : other;
  9027. const shortcut = source.split('+');
  9028. const updated = map$2(shortcut, segment => {
  9029. const search = segment.toLowerCase().trim();
  9030. return has$2(replace, search) ? replace[search] : segment;
  9031. });
  9032. return isMac ? updated.join('') : updated.join('+');
  9033. };
  9034. const renderIcon$1 = (name, icons, classes = [iconClass]) => render$3(name, {
  9035. tag: 'div',
  9036. classes
  9037. }, icons);
  9038. const renderText = text => ({
  9039. dom: {
  9040. tag: 'div',
  9041. classes: [textClass]
  9042. },
  9043. components: [text$1(global$8.translate(text))]
  9044. });
  9045. const renderHtml = (html, classes) => ({
  9046. dom: {
  9047. tag: 'div',
  9048. classes,
  9049. innerHtml: html
  9050. }
  9051. });
  9052. const renderStyledText = (style, text) => ({
  9053. dom: {
  9054. tag: 'div',
  9055. classes: [textClass]
  9056. },
  9057. components: [{
  9058. dom: {
  9059. tag: style.tag,
  9060. styles: style.styles
  9061. },
  9062. components: [text$1(global$8.translate(text))]
  9063. }]
  9064. });
  9065. const renderShortcut = shortcut => ({
  9066. dom: {
  9067. tag: 'div',
  9068. classes: [accessoryClass]
  9069. },
  9070. components: [text$1(convertText(shortcut))]
  9071. });
  9072. const renderCheckmark = icons => renderIcon$1('checkmark', icons, [checkmarkClass]);
  9073. const renderSubmenuCaret = icons => renderIcon$1('chevron-right', icons, [caretClass]);
  9074. const renderDownwardsCaret = icons => renderIcon$1('chevron-down', icons, [caretClass]);
  9075. const renderContainer = (container, components) => {
  9076. const directionClass = container.direction === 'vertical' ? containerColumnClass : containerRowClass;
  9077. const alignClass = container.align === 'left' ? containerAlignLeftClass : containerAlignRightClass;
  9078. const getValignClass = () => {
  9079. switch (container.valign) {
  9080. case 'top':
  9081. return containerValignTopClass;
  9082. case 'middle':
  9083. return containerValignMiddleClass;
  9084. case 'bottom':
  9085. return containerValignBottomClass;
  9086. }
  9087. };
  9088. return {
  9089. dom: {
  9090. tag: 'div',
  9091. classes: [
  9092. containerClass,
  9093. directionClass,
  9094. alignClass,
  9095. getValignClass()
  9096. ]
  9097. },
  9098. components
  9099. };
  9100. };
  9101. const renderImage = (src, classes, alt) => ({
  9102. dom: {
  9103. tag: 'img',
  9104. classes,
  9105. attributes: {
  9106. src,
  9107. alt: alt.getOr('')
  9108. }
  9109. }
  9110. });
  9111. const renderColorStructure = (item, providerBackstage, fallbackIcon) => {
  9112. const colorPickerCommand = 'custom';
  9113. const removeColorCommand = 'remove';
  9114. const itemText = item.ariaLabel;
  9115. const itemValue = item.value;
  9116. const iconSvg = item.iconContent.map(name => getOr(name, providerBackstage.icons, fallbackIcon));
  9117. const getDom = () => {
  9118. const common = colorClass;
  9119. const icon = iconSvg.getOr('');
  9120. const attributes = itemText.map(text => ({ title: providerBackstage.translate(text) })).getOr({});
  9121. const baseDom = {
  9122. tag: 'div',
  9123. attributes,
  9124. classes: [common]
  9125. };
  9126. if (itemValue === colorPickerCommand) {
  9127. return {
  9128. ...baseDom,
  9129. tag: 'button',
  9130. classes: [
  9131. ...baseDom.classes,
  9132. 'tox-swatches__picker-btn'
  9133. ],
  9134. innerHtml: icon
  9135. };
  9136. } else if (itemValue === removeColorCommand) {
  9137. return {
  9138. ...baseDom,
  9139. classes: [
  9140. ...baseDom.classes,
  9141. 'tox-swatch--remove'
  9142. ],
  9143. innerHtml: icon
  9144. };
  9145. } else {
  9146. return {
  9147. ...baseDom,
  9148. attributes: {
  9149. ...baseDom.attributes,
  9150. 'data-mce-color': itemValue
  9151. },
  9152. styles: { 'background-color': itemValue }
  9153. };
  9154. }
  9155. };
  9156. return {
  9157. dom: getDom(),
  9158. optComponents: []
  9159. };
  9160. };
  9161. const renderItemDomStructure = ariaLabel => {
  9162. const domTitle = ariaLabel.map(label => ({ attributes: { title: global$8.translate(label) } })).getOr({});
  9163. return {
  9164. tag: 'div',
  9165. classes: [
  9166. navClass,
  9167. selectableClass
  9168. ],
  9169. ...domTitle
  9170. };
  9171. };
  9172. const renderNormalItemStructure = (info, providersBackstage, renderIcons, fallbackIcon) => {
  9173. const iconSpec = {
  9174. tag: 'div',
  9175. classes: [iconClass]
  9176. };
  9177. const renderIcon = iconName => render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
  9178. const renderEmptyIcon = () => Optional.some({ dom: iconSpec });
  9179. const leftIcon = renderIcons ? info.iconContent.map(renderIcon).orThunk(renderEmptyIcon) : Optional.none();
  9180. const checkmark = info.checkMark;
  9181. const textRender = Optional.from(info.meta).fold(() => renderText, meta => has$2(meta, 'style') ? curry(renderStyledText, meta.style) : renderText);
  9182. const content = info.htmlContent.fold(() => info.textContent.map(textRender), html => Optional.some(renderHtml(html, [textClass])));
  9183. const menuItem = {
  9184. dom: renderItemDomStructure(info.ariaLabel),
  9185. optComponents: [
  9186. leftIcon,
  9187. content,
  9188. info.shortcutContent.map(renderShortcut),
  9189. checkmark,
  9190. info.caret
  9191. ]
  9192. };
  9193. return menuItem;
  9194. };
  9195. const renderItemStructure = (info, providersBackstage, renderIcons, fallbackIcon = Optional.none()) => {
  9196. if (info.presets === 'color') {
  9197. return renderColorStructure(info, providersBackstage, fallbackIcon);
  9198. } else {
  9199. return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
  9200. }
  9201. };
  9202. const tooltipBehaviour = (meta, sharedBackstage) => get$g(meta, 'tooltipWorker').map(tooltipWorker => [Tooltipping.config({
  9203. lazySink: sharedBackstage.getSink,
  9204. tooltipDom: {
  9205. tag: 'div',
  9206. classes: ['tox-tooltip-worker-container']
  9207. },
  9208. tooltipComponents: [],
  9209. anchor: comp => ({
  9210. type: 'submenu',
  9211. item: comp,
  9212. overrides: { maxHeightFunction: expandable$1 }
  9213. }),
  9214. mode: 'follow-highlight',
  9215. onShow: (component, _tooltip) => {
  9216. tooltipWorker(elm => {
  9217. Tooltipping.setComponents(component, [external$1({ element: SugarElement.fromDom(elm) })]);
  9218. });
  9219. }
  9220. })]).getOr([]);
  9221. const encodeText = text => global$7.DOM.encode(text);
  9222. const replaceText = (text, matchText) => {
  9223. const translated = global$8.translate(text);
  9224. const encoded = encodeText(translated);
  9225. if (matchText.length > 0) {
  9226. const escapedMatchRegex = new RegExp(escape(matchText), 'gi');
  9227. return encoded.replace(escapedMatchRegex, match => `<span class="tox-autocompleter-highlight">${ match }</span>`);
  9228. } else {
  9229. return encoded;
  9230. }
  9231. };
  9232. const renderAutocompleteItem = (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons = true) => {
  9233. const structure = renderItemStructure({
  9234. presets,
  9235. textContent: Optional.none(),
  9236. htmlContent: useText ? spec.text.map(text => replaceText(text, matchText)) : Optional.none(),
  9237. ariaLabel: spec.text,
  9238. iconContent: spec.icon,
  9239. shortcutContent: Optional.none(),
  9240. checkMark: Optional.none(),
  9241. caret: Optional.none(),
  9242. value: spec.value
  9243. }, sharedBackstage.providers, renderIcons, spec.icon);
  9244. return renderCommonItem({
  9245. data: buildData(spec),
  9246. enabled: spec.enabled,
  9247. getApi: constant$1({}),
  9248. onAction: _api => onItemValueHandler(spec.value, spec.meta),
  9249. onSetup: constant$1(noop),
  9250. triggersSubmenu: false,
  9251. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  9252. }, structure, itemResponse, sharedBackstage.providers);
  9253. };
  9254. const render$2 = (items, extras) => map$2(items, item => {
  9255. switch (item.type) {
  9256. case 'cardcontainer':
  9257. return renderContainer(item, render$2(item.items, extras));
  9258. case 'cardimage':
  9259. return renderImage(item.src, item.classes, item.alt);
  9260. case 'cardtext':
  9261. const shouldHighlight = item.name.exists(name => contains$2(extras.cardText.highlightOn, name));
  9262. const matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr('') : '';
  9263. return renderHtml(replaceText(item.text, matchText), item.classes);
  9264. }
  9265. });
  9266. const renderCardMenuItem = (spec, itemResponse, sharedBackstage, extras) => {
  9267. const getApi = component => ({
  9268. isEnabled: () => !Disabling.isDisabled(component),
  9269. setEnabled: state => {
  9270. Disabling.set(component, !state);
  9271. each$1(descendants(component.element, '*'), elm => {
  9272. component.getSystem().getByDom(elm).each(comp => {
  9273. if (comp.hasConfigured(Disabling)) {
  9274. Disabling.set(comp, !state);
  9275. }
  9276. });
  9277. });
  9278. }
  9279. });
  9280. const structure = {
  9281. dom: renderItemDomStructure(spec.label),
  9282. optComponents: [Optional.some({
  9283. dom: {
  9284. tag: 'div',
  9285. classes: [
  9286. containerClass,
  9287. containerRowClass
  9288. ]
  9289. },
  9290. components: render$2(spec.items, extras)
  9291. })]
  9292. };
  9293. return renderCommonItem({
  9294. data: buildData({
  9295. text: Optional.none(),
  9296. ...spec
  9297. }),
  9298. enabled: spec.enabled,
  9299. getApi,
  9300. onAction: spec.onAction,
  9301. onSetup: spec.onSetup,
  9302. triggersSubmenu: false,
  9303. itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
  9304. }, structure, itemResponse, sharedBackstage.providers);
  9305. };
  9306. const renderChoiceItem = (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons = true) => {
  9307. const getApi = component => ({
  9308. setActive: state => {
  9309. Toggling.set(component, state);
  9310. },
  9311. isActive: () => Toggling.isOn(component),
  9312. isEnabled: () => !Disabling.isDisabled(component),
  9313. setEnabled: state => Disabling.set(component, !state)
  9314. });
  9315. const structure = renderItemStructure({
  9316. presets,
  9317. textContent: useText ? spec.text : Optional.none(),
  9318. htmlContent: Optional.none(),
  9319. ariaLabel: spec.text,
  9320. iconContent: spec.icon,
  9321. shortcutContent: useText ? spec.shortcut : Optional.none(),
  9322. checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
  9323. caret: Optional.none(),
  9324. value: spec.value
  9325. }, providersBackstage, renderIcons);
  9326. return deepMerge(renderCommonItem({
  9327. data: buildData(spec),
  9328. enabled: spec.enabled,
  9329. getApi,
  9330. onAction: _api => onItemValueHandler(spec.value),
  9331. onSetup: api => {
  9332. api.setActive(isSelected);
  9333. return noop;
  9334. },
  9335. triggersSubmenu: false,
  9336. itemBehaviours: []
  9337. }, structure, itemResponse, providersBackstage), {
  9338. toggling: {
  9339. toggleClass: tickedClass,
  9340. toggleOnExecute: false,
  9341. selected: spec.active
  9342. }
  9343. });
  9344. };
  9345. const parts$f = generate$3(owner$2(), parts$h());
  9346. const hexColour = value => ({ value });
  9347. const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  9348. const longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  9349. const isHexString = hex => shorthandRegex.test(hex) || longformRegex.test(hex);
  9350. const normalizeHex = hex => removeLeading(hex, '#').toUpperCase();
  9351. const fromString$1 = hex => isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  9352. const getLongForm = hex => {
  9353. const hexString = hex.value.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
  9354. return { value: hexString };
  9355. };
  9356. const extractValues = hex => {
  9357. const longForm = getLongForm(hex);
  9358. const splitForm = longformRegex.exec(longForm.value);
  9359. return splitForm === null ? [
  9360. 'FFFFFF',
  9361. 'FF',
  9362. 'FF',
  9363. 'FF'
  9364. ] : splitForm;
  9365. };
  9366. const toHex = component => {
  9367. const hex = component.toString(16);
  9368. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  9369. };
  9370. const fromRgba = rgbaColour => {
  9371. const value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  9372. return hexColour(value);
  9373. };
  9374. const min = Math.min;
  9375. const max = Math.max;
  9376. const round$1 = Math.round;
  9377. const rgbRegex = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/i;
  9378. const rgbaRegex = /^\s*rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?(?:\.\d+)?)\s*\)\s*$/i;
  9379. const rgbaColour = (red, green, blue, alpha) => ({
  9380. red,
  9381. green,
  9382. blue,
  9383. alpha
  9384. });
  9385. const isRgbaComponent = value => {
  9386. const num = parseInt(value, 10);
  9387. return num.toString() === value && num >= 0 && num <= 255;
  9388. };
  9389. const fromHsv = hsv => {
  9390. let r;
  9391. let g;
  9392. let b;
  9393. const hue = (hsv.hue || 0) % 360;
  9394. let saturation = hsv.saturation / 100;
  9395. let brightness = hsv.value / 100;
  9396. saturation = max(0, min(saturation, 1));
  9397. brightness = max(0, min(brightness, 1));
  9398. if (saturation === 0) {
  9399. r = g = b = round$1(255 * brightness);
  9400. return rgbaColour(r, g, b, 1);
  9401. }
  9402. const side = hue / 60;
  9403. const chroma = brightness * saturation;
  9404. const x = chroma * (1 - Math.abs(side % 2 - 1));
  9405. const match = brightness - chroma;
  9406. switch (Math.floor(side)) {
  9407. case 0:
  9408. r = chroma;
  9409. g = x;
  9410. b = 0;
  9411. break;
  9412. case 1:
  9413. r = x;
  9414. g = chroma;
  9415. b = 0;
  9416. break;
  9417. case 2:
  9418. r = 0;
  9419. g = chroma;
  9420. b = x;
  9421. break;
  9422. case 3:
  9423. r = 0;
  9424. g = x;
  9425. b = chroma;
  9426. break;
  9427. case 4:
  9428. r = x;
  9429. g = 0;
  9430. b = chroma;
  9431. break;
  9432. case 5:
  9433. r = chroma;
  9434. g = 0;
  9435. b = x;
  9436. break;
  9437. default:
  9438. r = g = b = 0;
  9439. }
  9440. r = round$1(255 * (r + match));
  9441. g = round$1(255 * (g + match));
  9442. b = round$1(255 * (b + match));
  9443. return rgbaColour(r, g, b, 1);
  9444. };
  9445. const fromHex = hexColour => {
  9446. const result = extractValues(hexColour);
  9447. const red = parseInt(result[1], 16);
  9448. const green = parseInt(result[2], 16);
  9449. const blue = parseInt(result[3], 16);
  9450. return rgbaColour(red, green, blue, 1);
  9451. };
  9452. const fromStringValues = (red, green, blue, alpha) => {
  9453. const r = parseInt(red, 10);
  9454. const g = parseInt(green, 10);
  9455. const b = parseInt(blue, 10);
  9456. const a = parseFloat(alpha);
  9457. return rgbaColour(r, g, b, a);
  9458. };
  9459. const fromString = rgbaString => {
  9460. if (rgbaString === 'transparent') {
  9461. return Optional.some(rgbaColour(0, 0, 0, 0));
  9462. }
  9463. const rgbMatch = rgbRegex.exec(rgbaString);
  9464. if (rgbMatch !== null) {
  9465. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  9466. }
  9467. const rgbaMatch = rgbaRegex.exec(rgbaString);
  9468. if (rgbaMatch !== null) {
  9469. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  9470. }
  9471. return Optional.none();
  9472. };
  9473. const toString = rgba => `rgba(${ rgba.red },${ rgba.green },${ rgba.blue },${ rgba.alpha })`;
  9474. const red = rgbaColour(255, 0, 0, 1);
  9475. const fireSkinLoaded$1 = editor => editor.dispatch('SkinLoaded');
  9476. const fireSkinLoadError$1 = (editor, error) => editor.dispatch('SkinLoadError', error);
  9477. const fireResizeEditor = editor => editor.dispatch('ResizeEditor');
  9478. const fireResizeContent = (editor, e) => editor.dispatch('ResizeContent', e);
  9479. const fireScrollContent = (editor, e) => editor.dispatch('ScrollContent', e);
  9480. const fireTextColorChange = (editor, data) => editor.dispatch('TextColorChange', data);
  9481. const hsvColour = (hue, saturation, value) => ({
  9482. hue,
  9483. saturation,
  9484. value
  9485. });
  9486. const fromRgb = rgbaColour => {
  9487. let h = 0;
  9488. let s = 0;
  9489. let v = 0;
  9490. const r = rgbaColour.red / 255;
  9491. const g = rgbaColour.green / 255;
  9492. const b = rgbaColour.blue / 255;
  9493. const minRGB = Math.min(r, Math.min(g, b));
  9494. const maxRGB = Math.max(r, Math.max(g, b));
  9495. if (minRGB === maxRGB) {
  9496. v = minRGB;
  9497. return hsvColour(0, 0, v * 100);
  9498. }
  9499. const d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  9500. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  9501. h = 60 * (h - d / (maxRGB - minRGB));
  9502. s = (maxRGB - minRGB) / maxRGB;
  9503. v = maxRGB;
  9504. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  9505. };
  9506. const hexToHsv = hex => fromRgb(fromHex(hex));
  9507. const hsvToHex = hsv => fromRgba(fromHsv(hsv));
  9508. const anyToHex = color => fromString$1(color).orThunk(() => fromString(color).map(fromRgba)).getOrThunk(() => {
  9509. const canvas = document.createElement('canvas');
  9510. canvas.height = 1;
  9511. canvas.width = 1;
  9512. const canvasContext = canvas.getContext('2d');
  9513. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  9514. canvasContext.fillStyle = '#FFFFFF';
  9515. canvasContext.fillStyle = color;
  9516. canvasContext.fillRect(0, 0, 1, 1);
  9517. const rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  9518. const r = rgba[0];
  9519. const g = rgba[1];
  9520. const b = rgba[2];
  9521. const a = rgba[3];
  9522. return fromRgba(rgbaColour(r, g, b, a));
  9523. });
  9524. var global$4 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  9525. const storageName = 'tinymce-custom-colors';
  9526. var ColorCache = (max = 10) => {
  9527. const storageString = global$4.getItem(storageName);
  9528. const localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  9529. const prune = list => {
  9530. const diff = max - list.length;
  9531. return diff < 0 ? list.slice(0, max) : list;
  9532. };
  9533. const cache = prune(localstorage);
  9534. const add = key => {
  9535. indexOf(cache, key).each(remove);
  9536. cache.unshift(key);
  9537. if (cache.length > max) {
  9538. cache.pop();
  9539. }
  9540. global$4.setItem(storageName, JSON.stringify(cache));
  9541. };
  9542. const remove = idx => {
  9543. cache.splice(idx, 1);
  9544. };
  9545. const state = () => cache.slice(0);
  9546. return {
  9547. add,
  9548. state
  9549. };
  9550. };
  9551. const colorCache = ColorCache(10);
  9552. const calcCols = colors => Math.max(5, Math.ceil(Math.sqrt(colors)));
  9553. const mapColors = colorMap => {
  9554. const colors = [];
  9555. for (let i = 0; i < colorMap.length; i += 2) {
  9556. colors.push({
  9557. text: colorMap[i + 1],
  9558. value: '#' + anyToHex(colorMap[i]).value,
  9559. type: 'choiceitem'
  9560. });
  9561. }
  9562. return colors;
  9563. };
  9564. const option$1 = name => editor => editor.options.get(name);
  9565. const register$d = editor => {
  9566. const registerOption = editor.options.register;
  9567. registerOption('color_map', {
  9568. processor: value => {
  9569. if (isArrayOf(value, isString)) {
  9570. return {
  9571. value: mapColors(value),
  9572. valid: true
  9573. };
  9574. } else {
  9575. return {
  9576. valid: false,
  9577. message: 'Must be an array of strings.'
  9578. };
  9579. }
  9580. },
  9581. default: [
  9582. '#BFEDD2',
  9583. 'Light Green',
  9584. '#FBEEB8',
  9585. 'Light Yellow',
  9586. '#F8CAC6',
  9587. 'Light Red',
  9588. '#ECCAFA',
  9589. 'Light Purple',
  9590. '#C2E0F4',
  9591. 'Light Blue',
  9592. '#2DC26B',
  9593. 'Green',
  9594. '#F1C40F',
  9595. 'Yellow',
  9596. '#E03E2D',
  9597. 'Red',
  9598. '#B96AD9',
  9599. 'Purple',
  9600. '#3598DB',
  9601. 'Blue',
  9602. '#169179',
  9603. 'Dark Turquoise',
  9604. '#E67E23',
  9605. 'Orange',
  9606. '#BA372A',
  9607. 'Dark Red',
  9608. '#843FA1',
  9609. 'Dark Purple',
  9610. '#236FA1',
  9611. 'Dark Blue',
  9612. '#ECF0F1',
  9613. 'Light Gray',
  9614. '#CED4D9',
  9615. 'Medium Gray',
  9616. '#95A5A6',
  9617. 'Gray',
  9618. '#7E8C8D',
  9619. 'Dark Gray',
  9620. '#34495E',
  9621. 'Navy Blue',
  9622. '#000000',
  9623. 'Black',
  9624. '#ffffff',
  9625. 'White'
  9626. ]
  9627. });
  9628. registerOption('color_cols', {
  9629. processor: 'number',
  9630. default: calcCols(getColors$2(editor).length)
  9631. });
  9632. registerOption('custom_colors', {
  9633. processor: 'boolean',
  9634. default: true
  9635. });
  9636. };
  9637. const getColorCols$1 = option$1('color_cols');
  9638. const hasCustomColors$1 = option$1('custom_colors');
  9639. const getColors$2 = option$1('color_map');
  9640. const getCurrentColors = () => map$2(colorCache.state(), color => ({
  9641. type: 'choiceitem',
  9642. text: color,
  9643. value: color
  9644. }));
  9645. const addColor = color => {
  9646. colorCache.add(color);
  9647. };
  9648. const fallbackColor = '#000000';
  9649. const getCurrentColor = (editor, format) => {
  9650. let color;
  9651. editor.dom.getParents(editor.selection.getStart(), elm => {
  9652. let value;
  9653. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  9654. color = color ? color : value;
  9655. }
  9656. });
  9657. return Optional.from(color);
  9658. };
  9659. const applyFormat = (editor, format, value) => {
  9660. editor.undoManager.transact(() => {
  9661. editor.focus();
  9662. editor.formatter.apply(format, { value });
  9663. editor.nodeChanged();
  9664. });
  9665. };
  9666. const removeFormat = (editor, format) => {
  9667. editor.undoManager.transact(() => {
  9668. editor.focus();
  9669. editor.formatter.remove(format, { value: null }, null, true);
  9670. editor.nodeChanged();
  9671. });
  9672. };
  9673. const registerCommands = editor => {
  9674. editor.addCommand('mceApplyTextcolor', (format, value) => {
  9675. applyFormat(editor, format, value);
  9676. });
  9677. editor.addCommand('mceRemoveTextcolor', format => {
  9678. removeFormat(editor, format);
  9679. });
  9680. };
  9681. const getAdditionalColors = hasCustom => {
  9682. const type = 'choiceitem';
  9683. const remove = {
  9684. type,
  9685. text: 'Remove color',
  9686. icon: 'color-swatch-remove-color',
  9687. value: 'remove'
  9688. };
  9689. const custom = {
  9690. type,
  9691. text: 'Custom color',
  9692. icon: 'color-picker',
  9693. value: 'custom'
  9694. };
  9695. return hasCustom ? [
  9696. remove,
  9697. custom
  9698. ] : [remove];
  9699. };
  9700. const applyColor = (editor, format, value, onChoice) => {
  9701. if (value === 'custom') {
  9702. const dialog = colorPickerDialog(editor);
  9703. dialog(colorOpt => {
  9704. colorOpt.each(color => {
  9705. addColor(color);
  9706. editor.execCommand('mceApplyTextcolor', format, color);
  9707. onChoice(color);
  9708. });
  9709. }, fallbackColor);
  9710. } else if (value === 'remove') {
  9711. onChoice('');
  9712. editor.execCommand('mceRemoveTextcolor', format);
  9713. } else {
  9714. onChoice(value);
  9715. editor.execCommand('mceApplyTextcolor', format, value);
  9716. }
  9717. };
  9718. const getColors$1 = (colors, hasCustom) => colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  9719. const getFetch$1 = (colors, hasCustom) => callback => {
  9720. callback(getColors$1(colors, hasCustom));
  9721. };
  9722. const setIconColor = (splitButtonApi, name, newColor) => {
  9723. const id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  9724. splitButtonApi.setIconFill(id, newColor);
  9725. };
  9726. const registerTextColorButton = (editor, name, format, tooltip, lastColor) => {
  9727. editor.ui.registry.addSplitButton(name, {
  9728. tooltip,
  9729. presets: 'color',
  9730. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  9731. select: value => {
  9732. const optCurrentRgb = getCurrentColor(editor, format);
  9733. return optCurrentRgb.bind(currentRgb => fromString(currentRgb).map(rgba => {
  9734. const currentHex = fromRgba(rgba).value;
  9735. return contains$1(value.toLowerCase(), currentHex);
  9736. })).getOr(false);
  9737. },
  9738. columns: getColorCols$1(editor),
  9739. fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
  9740. onAction: _splitButtonApi => {
  9741. applyColor(editor, format, lastColor.get(), noop);
  9742. },
  9743. onItemAction: (_splitButtonApi, value) => {
  9744. applyColor(editor, format, value, newColor => {
  9745. lastColor.set(newColor);
  9746. fireTextColorChange(editor, {
  9747. name,
  9748. color: newColor
  9749. });
  9750. });
  9751. },
  9752. onSetup: splitButtonApi => {
  9753. setIconColor(splitButtonApi, name, lastColor.get());
  9754. const handler = e => {
  9755. if (e.name === name) {
  9756. setIconColor(splitButtonApi, e.name, e.color);
  9757. }
  9758. };
  9759. editor.on('TextColorChange', handler);
  9760. return () => {
  9761. editor.off('TextColorChange', handler);
  9762. };
  9763. }
  9764. });
  9765. };
  9766. const registerTextColorMenuItem = (editor, name, format, text) => {
  9767. editor.ui.registry.addNestedMenuItem(name, {
  9768. text,
  9769. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  9770. getSubmenuItems: () => [{
  9771. type: 'fancymenuitem',
  9772. fancytype: 'colorswatch',
  9773. onAction: data => {
  9774. applyColor(editor, format, data.value, noop);
  9775. }
  9776. }]
  9777. });
  9778. };
  9779. const colorPickerDialog = editor => (callback, value) => {
  9780. let isValid = false;
  9781. const onSubmit = api => {
  9782. const data = api.getData();
  9783. const hex = data.colorpicker;
  9784. if (isValid) {
  9785. callback(Optional.from(hex));
  9786. api.close();
  9787. } else {
  9788. editor.windowManager.alert(editor.translate([
  9789. 'Invalid hex color code: {0}',
  9790. hex
  9791. ]));
  9792. }
  9793. };
  9794. const onAction = (_api, details) => {
  9795. if (details.name === 'hex-valid') {
  9796. isValid = details.value;
  9797. }
  9798. };
  9799. const initialData = { colorpicker: value };
  9800. editor.windowManager.open({
  9801. title: 'Color Picker',
  9802. size: 'normal',
  9803. body: {
  9804. type: 'panel',
  9805. items: [{
  9806. type: 'colorpicker',
  9807. name: 'colorpicker',
  9808. label: 'Color'
  9809. }]
  9810. },
  9811. buttons: [
  9812. {
  9813. type: 'cancel',
  9814. name: 'cancel',
  9815. text: 'Cancel'
  9816. },
  9817. {
  9818. type: 'submit',
  9819. name: 'save',
  9820. text: 'Save',
  9821. primary: true
  9822. }
  9823. ],
  9824. initialData,
  9825. onAction,
  9826. onSubmit,
  9827. onClose: noop,
  9828. onCancel: () => {
  9829. callback(Optional.none());
  9830. }
  9831. });
  9832. };
  9833. const register$c = editor => {
  9834. registerCommands(editor);
  9835. const lastForeColor = Cell(fallbackColor);
  9836. const lastBackColor = Cell(fallbackColor);
  9837. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  9838. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  9839. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  9840. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  9841. };
  9842. const createPartialChoiceMenu = (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) => {
  9843. const hasIcons = menuHasIcons(items);
  9844. const presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  9845. const alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  9846. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  9847. };
  9848. const createChoiceItems = (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) => cat(map$2(items, item => {
  9849. if (item.type === 'choiceitem') {
  9850. return createChoiceMenuItem(item).fold(handleError, d => Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items))));
  9851. } else {
  9852. return Optional.none();
  9853. }
  9854. }));
  9855. const deriveMenuMovement = (columns, presets) => {
  9856. const menuMarkers = markers(presets);
  9857. if (columns === 1) {
  9858. return {
  9859. mode: 'menu',
  9860. moveOnTab: true
  9861. };
  9862. } else if (columns === 'auto') {
  9863. return {
  9864. mode: 'grid',
  9865. selector: '.' + menuMarkers.item,
  9866. initSize: {
  9867. numColumns: 1,
  9868. numRows: 1
  9869. }
  9870. };
  9871. } else {
  9872. const rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  9873. return {
  9874. mode: 'matrix',
  9875. rowSelector: '.' + rowClass
  9876. };
  9877. }
  9878. };
  9879. const deriveCollectionMovement = (columns, presets) => {
  9880. if (columns === 1) {
  9881. return {
  9882. mode: 'menu',
  9883. moveOnTab: false,
  9884. selector: '.tox-collection__item'
  9885. };
  9886. } else if (columns === 'auto') {
  9887. return {
  9888. mode: 'flatgrid',
  9889. selector: '.' + 'tox-collection__item',
  9890. initSize: {
  9891. numColumns: 1,
  9892. numRows: 1
  9893. }
  9894. };
  9895. } else {
  9896. return {
  9897. mode: 'matrix',
  9898. selectors: {
  9899. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  9900. cell: presets === 'color' ? `.${ colorClass }` : `.${ selectableClass }`
  9901. }
  9902. };
  9903. }
  9904. };
  9905. const renderColorSwatchItem = (spec, backstage) => {
  9906. const items = getColorItems(spec, backstage);
  9907. const columns = backstage.colorinput.getColorCols();
  9908. const presets = 'color';
  9909. const menuSpec = createPartialChoiceMenu(generate$6('menu-value'), items, value => {
  9910. spec.onAction({ value });
  9911. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
  9912. const widgetSpec = {
  9913. ...menuSpec,
  9914. markers: markers(presets),
  9915. movement: deriveMenuMovement(columns, presets)
  9916. };
  9917. return {
  9918. type: 'widget',
  9919. data: { value: generate$6('widget-id') },
  9920. dom: {
  9921. tag: 'div',
  9922. classes: ['tox-fancymenuitem']
  9923. },
  9924. autofocus: true,
  9925. components: [parts$f.widget(Menu.sketch(widgetSpec))]
  9926. };
  9927. };
  9928. const getColorItems = (spec, backstage) => {
  9929. const useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
  9930. return spec.initData.colors.fold(() => getColors$1(backstage.colorinput.getColors(), useCustomColors), colors => colors.concat(getAdditionalColors(useCustomColors)));
  9931. };
  9932. const cellOverEvent = generate$6('cell-over');
  9933. const cellExecuteEvent = generate$6('cell-execute');
  9934. const makeCell = (row, col, labelId) => {
  9935. const emitCellOver = c => emitWith(c, cellOverEvent, {
  9936. row,
  9937. col
  9938. });
  9939. const emitExecute = c => emitWith(c, cellExecuteEvent, {
  9940. row,
  9941. col
  9942. });
  9943. const onClick = (c, se) => {
  9944. se.stop();
  9945. emitExecute(c);
  9946. };
  9947. return build$1({
  9948. dom: {
  9949. tag: 'div',
  9950. attributes: {
  9951. role: 'button',
  9952. ['aria-labelledby']: labelId
  9953. }
  9954. },
  9955. behaviours: derive$1([
  9956. config('insert-table-picker-cell', [
  9957. run$1(mouseover(), Focusing.focus),
  9958. run$1(execute$5(), emitExecute),
  9959. run$1(click(), onClick),
  9960. run$1(tap(), onClick)
  9961. ]),
  9962. Toggling.config({
  9963. toggleClass: 'tox-insert-table-picker__selected',
  9964. toggleOnExecute: false
  9965. }),
  9966. Focusing.config({ onFocus: emitCellOver })
  9967. ])
  9968. });
  9969. };
  9970. const makeCells = (labelId, numRows, numCols) => {
  9971. const cells = [];
  9972. for (let i = 0; i < numRows; i++) {
  9973. const row = [];
  9974. for (let j = 0; j < numCols; j++) {
  9975. row.push(makeCell(i, j, labelId));
  9976. }
  9977. cells.push(row);
  9978. }
  9979. return cells;
  9980. };
  9981. const selectCells = (cells, selectedRow, selectedColumn, numRows, numColumns) => {
  9982. for (let i = 0; i < numRows; i++) {
  9983. for (let j = 0; j < numColumns; j++) {
  9984. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  9985. }
  9986. }
  9987. };
  9988. const makeComponents = cells => bind$3(cells, cellRow => map$2(cellRow, premade));
  9989. const makeLabelText = (row, col) => text$1(`${ col }x${ row }`);
  9990. const renderInsertTableMenuItem = spec => {
  9991. const numRows = 10;
  9992. const numColumns = 10;
  9993. const sizeLabelId = generate$6('size-label');
  9994. const cells = makeCells(sizeLabelId, numRows, numColumns);
  9995. const emptyLabelText = makeLabelText(0, 0);
  9996. const memLabel = record({
  9997. dom: {
  9998. tag: 'span',
  9999. classes: ['tox-insert-table-picker__label'],
  10000. attributes: { id: sizeLabelId }
  10001. },
  10002. components: [emptyLabelText],
  10003. behaviours: derive$1([Replacing.config({})])
  10004. });
  10005. return {
  10006. type: 'widget',
  10007. data: { value: generate$6('widget-id') },
  10008. dom: {
  10009. tag: 'div',
  10010. classes: ['tox-fancymenuitem']
  10011. },
  10012. autofocus: true,
  10013. components: [parts$f.widget({
  10014. dom: {
  10015. tag: 'div',
  10016. classes: ['tox-insert-table-picker']
  10017. },
  10018. components: makeComponents(cells).concat(memLabel.asSpec()),
  10019. behaviours: derive$1([
  10020. config('insert-table-picker', [
  10021. runOnAttached(c => {
  10022. Replacing.set(memLabel.get(c), [emptyLabelText]);
  10023. }),
  10024. runWithTarget(cellOverEvent, (c, t, e) => {
  10025. const {row, col} = e.event;
  10026. selectCells(cells, row, col, numRows, numColumns);
  10027. Replacing.set(memLabel.get(c), [makeLabelText(row + 1, col + 1)]);
  10028. }),
  10029. runWithTarget(cellExecuteEvent, (c, _, e) => {
  10030. const {row, col} = e.event;
  10031. spec.onAction({
  10032. numRows: row + 1,
  10033. numColumns: col + 1
  10034. });
  10035. emit(c, sandboxClose());
  10036. })
  10037. ]),
  10038. Keying.config({
  10039. initSize: {
  10040. numRows,
  10041. numColumns
  10042. },
  10043. mode: 'flatgrid',
  10044. selector: '[role="button"]'
  10045. })
  10046. ])
  10047. })]
  10048. };
  10049. };
  10050. const fancyMenuItems = {
  10051. inserttable: renderInsertTableMenuItem,
  10052. colorswatch: renderColorSwatchItem
  10053. };
  10054. const renderFancyMenuItem = (spec, backstage) => get$g(fancyMenuItems, spec.fancytype).map(render => render(spec, backstage));
  10055. const renderNestedItem = (spec, itemResponse, providersBackstage, renderIcons = true, downwardsCaret = false) => {
  10056. const caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  10057. const getApi = component => ({
  10058. isEnabled: () => !Disabling.isDisabled(component),
  10059. setEnabled: state => Disabling.set(component, !state)
  10060. });
  10061. const structure = renderItemStructure({
  10062. presets: 'normal',
  10063. iconContent: spec.icon,
  10064. textContent: spec.text,
  10065. htmlContent: Optional.none(),
  10066. ariaLabel: spec.text,
  10067. caret: Optional.some(caret),
  10068. checkMark: Optional.none(),
  10069. shortcutContent: spec.shortcut
  10070. }, providersBackstage, renderIcons);
  10071. return renderCommonItem({
  10072. data: buildData(spec),
  10073. getApi,
  10074. enabled: spec.enabled,
  10075. onAction: noop,
  10076. onSetup: spec.onSetup,
  10077. triggersSubmenu: true,
  10078. itemBehaviours: []
  10079. }, structure, itemResponse, providersBackstage);
  10080. };
  10081. const renderNormalItem = (spec, itemResponse, providersBackstage, renderIcons = true) => {
  10082. const getApi = component => ({
  10083. isEnabled: () => !Disabling.isDisabled(component),
  10084. setEnabled: state => Disabling.set(component, !state)
  10085. });
  10086. const structure = renderItemStructure({
  10087. presets: 'normal',
  10088. iconContent: spec.icon,
  10089. textContent: spec.text,
  10090. htmlContent: Optional.none(),
  10091. ariaLabel: spec.text,
  10092. caret: Optional.none(),
  10093. checkMark: Optional.none(),
  10094. shortcutContent: spec.shortcut
  10095. }, providersBackstage, renderIcons);
  10096. return renderCommonItem({
  10097. data: buildData(spec),
  10098. getApi,
  10099. enabled: spec.enabled,
  10100. onAction: spec.onAction,
  10101. onSetup: spec.onSetup,
  10102. triggersSubmenu: false,
  10103. itemBehaviours: []
  10104. }, structure, itemResponse, providersBackstage);
  10105. };
  10106. const renderSeparatorItem = spec => ({
  10107. type: 'separator',
  10108. dom: {
  10109. tag: 'div',
  10110. classes: [
  10111. selectableClass,
  10112. groupHeadingClass
  10113. ]
  10114. },
  10115. components: spec.text.map(text$1).toArray()
  10116. });
  10117. const renderToggleMenuItem = (spec, itemResponse, providersBackstage, renderIcons = true) => {
  10118. const getApi = component => ({
  10119. setActive: state => {
  10120. Toggling.set(component, state);
  10121. },
  10122. isActive: () => Toggling.isOn(component),
  10123. isEnabled: () => !Disabling.isDisabled(component),
  10124. setEnabled: state => Disabling.set(component, !state)
  10125. });
  10126. const structure = renderItemStructure({
  10127. iconContent: spec.icon,
  10128. textContent: spec.text,
  10129. htmlContent: Optional.none(),
  10130. ariaLabel: spec.text,
  10131. checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
  10132. caret: Optional.none(),
  10133. shortcutContent: spec.shortcut,
  10134. presets: 'normal',
  10135. meta: spec.meta
  10136. }, providersBackstage, renderIcons);
  10137. return deepMerge(renderCommonItem({
  10138. data: buildData(spec),
  10139. enabled: spec.enabled,
  10140. getApi,
  10141. onAction: spec.onAction,
  10142. onSetup: spec.onSetup,
  10143. triggersSubmenu: false,
  10144. itemBehaviours: []
  10145. }, structure, itemResponse, providersBackstage), {
  10146. toggling: {
  10147. toggleClass: tickedClass,
  10148. toggleOnExecute: false,
  10149. selected: spec.active
  10150. }
  10151. });
  10152. };
  10153. const autocomplete = renderAutocompleteItem;
  10154. const separator$3 = renderSeparatorItem;
  10155. const normal = renderNormalItem;
  10156. const nested = renderNestedItem;
  10157. const toggle$1 = renderToggleMenuItem;
  10158. const fancy = renderFancyMenuItem;
  10159. const card = renderCardMenuItem;
  10160. var FocusMode;
  10161. (function (FocusMode) {
  10162. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  10163. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  10164. }(FocusMode || (FocusMode = {})));
  10165. const createMenuItemFromBridge = (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) => {
  10166. const providersBackstage = backstage.shared.providers;
  10167. const parseForHorizontalMenu = menuitem => !isHorizontalMenu ? menuitem : {
  10168. ...menuitem,
  10169. shortcut: Optional.none(),
  10170. icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
  10171. };
  10172. switch (item.type) {
  10173. case 'menuitem':
  10174. return createMenuItem(item).fold(handleError, d => Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons)));
  10175. case 'nestedmenuitem':
  10176. return createNestedMenuItem(item).fold(handleError, d => Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu)));
  10177. case 'togglemenuitem':
  10178. return createToggleMenuItem(item).fold(handleError, d => Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons)));
  10179. case 'separator':
  10180. return createSeparatorMenuItem(item).fold(handleError, d => Optional.some(separator$3(d)));
  10181. case 'fancymenuitem':
  10182. return createFancyMenuItem(item).fold(handleError, d => fancy(parseForHorizontalMenu(d), backstage));
  10183. default: {
  10184. console.error('Unknown item in general menu', item);
  10185. return Optional.none();
  10186. }
  10187. }
  10188. };
  10189. const createAutocompleteItems = (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) => {
  10190. const renderText = columns === 1;
  10191. const renderIcons = !renderText || menuHasIcons(items);
  10192. return cat(map$2(items, item => {
  10193. switch (item.type) {
  10194. case 'separator':
  10195. return createSeparatorItem(item).fold(handleError, d => Optional.some(separator$3(d)));
  10196. case 'cardmenuitem':
  10197. return createCardMenuItem(item).fold(handleError, d => Optional.some(card({
  10198. ...d,
  10199. onAction: api => {
  10200. d.onAction(api);
  10201. onItemValueHandler(d.value, d.meta);
  10202. }
  10203. }, itemResponse, sharedBackstage, {
  10204. itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage),
  10205. cardText: {
  10206. matchText,
  10207. highlightOn
  10208. }
  10209. })));
  10210. case 'autocompleteitem':
  10211. default:
  10212. return createAutocompleterItem(item).fold(handleError, d => Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons)));
  10213. }
  10214. }));
  10215. };
  10216. const createPartialMenu = (value, items, itemResponse, backstage, isHorizontalMenu) => {
  10217. const hasIcons = menuHasIcons(items);
  10218. const alloyItems = cat(map$2(items, item => {
  10219. const itemHasIcon = i => isHorizontalMenu ? !has$2(i, 'text') : hasIcons;
  10220. const createItem = i => createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  10221. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  10222. return createItem({
  10223. ...item,
  10224. enabled: false
  10225. });
  10226. } else {
  10227. return createItem(item);
  10228. }
  10229. }));
  10230. const createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  10231. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  10232. };
  10233. const createTieredDataFrom = partialMenu => tieredMenu.singleData(partialMenu.value, partialMenu);
  10234. const createMenuFrom = (partialMenu, columns, focusMode, presets) => {
  10235. const focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
  10236. const movement = deriveMenuMovement(columns, presets);
  10237. const menuMarkers = markers(presets);
  10238. return {
  10239. dom: partialMenu.dom,
  10240. components: partialMenu.components,
  10241. items: partialMenu.items,
  10242. value: partialMenu.value,
  10243. markers: {
  10244. selectedItem: menuMarkers.selectedItem,
  10245. item: menuMarkers.item
  10246. },
  10247. movement,
  10248. fakeFocus: focusMode === FocusMode.ContentFocus,
  10249. focusManager,
  10250. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached((comp, _se) => {
  10251. detectSize(comp, 4, menuMarkers.item).each(({numColumns, numRows}) => {
  10252. Keying.setGridSize(comp, numRows, numColumns);
  10253. });
  10254. })])
  10255. };
  10256. };
  10257. const getAutocompleterRange = (dom, initRange) => {
  10258. return detect(SugarElement.fromDom(initRange.startContainer)).map(elm => {
  10259. const range = dom.createRng();
  10260. range.selectNode(elm.dom);
  10261. return range;
  10262. });
  10263. };
  10264. const register$b = (editor, sharedBackstage) => {
  10265. const processingAction = Cell(false);
  10266. const activeState = Cell(false);
  10267. const autocompleter = build$1(InlineView.sketch({
  10268. dom: {
  10269. tag: 'div',
  10270. classes: ['tox-autocompleter']
  10271. },
  10272. components: [],
  10273. fireDismissalEventInstead: {},
  10274. inlineBehaviours: derive$1([config('dismissAutocompleter', [run$1(dismissRequested(), () => cancelIfNecessary())])]),
  10275. lazySink: sharedBackstage.getSink
  10276. }));
  10277. const isMenuOpen = () => InlineView.isOpen(autocompleter);
  10278. const isActive = activeState.get;
  10279. const hideIfNecessary = () => {
  10280. if (isMenuOpen()) {
  10281. InlineView.hide(autocompleter);
  10282. }
  10283. };
  10284. const cancelIfNecessary = () => editor.execCommand('mceAutocompleterClose');
  10285. const getCombinedItems = matches => {
  10286. const columns = findMap(matches, m => Optional.from(m.columns)).getOr(1);
  10287. return bind$3(matches, match => {
  10288. const choices = match.items;
  10289. return createAutocompleteItems(choices, match.matchText, (itemValue, itemMeta) => {
  10290. const nr = editor.selection.getRng();
  10291. getAutocompleterRange(editor.dom, nr).each(range => {
  10292. const autocompleterApi = {
  10293. hide: () => cancelIfNecessary(),
  10294. reload: fetchOptions => {
  10295. hideIfNecessary();
  10296. editor.execCommand('mceAutocompleterReload', false, { fetchOptions });
  10297. }
  10298. };
  10299. processingAction.set(true);
  10300. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  10301. processingAction.set(false);
  10302. });
  10303. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn);
  10304. });
  10305. };
  10306. const display = (lookupData, items) => {
  10307. findIn(SugarElement.fromDom(editor.getBody())).each(element => {
  10308. const columns = findMap(lookupData, ld => Optional.from(ld.columns)).getOr(1);
  10309. InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')), {
  10310. anchor: {
  10311. type: 'node',
  10312. root: SugarElement.fromDom(editor.getBody()),
  10313. node: Optional.from(element)
  10314. }
  10315. });
  10316. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  10317. });
  10318. };
  10319. const updateDisplay = lookupData => {
  10320. const combinedItems = getCombinedItems(lookupData);
  10321. if (combinedItems.length > 0) {
  10322. display(lookupData, combinedItems);
  10323. } else {
  10324. hideIfNecessary();
  10325. }
  10326. };
  10327. editor.on('AutocompleterStart', ({lookupData}) => {
  10328. activeState.set(true);
  10329. processingAction.set(false);
  10330. updateDisplay(lookupData);
  10331. });
  10332. editor.on('AutocompleterUpdate', ({lookupData}) => updateDisplay(lookupData));
  10333. editor.on('AutocompleterEnd', () => {
  10334. hideIfNecessary();
  10335. activeState.set(false);
  10336. processingAction.set(false);
  10337. });
  10338. const autocompleterUiApi = {
  10339. cancelIfNecessary,
  10340. isMenuOpen,
  10341. isActive,
  10342. isProcessingAction: processingAction.get,
  10343. getView: () => InlineView.getContent(autocompleter)
  10344. };
  10345. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  10346. };
  10347. const Autocompleter = { register: register$b };
  10348. const closest = (scope, selector, isRoot) => closest$1(scope, selector, isRoot).isSome();
  10349. const DelayedFunction = (fun, delay) => {
  10350. let ref = null;
  10351. const schedule = (...args) => {
  10352. ref = setTimeout(() => {
  10353. fun.apply(null, args);
  10354. ref = null;
  10355. }, delay);
  10356. };
  10357. const cancel = () => {
  10358. if (ref !== null) {
  10359. clearTimeout(ref);
  10360. ref = null;
  10361. }
  10362. };
  10363. return {
  10364. cancel,
  10365. schedule
  10366. };
  10367. };
  10368. const SIGNIFICANT_MOVE = 5;
  10369. const LONGPRESS_DELAY = 400;
  10370. const getTouch = event => {
  10371. const raw = event.raw;
  10372. if (raw.touches === undefined || raw.touches.length !== 1) {
  10373. return Optional.none();
  10374. }
  10375. return Optional.some(raw.touches[0]);
  10376. };
  10377. const isFarEnough = (touch, data) => {
  10378. const distX = Math.abs(touch.clientX - data.x);
  10379. const distY = Math.abs(touch.clientY - data.y);
  10380. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  10381. };
  10382. const monitor = settings => {
  10383. const startData = value$2();
  10384. const longpressFired = Cell(false);
  10385. const longpress$1 = DelayedFunction(event => {
  10386. settings.triggerEvent(longpress(), event);
  10387. longpressFired.set(true);
  10388. }, LONGPRESS_DELAY);
  10389. const handleTouchstart = event => {
  10390. getTouch(event).each(touch => {
  10391. longpress$1.cancel();
  10392. const data = {
  10393. x: touch.clientX,
  10394. y: touch.clientY,
  10395. target: event.target
  10396. };
  10397. longpress$1.schedule(event);
  10398. longpressFired.set(false);
  10399. startData.set(data);
  10400. });
  10401. return Optional.none();
  10402. };
  10403. const handleTouchmove = event => {
  10404. longpress$1.cancel();
  10405. getTouch(event).each(touch => {
  10406. startData.on(data => {
  10407. if (isFarEnough(touch, data)) {
  10408. startData.clear();
  10409. }
  10410. });
  10411. });
  10412. return Optional.none();
  10413. };
  10414. const handleTouchend = event => {
  10415. longpress$1.cancel();
  10416. const isSame = data => eq(data.target, event.target);
  10417. return startData.get().filter(isSame).map(_data => {
  10418. if (longpressFired.get()) {
  10419. event.prevent();
  10420. return false;
  10421. } else {
  10422. return settings.triggerEvent(tap(), event);
  10423. }
  10424. });
  10425. };
  10426. const handlers = wrapAll([
  10427. {
  10428. key: touchstart(),
  10429. value: handleTouchstart
  10430. },
  10431. {
  10432. key: touchmove(),
  10433. value: handleTouchmove
  10434. },
  10435. {
  10436. key: touchend(),
  10437. value: handleTouchend
  10438. }
  10439. ]);
  10440. const fireIfReady = (event, type) => get$g(handlers, type).bind(handler => handler(event));
  10441. return { fireIfReady };
  10442. };
  10443. const isDangerous = event => {
  10444. const keyEv = event.raw;
  10445. return keyEv.which === BACKSPACE[0] && !contains$2([
  10446. 'input',
  10447. 'textarea'
  10448. ], name$3(event.target)) && !closest(event.target, '[contenteditable="true"]');
  10449. };
  10450. const setup$d = (container, rawSettings) => {
  10451. const settings = {
  10452. stopBackspace: true,
  10453. ...rawSettings
  10454. };
  10455. const pointerEvents = [
  10456. 'touchstart',
  10457. 'touchmove',
  10458. 'touchend',
  10459. 'touchcancel',
  10460. 'gesturestart',
  10461. 'mousedown',
  10462. 'mouseup',
  10463. 'mouseover',
  10464. 'mousemove',
  10465. 'mouseout',
  10466. 'click'
  10467. ];
  10468. const tapEvent = monitor(settings);
  10469. const simpleEvents = map$2(pointerEvents.concat([
  10470. 'selectstart',
  10471. 'input',
  10472. 'contextmenu',
  10473. 'change',
  10474. 'transitionend',
  10475. 'transitioncancel',
  10476. 'drag',
  10477. 'dragstart',
  10478. 'dragend',
  10479. 'dragenter',
  10480. 'dragleave',
  10481. 'dragover',
  10482. 'drop',
  10483. 'keyup'
  10484. ]), type => bind(container, type, event => {
  10485. tapEvent.fireIfReady(event, type).each(tapStopped => {
  10486. if (tapStopped) {
  10487. event.kill();
  10488. }
  10489. });
  10490. const stopped = settings.triggerEvent(type, event);
  10491. if (stopped) {
  10492. event.kill();
  10493. }
  10494. }));
  10495. const pasteTimeout = value$2();
  10496. const onPaste = bind(container, 'paste', event => {
  10497. tapEvent.fireIfReady(event, 'paste').each(tapStopped => {
  10498. if (tapStopped) {
  10499. event.kill();
  10500. }
  10501. });
  10502. const stopped = settings.triggerEvent('paste', event);
  10503. if (stopped) {
  10504. event.kill();
  10505. }
  10506. pasteTimeout.set(setTimeout(() => {
  10507. settings.triggerEvent(postPaste(), event);
  10508. }, 0));
  10509. });
  10510. const onKeydown = bind(container, 'keydown', event => {
  10511. const stopped = settings.triggerEvent('keydown', event);
  10512. if (stopped) {
  10513. event.kill();
  10514. } else if (settings.stopBackspace && isDangerous(event)) {
  10515. event.prevent();
  10516. }
  10517. });
  10518. const onFocusIn = bind(container, 'focusin', event => {
  10519. const stopped = settings.triggerEvent('focusin', event);
  10520. if (stopped) {
  10521. event.kill();
  10522. }
  10523. });
  10524. const focusoutTimeout = value$2();
  10525. const onFocusOut = bind(container, 'focusout', event => {
  10526. const stopped = settings.triggerEvent('focusout', event);
  10527. if (stopped) {
  10528. event.kill();
  10529. }
  10530. focusoutTimeout.set(setTimeout(() => {
  10531. settings.triggerEvent(postBlur(), event);
  10532. }, 0));
  10533. });
  10534. const unbind = () => {
  10535. each$1(simpleEvents, e => {
  10536. e.unbind();
  10537. });
  10538. onKeydown.unbind();
  10539. onFocusIn.unbind();
  10540. onFocusOut.unbind();
  10541. onPaste.unbind();
  10542. pasteTimeout.on(clearTimeout);
  10543. focusoutTimeout.on(clearTimeout);
  10544. };
  10545. return { unbind };
  10546. };
  10547. const derive = (rawEvent, rawTarget) => {
  10548. const source = get$g(rawEvent, 'target').getOr(rawTarget);
  10549. return Cell(source);
  10550. };
  10551. const fromSource = (event, source) => {
  10552. const stopper = Cell(false);
  10553. const cutter = Cell(false);
  10554. const stop = () => {
  10555. stopper.set(true);
  10556. };
  10557. const cut = () => {
  10558. cutter.set(true);
  10559. };
  10560. return {
  10561. stop,
  10562. cut,
  10563. isStopped: stopper.get,
  10564. isCut: cutter.get,
  10565. event,
  10566. setSource: source.set,
  10567. getSource: source.get
  10568. };
  10569. };
  10570. const fromExternal = event => {
  10571. const stopper = Cell(false);
  10572. const stop = () => {
  10573. stopper.set(true);
  10574. };
  10575. return {
  10576. stop,
  10577. cut: noop,
  10578. isStopped: stopper.get,
  10579. isCut: never,
  10580. event,
  10581. setSource: die('Cannot set source of a broadcasted event'),
  10582. getSource: die('Cannot get source of a broadcasted event')
  10583. };
  10584. };
  10585. const adt$1 = Adt.generate([
  10586. { stopped: [] },
  10587. { resume: ['element'] },
  10588. { complete: [] }
  10589. ]);
  10590. const doTriggerHandler = (lookup, eventType, rawEvent, target, source, logger) => {
  10591. const handler = lookup(eventType, target);
  10592. const simulatedEvent = fromSource(rawEvent, source);
  10593. return handler.fold(() => {
  10594. logger.logEventNoHandlers(eventType, target);
  10595. return adt$1.complete();
  10596. }, handlerInfo => {
  10597. const descHandler = handlerInfo.descHandler;
  10598. const eventHandler = getCurried(descHandler);
  10599. eventHandler(simulatedEvent);
  10600. if (simulatedEvent.isStopped()) {
  10601. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  10602. return adt$1.stopped();
  10603. } else if (simulatedEvent.isCut()) {
  10604. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  10605. return adt$1.complete();
  10606. } else {
  10607. return parent(handlerInfo.element).fold(() => {
  10608. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  10609. return adt$1.complete();
  10610. }, parent => {
  10611. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  10612. return adt$1.resume(parent);
  10613. });
  10614. }
  10615. });
  10616. };
  10617. const doTriggerOnUntilStopped = (lookup, eventType, rawEvent, rawTarget, source, logger) => doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, parent => doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger), never);
  10618. const triggerHandler = (lookup, eventType, rawEvent, target, logger) => {
  10619. const source = derive(rawEvent, target);
  10620. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  10621. };
  10622. const broadcast = (listeners, rawEvent, _logger) => {
  10623. const simulatedEvent = fromExternal(rawEvent);
  10624. each$1(listeners, listener => {
  10625. const descHandler = listener.descHandler;
  10626. const handler = getCurried(descHandler);
  10627. handler(simulatedEvent);
  10628. });
  10629. return simulatedEvent.isStopped();
  10630. };
  10631. const triggerUntilStopped = (lookup, eventType, rawEvent, logger) => triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  10632. const triggerOnUntilStopped = (lookup, eventType, rawEvent, rawTarget, logger) => {
  10633. const source = derive(rawEvent, rawTarget);
  10634. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  10635. };
  10636. const eventHandler = (element, descHandler) => ({
  10637. element,
  10638. descHandler
  10639. });
  10640. const broadcastHandler = (id, handler) => ({
  10641. id,
  10642. descHandler: handler
  10643. });
  10644. const EventRegistry = () => {
  10645. const registry = {};
  10646. const registerId = (extraArgs, id, events) => {
  10647. each(events, (v, k) => {
  10648. const handlers = registry[k] !== undefined ? registry[k] : {};
  10649. handlers[id] = curryArgs(v, extraArgs);
  10650. registry[k] = handlers;
  10651. });
  10652. };
  10653. const findHandler = (handlers, elem) => read$1(elem).bind(id => get$g(handlers, id)).map(descHandler => eventHandler(elem, descHandler));
  10654. const filterByType = type => get$g(registry, type).map(handlers => mapToArray(handlers, (f, id) => broadcastHandler(id, f))).getOr([]);
  10655. const find = (isAboveRoot, type, target) => get$g(registry, type).bind(handlers => closest$4(target, elem => findHandler(handlers, elem), isAboveRoot));
  10656. const unregisterId = id => {
  10657. each(registry, (handlersById, _eventName) => {
  10658. if (has$2(handlersById, id)) {
  10659. delete handlersById[id];
  10660. }
  10661. });
  10662. };
  10663. return {
  10664. registerId,
  10665. unregisterId,
  10666. filterByType,
  10667. find
  10668. };
  10669. };
  10670. const Registry = () => {
  10671. const events = EventRegistry();
  10672. const components = {};
  10673. const readOrTag = component => {
  10674. const elem = component.element;
  10675. return read$1(elem).getOrThunk(() => write('uid-', component.element));
  10676. };
  10677. const failOnDuplicate = (component, tagId) => {
  10678. const conflict = components[tagId];
  10679. if (conflict === component) {
  10680. unregister(component);
  10681. } else {
  10682. 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');
  10683. }
  10684. };
  10685. const register = component => {
  10686. const tagId = readOrTag(component);
  10687. if (hasNonNullableKey(components, tagId)) {
  10688. failOnDuplicate(component, tagId);
  10689. }
  10690. const extraArgs = [component];
  10691. events.registerId(extraArgs, tagId, component.events);
  10692. components[tagId] = component;
  10693. };
  10694. const unregister = component => {
  10695. read$1(component.element).each(tagId => {
  10696. delete components[tagId];
  10697. events.unregisterId(tagId);
  10698. });
  10699. };
  10700. const filter = type => events.filterByType(type);
  10701. const find = (isAboveRoot, type, target) => events.find(isAboveRoot, type, target);
  10702. const getById = id => get$g(components, id);
  10703. return {
  10704. find,
  10705. filter,
  10706. register,
  10707. unregister,
  10708. getById
  10709. };
  10710. };
  10711. const factory$j = detail => {
  10712. const {attributes, ...domWithoutAttributes} = detail.dom;
  10713. return {
  10714. uid: detail.uid,
  10715. dom: {
  10716. tag: 'div',
  10717. attributes: {
  10718. role: 'presentation',
  10719. ...attributes
  10720. },
  10721. ...domWithoutAttributes
  10722. },
  10723. components: detail.components,
  10724. behaviours: get$3(detail.containerBehaviours),
  10725. events: detail.events,
  10726. domModification: detail.domModification,
  10727. eventOrder: detail.eventOrder
  10728. };
  10729. };
  10730. const Container = single({
  10731. name: 'Container',
  10732. factory: factory$j,
  10733. configFields: [
  10734. defaulted('components', []),
  10735. field('containerBehaviours', []),
  10736. defaulted('events', {}),
  10737. defaulted('domModification', {}),
  10738. defaulted('eventOrder', {})
  10739. ]
  10740. });
  10741. const takeover = root => {
  10742. const isAboveRoot = el => parent(root.element).fold(always, parent => eq(el, parent));
  10743. const registry = Registry();
  10744. const lookup = (eventName, target) => registry.find(isAboveRoot, eventName, target);
  10745. const domEvents = setup$d(root.element, {
  10746. triggerEvent: (eventName, event) => {
  10747. return monitorEvent(eventName, event.target, logger => triggerUntilStopped(lookup, eventName, event, logger));
  10748. }
  10749. });
  10750. const systemApi = {
  10751. debugInfo: constant$1('real'),
  10752. triggerEvent: (eventName, target, data) => {
  10753. monitorEvent(eventName, target, logger => triggerOnUntilStopped(lookup, eventName, data, target, logger));
  10754. },
  10755. triggerFocus: (target, originator) => {
  10756. read$1(target).fold(() => {
  10757. focus$3(target);
  10758. }, _alloyId => {
  10759. monitorEvent(focus$4(), target, logger => {
  10760. triggerHandler(lookup, focus$4(), {
  10761. originator,
  10762. kill: noop,
  10763. prevent: noop,
  10764. target
  10765. }, target, logger);
  10766. return false;
  10767. });
  10768. });
  10769. },
  10770. triggerEscape: (comp, simulatedEvent) => {
  10771. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  10772. },
  10773. getByUid: uid => {
  10774. return getByUid(uid);
  10775. },
  10776. getByDom: elem => {
  10777. return getByDom(elem);
  10778. },
  10779. build: build$1,
  10780. buildOrPatch: buildOrPatch,
  10781. addToGui: c => {
  10782. add(c);
  10783. },
  10784. removeFromGui: c => {
  10785. remove(c);
  10786. },
  10787. addToWorld: c => {
  10788. addToWorld(c);
  10789. },
  10790. removeFromWorld: c => {
  10791. removeFromWorld(c);
  10792. },
  10793. broadcast: message => {
  10794. broadcast$1(message);
  10795. },
  10796. broadcastOn: (channels, message) => {
  10797. broadcastOn(channels, message);
  10798. },
  10799. broadcastEvent: (eventName, event) => {
  10800. broadcastEvent(eventName, event);
  10801. },
  10802. isConnected: always
  10803. };
  10804. const addToWorld = component => {
  10805. component.connect(systemApi);
  10806. if (!isText(component.element)) {
  10807. registry.register(component);
  10808. each$1(component.components(), addToWorld);
  10809. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  10810. }
  10811. };
  10812. const removeFromWorld = component => {
  10813. if (!isText(component.element)) {
  10814. each$1(component.components(), removeFromWorld);
  10815. registry.unregister(component);
  10816. }
  10817. component.disconnect();
  10818. };
  10819. const add = component => {
  10820. attach(root, component);
  10821. };
  10822. const remove = component => {
  10823. detach(component);
  10824. };
  10825. const destroy = () => {
  10826. domEvents.unbind();
  10827. remove$5(root.element);
  10828. };
  10829. const broadcastData = data => {
  10830. const receivers = registry.filter(receive());
  10831. each$1(receivers, receiver => {
  10832. const descHandler = receiver.descHandler;
  10833. const handler = getCurried(descHandler);
  10834. handler(data);
  10835. });
  10836. };
  10837. const broadcast$1 = message => {
  10838. broadcastData({
  10839. universal: true,
  10840. data: message
  10841. });
  10842. };
  10843. const broadcastOn = (channels, message) => {
  10844. broadcastData({
  10845. universal: false,
  10846. channels,
  10847. data: message
  10848. });
  10849. };
  10850. const broadcastEvent = (eventName, event) => {
  10851. const listeners = registry.filter(eventName);
  10852. return broadcast(listeners, event);
  10853. };
  10854. const getByUid = uid => registry.getById(uid).fold(() => Result.error(new Error('Could not find component with uid: "' + uid + '" in system.')), Result.value);
  10855. const getByDom = elem => {
  10856. const uid = read$1(elem).getOr('not found');
  10857. return getByUid(uid);
  10858. };
  10859. addToWorld(root);
  10860. return {
  10861. root,
  10862. element: root.element,
  10863. destroy,
  10864. add,
  10865. remove,
  10866. getByUid,
  10867. getByDom,
  10868. addToWorld,
  10869. removeFromWorld,
  10870. broadcast: broadcast$1,
  10871. broadcastOn,
  10872. broadcastEvent
  10873. };
  10874. };
  10875. const renderBar = (spec, backstage) => ({
  10876. dom: {
  10877. tag: 'div',
  10878. classes: [
  10879. 'tox-bar',
  10880. 'tox-form__controls-h-stack'
  10881. ]
  10882. },
  10883. components: map$2(spec.items, backstage.interpreter)
  10884. });
  10885. const schema$l = constant$1([
  10886. defaulted('prefix', 'form-field'),
  10887. field('fieldBehaviours', [
  10888. Composing,
  10889. Representing
  10890. ])
  10891. ]);
  10892. const parts$e = constant$1([
  10893. optional({
  10894. schema: [required$1('dom')],
  10895. name: 'label'
  10896. }),
  10897. optional({
  10898. factory: {
  10899. sketch: spec => {
  10900. return {
  10901. uid: spec.uid,
  10902. dom: {
  10903. tag: 'span',
  10904. styles: { display: 'none' },
  10905. attributes: { 'aria-hidden': 'true' },
  10906. innerHtml: spec.text
  10907. }
  10908. };
  10909. }
  10910. },
  10911. schema: [required$1('text')],
  10912. name: 'aria-descriptor'
  10913. }),
  10914. required({
  10915. factory: {
  10916. sketch: spec => {
  10917. const excludeFactory = exclude(spec, ['factory']);
  10918. return spec.factory.sketch(excludeFactory);
  10919. }
  10920. },
  10921. schema: [required$1('factory')],
  10922. name: 'field'
  10923. })
  10924. ]);
  10925. const factory$i = (detail, components, _spec, _externals) => {
  10926. const behaviours = augment(detail.fieldBehaviours, [
  10927. Composing.config({
  10928. find: container => {
  10929. return getPart(container, detail, 'field');
  10930. }
  10931. }),
  10932. Representing.config({
  10933. store: {
  10934. mode: 'manual',
  10935. getValue: field => {
  10936. return Composing.getCurrent(field).bind(Representing.getValue);
  10937. },
  10938. setValue: (field, value) => {
  10939. Composing.getCurrent(field).each(current => {
  10940. Representing.setValue(current, value);
  10941. });
  10942. }
  10943. }
  10944. })
  10945. ]);
  10946. const events = derive$2([runOnAttached((component, _simulatedEvent) => {
  10947. const ps = getParts(component, detail, [
  10948. 'label',
  10949. 'field',
  10950. 'aria-descriptor'
  10951. ]);
  10952. ps.field().each(field => {
  10953. const id = generate$6(detail.prefix);
  10954. ps.label().each(label => {
  10955. set$9(label.element, 'for', id);
  10956. set$9(field.element, 'id', id);
  10957. });
  10958. ps['aria-descriptor']().each(descriptor => {
  10959. const descriptorId = generate$6(detail.prefix);
  10960. set$9(descriptor.element, 'id', descriptorId);
  10961. set$9(field.element, 'aria-describedby', descriptorId);
  10962. });
  10963. });
  10964. })]);
  10965. const apis = {
  10966. getField: container => getPart(container, detail, 'field'),
  10967. getLabel: container => getPart(container, detail, 'label')
  10968. };
  10969. return {
  10970. uid: detail.uid,
  10971. dom: detail.dom,
  10972. components,
  10973. behaviours,
  10974. events,
  10975. apis
  10976. };
  10977. };
  10978. const FormField = composite({
  10979. name: 'FormField',
  10980. configFields: schema$l(),
  10981. partFields: parts$e(),
  10982. factory: factory$i,
  10983. apis: {
  10984. getField: (apis, comp) => apis.getField(comp),
  10985. getLabel: (apis, comp) => apis.getLabel(comp)
  10986. }
  10987. });
  10988. const exhibit$2 = (base, tabConfig) => nu$7({
  10989. attributes: wrapAll([{
  10990. key: tabConfig.tabAttr,
  10991. value: 'true'
  10992. }])
  10993. });
  10994. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  10995. __proto__: null,
  10996. exhibit: exhibit$2
  10997. });
  10998. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  10999. const Tabstopping = create$3({
  11000. fields: TabstopSchema,
  11001. name: 'tabstopping',
  11002. active: ActiveTabstopping
  11003. });
  11004. var global$3 = tinymce.util.Tools.resolve('tinymce.html.Entities');
  11005. const renderFormFieldWith = (pLabel, pField, extraClasses, extraBehaviours) => {
  11006. const spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  11007. return FormField.sketch(spec);
  11008. };
  11009. const renderFormField = (pLabel, pField) => renderFormFieldWith(pLabel, pField, [], []);
  11010. const renderFormFieldSpecWith = (pLabel, pField, extraClasses, extraBehaviours) => ({
  11011. dom: renderFormFieldDomWith(extraClasses),
  11012. components: pLabel.toArray().concat([pField]),
  11013. fieldBehaviours: derive$1(extraBehaviours)
  11014. });
  11015. const renderFormFieldDom = () => renderFormFieldDomWith([]);
  11016. const renderFormFieldDomWith = extraClasses => ({
  11017. tag: 'div',
  11018. classes: ['tox-form__group'].concat(extraClasses)
  11019. });
  11020. const renderLabel$2 = (label, providersBackstage) => FormField.parts.label({
  11021. dom: {
  11022. tag: 'label',
  11023. classes: ['tox-label']
  11024. },
  11025. components: [text$1(providersBackstage.translate(label))]
  11026. });
  11027. const formChangeEvent = generate$6('form-component-change');
  11028. const formCloseEvent = generate$6('form-close');
  11029. const formCancelEvent = generate$6('form-cancel');
  11030. const formActionEvent = generate$6('form-action');
  11031. const formSubmitEvent = generate$6('form-submit');
  11032. const formBlockEvent = generate$6('form-block');
  11033. const formUnblockEvent = generate$6('form-unblock');
  11034. const formTabChangeEvent = generate$6('form-tabchange');
  11035. const formResizeEvent = generate$6('form-resize');
  11036. const renderCollection = (spec, providersBackstage, initialData) => {
  11037. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  11038. const runOnItem = f => (comp, se) => {
  11039. closest$1(se.event.target, '[data-collection-item-value]').each(target => {
  11040. f(comp, se, target, get$f(target, 'data-collection-item-value'));
  11041. });
  11042. };
  11043. const setContents = (comp, items) => {
  11044. const htmlLines = map$2(items, item => {
  11045. const itemText = global$8.translate(item.text);
  11046. const textContent = spec.columns === 1 ? `<div class="tox-collection__item-label">${ itemText }</div>` : '';
  11047. const iconContent = `<div class="tox-collection__item-icon">${ item.icon }</div>`;
  11048. const mapItemName = {
  11049. '_': ' ',
  11050. ' - ': ' ',
  11051. '-': ' '
  11052. };
  11053. const ariaLabel = itemText.replace(/\_| \- |\-/g, match => mapItemName[match]);
  11054. const disabledClass = providersBackstage.isDisabled() ? ' tox-collection__item--state-disabled' : '';
  11055. return `<div class="tox-collection__item${ disabledClass }" tabindex="-1" data-collection-item-value="${ global$3.encodeAllRaw(item.value) }" title="${ ariaLabel }" aria-label="${ ariaLabel }">${ iconContent }${ textContent }</div>`;
  11056. });
  11057. const chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
  11058. const html = map$2(chunks, ch => `<div class="tox-collection__group">${ ch.join('') }</div>`);
  11059. set$6(comp.element, html.join(''));
  11060. };
  11061. const onClick = runOnItem((comp, se, tgt, itemValue) => {
  11062. se.stop();
  11063. if (!providersBackstage.isDisabled()) {
  11064. emitWith(comp, formActionEvent, {
  11065. name: spec.name,
  11066. value: itemValue
  11067. });
  11068. }
  11069. });
  11070. const collectionEvents = [
  11071. run$1(mouseover(), runOnItem((comp, se, tgt) => {
  11072. focus$3(tgt);
  11073. })),
  11074. run$1(click(), onClick),
  11075. run$1(tap(), onClick),
  11076. run$1(focusin(), runOnItem((comp, se, tgt) => {
  11077. descendant(comp.element, '.' + activeClass).each(currentActive => {
  11078. remove$2(currentActive, activeClass);
  11079. });
  11080. add$2(tgt, activeClass);
  11081. })),
  11082. run$1(focusout(), runOnItem(comp => {
  11083. descendant(comp.element, '.' + activeClass).each(currentActive => {
  11084. remove$2(currentActive, activeClass);
  11085. });
  11086. })),
  11087. runOnExecute$1(runOnItem((comp, se, tgt, itemValue) => {
  11088. emitWith(comp, formActionEvent, {
  11089. name: spec.name,
  11090. value: itemValue
  11091. });
  11092. }))
  11093. ];
  11094. const iterCollectionItems = (comp, applyAttributes) => map$2(descendants(comp.element, '.tox-collection__item'), applyAttributes);
  11095. const pField = FormField.parts.field({
  11096. dom: {
  11097. tag: 'div',
  11098. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  11099. },
  11100. components: [],
  11101. factory: { sketch: identity },
  11102. behaviours: derive$1([
  11103. Disabling.config({
  11104. disabled: providersBackstage.isDisabled,
  11105. onDisabled: comp => {
  11106. iterCollectionItems(comp, childElm => {
  11107. add$2(childElm, 'tox-collection__item--state-disabled');
  11108. set$9(childElm, 'aria-disabled', true);
  11109. });
  11110. },
  11111. onEnabled: comp => {
  11112. iterCollectionItems(comp, childElm => {
  11113. remove$2(childElm, 'tox-collection__item--state-disabled');
  11114. remove$7(childElm, 'aria-disabled');
  11115. });
  11116. }
  11117. }),
  11118. receivingConfig(),
  11119. Replacing.config({}),
  11120. Representing.config({
  11121. store: {
  11122. mode: 'memory',
  11123. initialValue: initialData.getOr([])
  11124. },
  11125. onSetValue: (comp, items) => {
  11126. setContents(comp, items);
  11127. if (spec.columns === 'auto') {
  11128. detectSize(comp, 5, 'tox-collection__item').each(({numRows, numColumns}) => {
  11129. Keying.setGridSize(comp, numRows, numColumns);
  11130. });
  11131. }
  11132. emit(comp, formResizeEvent);
  11133. }
  11134. }),
  11135. Tabstopping.config({}),
  11136. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  11137. config('collection-events', collectionEvents)
  11138. ]),
  11139. eventOrder: {
  11140. [execute$5()]: [
  11141. 'disabling',
  11142. 'alloy.base.behaviour',
  11143. 'collection-events'
  11144. ]
  11145. }
  11146. });
  11147. const extraClasses = ['tox-form__group--collection'];
  11148. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  11149. };
  11150. const schema$k = constant$1([
  11151. option$3('data'),
  11152. defaulted('inputAttributes', {}),
  11153. defaulted('inputStyles', {}),
  11154. defaulted('tag', 'input'),
  11155. defaulted('inputClasses', []),
  11156. onHandler('onSetValue'),
  11157. defaulted('styles', {}),
  11158. defaulted('eventOrder', {}),
  11159. field('inputBehaviours', [
  11160. Representing,
  11161. Focusing
  11162. ]),
  11163. defaulted('selectOnFocus', true)
  11164. ]);
  11165. const focusBehaviours = detail => derive$1([Focusing.config({
  11166. onFocus: !detail.selectOnFocus ? noop : component => {
  11167. const input = component.element;
  11168. const value = get$6(input);
  11169. input.dom.setSelectionRange(0, value.length);
  11170. }
  11171. })]);
  11172. const behaviours = detail => ({
  11173. ...focusBehaviours(detail),
  11174. ...augment(detail.inputBehaviours, [Representing.config({
  11175. store: {
  11176. mode: 'manual',
  11177. ...detail.data.map(data => ({ initialValue: data })).getOr({}),
  11178. getValue: input => {
  11179. return get$6(input.element);
  11180. },
  11181. setValue: (input, data) => {
  11182. const current = get$6(input.element);
  11183. if (current !== data) {
  11184. set$5(input.element, data);
  11185. }
  11186. }
  11187. },
  11188. onSetValue: detail.onSetValue
  11189. })])
  11190. });
  11191. const dom = detail => ({
  11192. tag: detail.tag,
  11193. attributes: {
  11194. type: 'text',
  11195. ...detail.inputAttributes
  11196. },
  11197. styles: detail.inputStyles,
  11198. classes: detail.inputClasses
  11199. });
  11200. const factory$h = (detail, _spec) => ({
  11201. uid: detail.uid,
  11202. dom: dom(detail),
  11203. components: [],
  11204. behaviours: behaviours(detail),
  11205. eventOrder: detail.eventOrder
  11206. });
  11207. const Input = single({
  11208. name: 'Input',
  11209. configFields: schema$k(),
  11210. factory: factory$h
  11211. });
  11212. const nu$3 = baseFn => {
  11213. let data = Optional.none();
  11214. let callbacks = [];
  11215. const map = f => nu$3(nCallback => {
  11216. get(data => {
  11217. nCallback(f(data));
  11218. });
  11219. });
  11220. const get = nCallback => {
  11221. if (isReady()) {
  11222. call(nCallback);
  11223. } else {
  11224. callbacks.push(nCallback);
  11225. }
  11226. };
  11227. const set = x => {
  11228. if (!isReady()) {
  11229. data = Optional.some(x);
  11230. run(callbacks);
  11231. callbacks = [];
  11232. }
  11233. };
  11234. const isReady = () => data.isSome();
  11235. const run = cbs => {
  11236. each$1(cbs, call);
  11237. };
  11238. const call = cb => {
  11239. data.each(x => {
  11240. setTimeout(() => {
  11241. cb(x);
  11242. }, 0);
  11243. });
  11244. };
  11245. baseFn(set);
  11246. return {
  11247. get,
  11248. map,
  11249. isReady
  11250. };
  11251. };
  11252. const pure$1 = a => nu$3(callback => {
  11253. callback(a);
  11254. });
  11255. const LazyValue = {
  11256. nu: nu$3,
  11257. pure: pure$1
  11258. };
  11259. const errorReporter = err => {
  11260. setTimeout(() => {
  11261. throw err;
  11262. }, 0);
  11263. };
  11264. const make$5 = run => {
  11265. const get = callback => {
  11266. run().then(callback, errorReporter);
  11267. };
  11268. const map = fab => {
  11269. return make$5(() => run().then(fab));
  11270. };
  11271. const bind = aFutureB => {
  11272. return make$5(() => run().then(v => aFutureB(v).toPromise()));
  11273. };
  11274. const anonBind = futureB => {
  11275. return make$5(() => run().then(() => futureB.toPromise()));
  11276. };
  11277. const toLazy = () => {
  11278. return LazyValue.nu(get);
  11279. };
  11280. const toCached = () => {
  11281. let cache = null;
  11282. return make$5(() => {
  11283. if (cache === null) {
  11284. cache = run();
  11285. }
  11286. return cache;
  11287. });
  11288. };
  11289. const toPromise = run;
  11290. return {
  11291. map,
  11292. bind,
  11293. anonBind,
  11294. toLazy,
  11295. toCached,
  11296. toPromise,
  11297. get
  11298. };
  11299. };
  11300. const nu$2 = baseFn => {
  11301. return make$5(() => new Promise(baseFn));
  11302. };
  11303. const pure = a => {
  11304. return make$5(() => Promise.resolve(a));
  11305. };
  11306. const Future = {
  11307. nu: nu$2,
  11308. pure
  11309. };
  11310. const ariaElements = [
  11311. 'input',
  11312. 'textarea'
  11313. ];
  11314. const isAriaElement = elem => {
  11315. const name = name$3(elem);
  11316. return contains$2(ariaElements, name);
  11317. };
  11318. const markValid = (component, invalidConfig) => {
  11319. const elem = invalidConfig.getRoot(component).getOr(component.element);
  11320. remove$2(elem, invalidConfig.invalidClass);
  11321. invalidConfig.notify.each(notifyInfo => {
  11322. if (isAriaElement(component.element)) {
  11323. set$9(component.element, 'aria-invalid', false);
  11324. }
  11325. notifyInfo.getContainer(component).each(container => {
  11326. set$6(container, notifyInfo.validHtml);
  11327. });
  11328. notifyInfo.onValid(component);
  11329. });
  11330. };
  11331. const markInvalid = (component, invalidConfig, invalidState, text) => {
  11332. const elem = invalidConfig.getRoot(component).getOr(component.element);
  11333. add$2(elem, invalidConfig.invalidClass);
  11334. invalidConfig.notify.each(notifyInfo => {
  11335. if (isAriaElement(component.element)) {
  11336. set$9(component.element, 'aria-invalid', true);
  11337. }
  11338. notifyInfo.getContainer(component).each(container => {
  11339. set$6(container, text);
  11340. });
  11341. notifyInfo.onInvalid(component, text);
  11342. });
  11343. };
  11344. const query = (component, invalidConfig, _invalidState) => invalidConfig.validator.fold(() => Future.pure(Result.value(true)), validatorInfo => validatorInfo.validate(component));
  11345. const run = (component, invalidConfig, invalidState) => {
  11346. invalidConfig.notify.each(notifyInfo => {
  11347. notifyInfo.onValidate(component);
  11348. });
  11349. return query(component, invalidConfig).map(valid => {
  11350. if (component.getSystem().isConnected()) {
  11351. return valid.fold(err => {
  11352. markInvalid(component, invalidConfig, invalidState, err);
  11353. return Result.error(err);
  11354. }, v => {
  11355. markValid(component, invalidConfig);
  11356. return Result.value(v);
  11357. });
  11358. } else {
  11359. return Result.error('No longer in system');
  11360. }
  11361. });
  11362. };
  11363. const isInvalid = (component, invalidConfig) => {
  11364. const elem = invalidConfig.getRoot(component).getOr(component.element);
  11365. return has(elem, invalidConfig.invalidClass);
  11366. };
  11367. var InvalidateApis = /*#__PURE__*/Object.freeze({
  11368. __proto__: null,
  11369. markValid: markValid,
  11370. markInvalid: markInvalid,
  11371. query: query,
  11372. run: run,
  11373. isInvalid: isInvalid
  11374. });
  11375. const events$8 = (invalidConfig, invalidState) => invalidConfig.validator.map(validatorInfo => derive$2([run$1(validatorInfo.onEvent, component => {
  11376. run(component, invalidConfig, invalidState).get(identity);
  11377. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(component => {
  11378. run(component, invalidConfig, invalidState).get(noop);
  11379. })] : []))).getOr({});
  11380. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  11381. __proto__: null,
  11382. events: events$8
  11383. });
  11384. var InvalidateSchema = [
  11385. required$1('invalidClass'),
  11386. defaulted('getRoot', Optional.none),
  11387. optionObjOf('notify', [
  11388. defaulted('aria', 'alert'),
  11389. defaulted('getContainer', Optional.none),
  11390. defaulted('validHtml', ''),
  11391. onHandler('onValid'),
  11392. onHandler('onInvalid'),
  11393. onHandler('onValidate')
  11394. ]),
  11395. optionObjOf('validator', [
  11396. required$1('validate'),
  11397. defaulted('onEvent', 'input'),
  11398. defaulted('validateOnLoad', true)
  11399. ])
  11400. ];
  11401. const Invalidating = create$3({
  11402. fields: InvalidateSchema,
  11403. name: 'invalidating',
  11404. active: ActiveInvalidate,
  11405. apis: InvalidateApis,
  11406. extra: {
  11407. validation: validator => {
  11408. return component => {
  11409. const v = Representing.getValue(component);
  11410. return Future.pure(validator(v));
  11411. };
  11412. }
  11413. }
  11414. });
  11415. const getCoupled = (component, coupleConfig, coupleState, name) => coupleState.getOrCreate(component, coupleConfig, name);
  11416. var CouplingApis = /*#__PURE__*/Object.freeze({
  11417. __proto__: null,
  11418. getCoupled: getCoupled
  11419. });
  11420. var CouplingSchema = [requiredOf('others', setOf(Result.value, anyValue()))];
  11421. const init$a = () => {
  11422. const coupled = {};
  11423. const getOrCreate = (component, coupleConfig, name) => {
  11424. const available = keys(coupleConfig.others);
  11425. if (!available) {
  11426. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  11427. } else {
  11428. return get$g(coupled, name).getOrThunk(() => {
  11429. const builder = get$g(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  11430. const spec = builder(component);
  11431. const built = component.getSystem().build(spec);
  11432. coupled[name] = built;
  11433. return built;
  11434. });
  11435. }
  11436. };
  11437. const readState = constant$1({});
  11438. return nu$8({
  11439. readState,
  11440. getOrCreate
  11441. });
  11442. };
  11443. var CouplingState = /*#__PURE__*/Object.freeze({
  11444. __proto__: null,
  11445. init: init$a
  11446. });
  11447. const Coupling = create$3({
  11448. fields: CouplingSchema,
  11449. name: 'coupling',
  11450. apis: CouplingApis,
  11451. state: CouplingState
  11452. });
  11453. const suffix = constant$1('sink');
  11454. const partType$1 = constant$1(optional({
  11455. name: suffix(),
  11456. overrides: constant$1({
  11457. dom: { tag: 'div' },
  11458. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  11459. events: derive$2([
  11460. cutter(keydown()),
  11461. cutter(mousedown()),
  11462. cutter(click())
  11463. ])
  11464. })
  11465. }));
  11466. var HighlightOnOpen;
  11467. (function (HighlightOnOpen) {
  11468. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  11469. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  11470. }(HighlightOnOpen || (HighlightOnOpen = {})));
  11471. const getAnchor = (detail, component) => {
  11472. const hotspot = detail.getHotspot(component).getOr(component);
  11473. const type = 'hotspot';
  11474. const overrides = detail.getAnchorOverrides();
  11475. return detail.layouts.fold(() => ({
  11476. type,
  11477. hotspot,
  11478. overrides
  11479. }), layouts => ({
  11480. type,
  11481. hotspot,
  11482. overrides,
  11483. layouts
  11484. }));
  11485. };
  11486. const fetch = (detail, mapFetch, component) => {
  11487. const fetcher = detail.fetch;
  11488. return fetcher(component).map(mapFetch);
  11489. };
  11490. const openF = (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) => {
  11491. const futureData = fetch(detail, mapFetch, component);
  11492. const getLazySink = getSink(component, detail);
  11493. return futureData.map(tdata => tdata.bind(data => Optional.from(tieredMenu.sketch({
  11494. ...externals.menu(),
  11495. uid: generate$5(''),
  11496. data,
  11497. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  11498. onOpenMenu: (tmenu, menu) => {
  11499. const sink = getLazySink().getOrDie();
  11500. Positioning.position(sink, menu, { anchor });
  11501. Sandboxing.decloak(sandbox);
  11502. },
  11503. onOpenSubmenu: (tmenu, item, submenu) => {
  11504. const sink = getLazySink().getOrDie();
  11505. Positioning.position(sink, submenu, {
  11506. anchor: {
  11507. type: 'submenu',
  11508. item
  11509. }
  11510. });
  11511. Sandboxing.decloak(sandbox);
  11512. },
  11513. onRepositionMenu: (tmenu, primaryMenu, submenuTriggers) => {
  11514. const sink = getLazySink().getOrDie();
  11515. Positioning.position(sink, primaryMenu, { anchor });
  11516. each$1(submenuTriggers, st => {
  11517. Positioning.position(sink, st.triggeredMenu, {
  11518. anchor: {
  11519. type: 'submenu',
  11520. item: st.triggeringItem
  11521. }
  11522. });
  11523. });
  11524. },
  11525. onEscape: () => {
  11526. Focusing.focus(component);
  11527. Sandboxing.close(sandbox);
  11528. return Optional.some(true);
  11529. }
  11530. }))));
  11531. };
  11532. const open = (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) => {
  11533. const anchor = getAnchor(detail, hotspot);
  11534. const processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  11535. return processed.map(tdata => {
  11536. tdata.fold(() => {
  11537. if (Sandboxing.isOpen(sandbox)) {
  11538. Sandboxing.close(sandbox);
  11539. }
  11540. }, data => {
  11541. Sandboxing.cloak(sandbox);
  11542. Sandboxing.open(sandbox, data);
  11543. onOpenSync(sandbox);
  11544. });
  11545. return sandbox;
  11546. });
  11547. };
  11548. const close = (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) => {
  11549. Sandboxing.close(sandbox);
  11550. return Future.pure(sandbox);
  11551. };
  11552. const togglePopup = (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) => {
  11553. const sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  11554. const showing = Sandboxing.isOpen(sandbox);
  11555. const action = showing ? close : open;
  11556. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  11557. };
  11558. const matchWidth = (hotspot, container, useMinWidth) => {
  11559. const menu = Composing.getCurrent(container).getOr(container);
  11560. const buttonWidth = get$c(hotspot.element);
  11561. if (useMinWidth) {
  11562. set$8(menu.element, 'min-width', buttonWidth + 'px');
  11563. } else {
  11564. set$7(menu.element, buttonWidth);
  11565. }
  11566. };
  11567. const getSink = (anyInSystem, sinkDetail) => anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(internalSink => () => Result.value(internalSink)).getOrThunk(() => sinkDetail.lazySink.fold(() => () => Result.error(new Error('No internal sink is specified, nor could an external sink be found')), lazySinkFn => () => lazySinkFn(anyInSystem)));
  11568. const doRepositionMenus = sandbox => {
  11569. Sandboxing.getState(sandbox).each(tmenu => {
  11570. tieredMenu.repositionMenus(tmenu);
  11571. });
  11572. };
  11573. const makeSandbox$1 = (detail, hotspot, extras) => {
  11574. const ariaControls = manager();
  11575. const onOpen = (component, menu) => {
  11576. const anchor = getAnchor(detail, hotspot);
  11577. ariaControls.link(hotspot.element);
  11578. if (detail.matchWidth) {
  11579. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  11580. }
  11581. detail.onOpen(anchor, component, menu);
  11582. if (extras !== undefined && extras.onOpen !== undefined) {
  11583. extras.onOpen(component, menu);
  11584. }
  11585. };
  11586. const onClose = (component, menu) => {
  11587. ariaControls.unlink(hotspot.element);
  11588. if (extras !== undefined && extras.onClose !== undefined) {
  11589. extras.onClose(component, menu);
  11590. }
  11591. };
  11592. const lazySink = getSink(hotspot, detail);
  11593. return {
  11594. dom: {
  11595. tag: 'div',
  11596. classes: detail.sandboxClasses,
  11597. attributes: {
  11598. id: ariaControls.id,
  11599. role: 'listbox'
  11600. }
  11601. },
  11602. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  11603. Representing.config({
  11604. store: {
  11605. mode: 'memory',
  11606. initialValue: hotspot
  11607. }
  11608. }),
  11609. Sandboxing.config({
  11610. onOpen,
  11611. onClose,
  11612. isPartOf: (container, data, queryElem) => {
  11613. return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
  11614. },
  11615. getAttachPoint: () => {
  11616. return lazySink().getOrDie();
  11617. }
  11618. }),
  11619. Composing.config({
  11620. find: sandbox => {
  11621. return Sandboxing.getState(sandbox).bind(menu => Composing.getCurrent(menu));
  11622. }
  11623. }),
  11624. Receiving.config({
  11625. channels: {
  11626. ...receivingChannel$1({ isExtraPart: never }),
  11627. ...receivingChannel({ doReposition: doRepositionMenus })
  11628. }
  11629. })
  11630. ])
  11631. };
  11632. };
  11633. const repositionMenus = comp => {
  11634. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  11635. doRepositionMenus(sandbox);
  11636. };
  11637. const sandboxFields = () => [
  11638. defaulted('sandboxClasses', []),
  11639. SketchBehaviours.field('sandboxBehaviours', [
  11640. Composing,
  11641. Receiving,
  11642. Sandboxing,
  11643. Representing
  11644. ])
  11645. ];
  11646. const schema$j = constant$1([
  11647. required$1('dom'),
  11648. required$1('fetch'),
  11649. onHandler('onOpen'),
  11650. onKeyboardHandler('onExecute'),
  11651. defaulted('getHotspot', Optional.some),
  11652. defaulted('getAnchorOverrides', constant$1({})),
  11653. schema$y(),
  11654. field('dropdownBehaviours', [
  11655. Toggling,
  11656. Coupling,
  11657. Keying,
  11658. Focusing
  11659. ]),
  11660. required$1('toggleClass'),
  11661. defaulted('eventOrder', {}),
  11662. option$3('lazySink'),
  11663. defaulted('matchWidth', false),
  11664. defaulted('useMinWidth', false),
  11665. option$3('role')
  11666. ].concat(sandboxFields()));
  11667. const parts$d = constant$1([
  11668. external({
  11669. schema: [tieredMenuMarkers()],
  11670. name: 'menu',
  11671. defaults: detail => {
  11672. return { onExecute: detail.onExecute };
  11673. }
  11674. }),
  11675. partType$1()
  11676. ]);
  11677. const factory$g = (detail, components, _spec, externals) => {
  11678. const lookupAttr = attr => get$g(detail.dom, 'attributes').bind(attrs => get$g(attrs, attr));
  11679. const switchToMenu = sandbox => {
  11680. Sandboxing.getState(sandbox).each(tmenu => {
  11681. tieredMenu.highlightPrimary(tmenu);
  11682. });
  11683. };
  11684. const action = component => {
  11685. const onOpenSync = switchToMenu;
  11686. togglePopup(detail, identity, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  11687. };
  11688. const apis = {
  11689. expand: comp => {
  11690. if (!Toggling.isOn(comp)) {
  11691. togglePopup(detail, identity, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  11692. }
  11693. },
  11694. open: comp => {
  11695. if (!Toggling.isOn(comp)) {
  11696. togglePopup(detail, identity, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  11697. }
  11698. },
  11699. isOpen: Toggling.isOn,
  11700. close: comp => {
  11701. if (Toggling.isOn(comp)) {
  11702. togglePopup(detail, identity, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  11703. }
  11704. },
  11705. repositionMenus: comp => {
  11706. if (Toggling.isOn(comp)) {
  11707. repositionMenus(comp);
  11708. }
  11709. }
  11710. };
  11711. const triggerExecute = (comp, _se) => {
  11712. emitExecute(comp);
  11713. return Optional.some(true);
  11714. };
  11715. return {
  11716. uid: detail.uid,
  11717. dom: detail.dom,
  11718. components,
  11719. behaviours: augment(detail.dropdownBehaviours, [
  11720. Toggling.config({
  11721. toggleClass: detail.toggleClass,
  11722. aria: { mode: 'expanded' }
  11723. }),
  11724. Coupling.config({
  11725. others: {
  11726. sandbox: hotspot => {
  11727. return makeSandbox$1(detail, hotspot, {
  11728. onOpen: () => Toggling.on(hotspot),
  11729. onClose: () => Toggling.off(hotspot)
  11730. });
  11731. }
  11732. }
  11733. }),
  11734. Keying.config({
  11735. mode: 'special',
  11736. onSpace: triggerExecute,
  11737. onEnter: triggerExecute,
  11738. onDown: (comp, _se) => {
  11739. if (Dropdown.isOpen(comp)) {
  11740. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  11741. switchToMenu(sandbox);
  11742. } else {
  11743. Dropdown.open(comp);
  11744. }
  11745. return Optional.some(true);
  11746. },
  11747. onEscape: (comp, _se) => {
  11748. if (Dropdown.isOpen(comp)) {
  11749. Dropdown.close(comp);
  11750. return Optional.some(true);
  11751. } else {
  11752. return Optional.none();
  11753. }
  11754. }
  11755. }),
  11756. Focusing.config({})
  11757. ]),
  11758. events: events$a(Optional.some(action)),
  11759. eventOrder: {
  11760. ...detail.eventOrder,
  11761. [execute$5()]: [
  11762. 'disabling',
  11763. 'toggling',
  11764. 'alloy.base.behaviour'
  11765. ]
  11766. },
  11767. apis,
  11768. domModification: {
  11769. attributes: {
  11770. 'aria-haspopup': 'true',
  11771. ...detail.role.fold(() => ({}), role => ({ role })),
  11772. ...detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {}
  11773. }
  11774. }
  11775. };
  11776. };
  11777. const Dropdown = composite({
  11778. name: 'Dropdown',
  11779. configFields: schema$j(),
  11780. partFields: parts$d(),
  11781. factory: factory$g,
  11782. apis: {
  11783. open: (apis, comp) => apis.open(comp),
  11784. expand: (apis, comp) => apis.expand(comp),
  11785. close: (apis, comp) => apis.close(comp),
  11786. isOpen: (apis, comp) => apis.isOpen(comp),
  11787. repositionMenus: (apis, comp) => apis.repositionMenus(comp)
  11788. }
  11789. });
  11790. const exhibit$1 = () => nu$7({
  11791. styles: {
  11792. '-webkit-user-select': 'none',
  11793. 'user-select': 'none',
  11794. '-ms-user-select': 'none',
  11795. '-moz-user-select': '-moz-none'
  11796. },
  11797. attributes: { unselectable: 'on' }
  11798. });
  11799. const events$7 = () => derive$2([abort(selectstart(), always)]);
  11800. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  11801. __proto__: null,
  11802. events: events$7,
  11803. exhibit: exhibit$1
  11804. });
  11805. const Unselecting = create$3({
  11806. fields: [],
  11807. name: 'unselecting',
  11808. active: ActiveUnselecting
  11809. });
  11810. const renderPanelButton = (spec, sharedBackstage) => Dropdown.sketch({
  11811. dom: spec.dom,
  11812. components: spec.components,
  11813. toggleClass: 'mce-active',
  11814. dropdownBehaviours: derive$1([
  11815. DisablingConfigs.button(sharedBackstage.providers.isDisabled),
  11816. receivingConfig(),
  11817. Unselecting.config({}),
  11818. Tabstopping.config({})
  11819. ]),
  11820. layouts: spec.layouts,
  11821. sandboxClasses: ['tox-dialog__popups'],
  11822. lazySink: sharedBackstage.getSink,
  11823. fetch: comp => Future.nu(callback => spec.fetch(callback)).map(items => Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, value => {
  11824. spec.onItemAction(comp, value);
  11825. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })))),
  11826. parts: { menu: part(false, 1, spec.presets) }
  11827. });
  11828. const colorInputChangeEvent = generate$6('color-input-change');
  11829. const colorSwatchChangeEvent = generate$6('color-swatch-change');
  11830. const colorPickerCancelEvent = generate$6('color-picker-cancel');
  11831. const renderColorInput = (spec, sharedBackstage, colorInputBackstage, initialData) => {
  11832. const pField = FormField.parts.field({
  11833. factory: Input,
  11834. inputClasses: ['tox-textfield'],
  11835. data: initialData,
  11836. onSetValue: c => Invalidating.run(c).get(noop),
  11837. inputBehaviours: derive$1([
  11838. Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
  11839. receivingConfig(),
  11840. Tabstopping.config({}),
  11841. Invalidating.config({
  11842. invalidClass: 'tox-textbox-field-invalid',
  11843. getRoot: comp => parentElement(comp.element),
  11844. notify: {
  11845. onValid: comp => {
  11846. const val = Representing.getValue(comp);
  11847. emitWith(comp, colorInputChangeEvent, { color: val });
  11848. }
  11849. },
  11850. validator: {
  11851. validateOnLoad: false,
  11852. validate: input => {
  11853. const inputValue = Representing.getValue(input);
  11854. if (inputValue.length === 0) {
  11855. return Future.pure(Result.value(true));
  11856. } else {
  11857. const span = SugarElement.fromTag('span');
  11858. set$8(span, 'background-color', inputValue);
  11859. const res = getRaw(span, 'background-color').fold(() => Result.error('blah'), _ => Result.value(inputValue));
  11860. return Future.pure(res);
  11861. }
  11862. }
  11863. }
  11864. })
  11865. ]),
  11866. selectOnFocus: false
  11867. });
  11868. const pLabel = spec.label.map(label => renderLabel$2(label, sharedBackstage.providers));
  11869. const emitSwatchChange = (colorBit, value) => {
  11870. emitWith(colorBit, colorSwatchChangeEvent, { value });
  11871. };
  11872. const onItemAction = (comp, value) => {
  11873. memColorButton.getOpt(comp).each(colorBit => {
  11874. if (value === 'custom') {
  11875. colorInputBackstage.colorPicker(valueOpt => {
  11876. valueOpt.fold(() => emit(colorBit, colorPickerCancelEvent), value => {
  11877. emitSwatchChange(colorBit, value);
  11878. addColor(value);
  11879. });
  11880. }, '#ffffff');
  11881. } else if (value === 'remove') {
  11882. emitSwatchChange(colorBit, '');
  11883. } else {
  11884. emitSwatchChange(colorBit, value);
  11885. }
  11886. });
  11887. };
  11888. const memColorButton = record(renderPanelButton({
  11889. dom: {
  11890. tag: 'span',
  11891. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  11892. },
  11893. layouts: {
  11894. onRtl: () => [
  11895. southwest$2,
  11896. southeast$2,
  11897. south$2
  11898. ],
  11899. onLtr: () => [
  11900. southeast$2,
  11901. southwest$2,
  11902. south$2
  11903. ]
  11904. },
  11905. components: [],
  11906. fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  11907. columns: colorInputBackstage.getColorCols(),
  11908. presets: 'color',
  11909. onItemAction
  11910. }, sharedBackstage));
  11911. return FormField.sketch({
  11912. dom: {
  11913. tag: 'div',
  11914. classes: ['tox-form__group']
  11915. },
  11916. components: pLabel.toArray().concat([{
  11917. dom: {
  11918. tag: 'div',
  11919. classes: ['tox-color-input']
  11920. },
  11921. components: [
  11922. pField,
  11923. memColorButton.asSpec()
  11924. ]
  11925. }]),
  11926. fieldBehaviours: derive$1([config('form-field-events', [
  11927. run$1(colorInputChangeEvent, (comp, se) => {
  11928. memColorButton.getOpt(comp).each(colorButton => {
  11929. set$8(colorButton.element, 'background-color', se.event.color);
  11930. });
  11931. emitWith(comp, formChangeEvent, { name: spec.name });
  11932. }),
  11933. run$1(colorSwatchChangeEvent, (comp, se) => {
  11934. FormField.getField(comp).each(field => {
  11935. Representing.setValue(field, se.event.value);
  11936. Composing.getCurrent(comp).each(Focusing.focus);
  11937. });
  11938. }),
  11939. run$1(colorPickerCancelEvent, (comp, _se) => {
  11940. FormField.getField(comp).each(_field => {
  11941. Composing.getCurrent(comp).each(Focusing.focus);
  11942. });
  11943. })
  11944. ])])
  11945. });
  11946. };
  11947. const labelPart = optional({
  11948. schema: [required$1('dom')],
  11949. name: 'label'
  11950. });
  11951. const edgePart = name => optional({
  11952. name: '' + name + '-edge',
  11953. overrides: detail => {
  11954. const action = detail.model.manager.edgeActions[name];
  11955. return action.fold(() => ({}), a => ({
  11956. events: derive$2([
  11957. runActionExtra(touchstart(), (comp, se, d) => a(comp, d), [detail]),
  11958. runActionExtra(mousedown(), (comp, se, d) => a(comp, d), [detail]),
  11959. runActionExtra(mousemove(), (comp, se, det) => {
  11960. if (det.mouseIsDown.get()) {
  11961. a(comp, det);
  11962. }
  11963. }, [detail])
  11964. ])
  11965. }));
  11966. }
  11967. });
  11968. const tlEdgePart = edgePart('top-left');
  11969. const tedgePart = edgePart('top');
  11970. const trEdgePart = edgePart('top-right');
  11971. const redgePart = edgePart('right');
  11972. const brEdgePart = edgePart('bottom-right');
  11973. const bedgePart = edgePart('bottom');
  11974. const blEdgePart = edgePart('bottom-left');
  11975. const ledgePart = edgePart('left');
  11976. const thumbPart = required({
  11977. name: 'thumb',
  11978. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  11979. overrides: detail => {
  11980. return {
  11981. events: derive$2([
  11982. redirectToPart(touchstart(), detail, 'spectrum'),
  11983. redirectToPart(touchmove(), detail, 'spectrum'),
  11984. redirectToPart(touchend(), detail, 'spectrum'),
  11985. redirectToPart(mousedown(), detail, 'spectrum'),
  11986. redirectToPart(mousemove(), detail, 'spectrum'),
  11987. redirectToPart(mouseup(), detail, 'spectrum')
  11988. ])
  11989. };
  11990. }
  11991. });
  11992. const spectrumPart = required({
  11993. schema: [customField('mouseIsDown', () => Cell(false))],
  11994. name: 'spectrum',
  11995. overrides: detail => {
  11996. const modelDetail = detail.model;
  11997. const model = modelDetail.manager;
  11998. const setValueFrom = (component, simulatedEvent) => model.getValueFromEvent(simulatedEvent).map(value => model.setValueFrom(component, detail, value));
  11999. return {
  12000. behaviours: derive$1([
  12001. Keying.config({
  12002. mode: 'special',
  12003. onLeft: spectrum => model.onLeft(spectrum, detail),
  12004. onRight: spectrum => model.onRight(spectrum, detail),
  12005. onUp: spectrum => model.onUp(spectrum, detail),
  12006. onDown: spectrum => model.onDown(spectrum, detail)
  12007. }),
  12008. Focusing.config({})
  12009. ]),
  12010. events: derive$2([
  12011. run$1(touchstart(), setValueFrom),
  12012. run$1(touchmove(), setValueFrom),
  12013. run$1(mousedown(), setValueFrom),
  12014. run$1(mousemove(), (spectrum, se) => {
  12015. if (detail.mouseIsDown.get()) {
  12016. setValueFrom(spectrum, se);
  12017. }
  12018. })
  12019. ])
  12020. };
  12021. }
  12022. });
  12023. var SliderParts = [
  12024. labelPart,
  12025. ledgePart,
  12026. redgePart,
  12027. tedgePart,
  12028. bedgePart,
  12029. tlEdgePart,
  12030. trEdgePart,
  12031. blEdgePart,
  12032. brEdgePart,
  12033. thumbPart,
  12034. spectrumPart
  12035. ];
  12036. const _sliderChangeEvent = 'slider.change.value';
  12037. const sliderChangeEvent = constant$1(_sliderChangeEvent);
  12038. const isTouchEvent$1 = evt => evt.type.indexOf('touch') !== -1;
  12039. const getEventSource = simulatedEvent => {
  12040. const evt = simulatedEvent.event.raw;
  12041. if (isTouchEvent$1(evt)) {
  12042. const touchEvent = evt;
  12043. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(t => SugarPosition(t.clientX, t.clientY)) : Optional.none();
  12044. } else {
  12045. const mouseEvent = evt;
  12046. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(me => SugarPosition(me.clientX, me.clientY)) : Optional.none();
  12047. }
  12048. };
  12049. const t = 'top', r = 'right', b = 'bottom', l = 'left';
  12050. const minX = detail => detail.model.minX;
  12051. const minY = detail => detail.model.minY;
  12052. const min1X = detail => detail.model.minX - 1;
  12053. const min1Y = detail => detail.model.minY - 1;
  12054. const maxX = detail => detail.model.maxX;
  12055. const maxY = detail => detail.model.maxY;
  12056. const max1X = detail => detail.model.maxX + 1;
  12057. const max1Y = detail => detail.model.maxY + 1;
  12058. const range = (detail, max, min) => max(detail) - min(detail);
  12059. const xRange = detail => range(detail, maxX, minX);
  12060. const yRange = detail => range(detail, maxY, minY);
  12061. const halfX = detail => xRange(detail) / 2;
  12062. const halfY = detail => yRange(detail) / 2;
  12063. const step = detail => detail.stepSize;
  12064. const snap = detail => detail.snapToGrid;
  12065. const snapStart = detail => detail.snapStart;
  12066. const rounded = detail => detail.rounded;
  12067. const hasEdge = (detail, edgeName) => detail[edgeName + '-edge'] !== undefined;
  12068. const hasLEdge = detail => hasEdge(detail, l);
  12069. const hasREdge = detail => hasEdge(detail, r);
  12070. const hasTEdge = detail => hasEdge(detail, t);
  12071. const hasBEdge = detail => hasEdge(detail, b);
  12072. const currentValue = detail => detail.model.value.get();
  12073. const xyValue = (x, y) => ({
  12074. x,
  12075. y
  12076. });
  12077. const fireSliderChange$3 = (component, value) => {
  12078. emitWith(component, sliderChangeEvent(), { value });
  12079. };
  12080. const setToTLEdgeXY = (edge, detail) => {
  12081. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  12082. };
  12083. const setToTEdge = (edge, detail) => {
  12084. fireSliderChange$3(edge, min1Y(detail));
  12085. };
  12086. const setToTEdgeXY = (edge, detail) => {
  12087. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  12088. };
  12089. const setToTREdgeXY = (edge, detail) => {
  12090. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  12091. };
  12092. const setToREdge = (edge, detail) => {
  12093. fireSliderChange$3(edge, max1X(detail));
  12094. };
  12095. const setToREdgeXY = (edge, detail) => {
  12096. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  12097. };
  12098. const setToBREdgeXY = (edge, detail) => {
  12099. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  12100. };
  12101. const setToBEdge = (edge, detail) => {
  12102. fireSliderChange$3(edge, max1Y(detail));
  12103. };
  12104. const setToBEdgeXY = (edge, detail) => {
  12105. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  12106. };
  12107. const setToBLEdgeXY = (edge, detail) => {
  12108. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  12109. };
  12110. const setToLEdge = (edge, detail) => {
  12111. fireSliderChange$3(edge, min1X(detail));
  12112. };
  12113. const setToLEdgeXY = (edge, detail) => {
  12114. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  12115. };
  12116. const reduceBy = (value, min, max, step) => {
  12117. if (value < min) {
  12118. return value;
  12119. } else if (value > max) {
  12120. return max;
  12121. } else if (value === min) {
  12122. return min - 1;
  12123. } else {
  12124. return Math.max(min, value - step);
  12125. }
  12126. };
  12127. const increaseBy = (value, min, max, step) => {
  12128. if (value > max) {
  12129. return value;
  12130. } else if (value < min) {
  12131. return min;
  12132. } else if (value === max) {
  12133. return max + 1;
  12134. } else {
  12135. return Math.min(max, value + step);
  12136. }
  12137. };
  12138. const capValue = (value, min, max) => Math.max(min, Math.min(max, value));
  12139. const snapValueOf = (value, min, max, step, snapStart) => snapStart.fold(() => {
  12140. const initValue = value - min;
  12141. const extraValue = Math.round(initValue / step) * step;
  12142. return capValue(min + extraValue, min - 1, max + 1);
  12143. }, start => {
  12144. const remainder = (value - start) % step;
  12145. const adjustment = Math.round(remainder / step);
  12146. const rawSteps = Math.floor((value - start) / step);
  12147. const maxSteps = Math.floor((max - start) / step);
  12148. const numSteps = Math.min(maxSteps, rawSteps + adjustment);
  12149. const r = start + numSteps * step;
  12150. return Math.max(start, r);
  12151. });
  12152. const findOffsetOf = (value, min, max) => Math.min(max, Math.max(value, min)) - min;
  12153. const findValueOf = args => {
  12154. const {min, max, range, value, step, snap, snapStart, rounded, hasMinEdge, hasMaxEdge, minBound, maxBound, screenRange} = args;
  12155. const capMin = hasMinEdge ? min - 1 : min;
  12156. const capMax = hasMaxEdge ? max + 1 : max;
  12157. if (value < minBound) {
  12158. return capMin;
  12159. } else if (value > maxBound) {
  12160. return capMax;
  12161. } else {
  12162. const offset = findOffsetOf(value, minBound, maxBound);
  12163. const newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  12164. if (snap && newValue >= min && newValue <= max) {
  12165. return snapValueOf(newValue, min, max, step, snapStart);
  12166. } else if (rounded) {
  12167. return Math.round(newValue);
  12168. } else {
  12169. return newValue;
  12170. }
  12171. }
  12172. };
  12173. const findOffsetOfValue$2 = args => {
  12174. const {min, max, range, value, hasMinEdge, hasMaxEdge, maxBound, maxOffset, centerMinEdge, centerMaxEdge} = args;
  12175. if (value < min) {
  12176. return hasMinEdge ? 0 : centerMinEdge;
  12177. } else if (value > max) {
  12178. return hasMaxEdge ? maxBound : centerMaxEdge;
  12179. } else {
  12180. return (value - min) / range * maxOffset;
  12181. }
  12182. };
  12183. const top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  12184. const getBounds = component => component.element.dom.getBoundingClientRect();
  12185. const getBoundsProperty = (bounds, property) => bounds[property];
  12186. const getMinXBounds = component => {
  12187. const bounds = getBounds(component);
  12188. return getBoundsProperty(bounds, left);
  12189. };
  12190. const getMaxXBounds = component => {
  12191. const bounds = getBounds(component);
  12192. return getBoundsProperty(bounds, right);
  12193. };
  12194. const getMinYBounds = component => {
  12195. const bounds = getBounds(component);
  12196. return getBoundsProperty(bounds, top);
  12197. };
  12198. const getMaxYBounds = component => {
  12199. const bounds = getBounds(component);
  12200. return getBoundsProperty(bounds, bottom);
  12201. };
  12202. const getXScreenRange = component => {
  12203. const bounds = getBounds(component);
  12204. return getBoundsProperty(bounds, width);
  12205. };
  12206. const getYScreenRange = component => {
  12207. const bounds = getBounds(component);
  12208. return getBoundsProperty(bounds, height);
  12209. };
  12210. const getCenterOffsetOf = (componentMinEdge, componentMaxEdge, spectrumMinEdge) => (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  12211. const getXCenterOffSetOf = (component, spectrum) => {
  12212. const componentBounds = getBounds(component);
  12213. const spectrumBounds = getBounds(spectrum);
  12214. const componentMinEdge = getBoundsProperty(componentBounds, left);
  12215. const componentMaxEdge = getBoundsProperty(componentBounds, right);
  12216. const spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  12217. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  12218. };
  12219. const getYCenterOffSetOf = (component, spectrum) => {
  12220. const componentBounds = getBounds(component);
  12221. const spectrumBounds = getBounds(spectrum);
  12222. const componentMinEdge = getBoundsProperty(componentBounds, top);
  12223. const componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  12224. const spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  12225. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  12226. };
  12227. const fireSliderChange$2 = (spectrum, value) => {
  12228. emitWith(spectrum, sliderChangeEvent(), { value });
  12229. };
  12230. const findValueOfOffset$1 = (spectrum, detail, left) => {
  12231. const args = {
  12232. min: minX(detail),
  12233. max: maxX(detail),
  12234. range: xRange(detail),
  12235. value: left,
  12236. step: step(detail),
  12237. snap: snap(detail),
  12238. snapStart: snapStart(detail),
  12239. rounded: rounded(detail),
  12240. hasMinEdge: hasLEdge(detail),
  12241. hasMaxEdge: hasREdge(detail),
  12242. minBound: getMinXBounds(spectrum),
  12243. maxBound: getMaxXBounds(spectrum),
  12244. screenRange: getXScreenRange(spectrum)
  12245. };
  12246. return findValueOf(args);
  12247. };
  12248. const setValueFrom$2 = (spectrum, detail, value) => {
  12249. const xValue = findValueOfOffset$1(spectrum, detail, value);
  12250. const sliderVal = xValue;
  12251. fireSliderChange$2(spectrum, sliderVal);
  12252. return xValue;
  12253. };
  12254. const setToMin$2 = (spectrum, detail) => {
  12255. const min = minX(detail);
  12256. fireSliderChange$2(spectrum, min);
  12257. };
  12258. const setToMax$2 = (spectrum, detail) => {
  12259. const max = maxX(detail);
  12260. fireSliderChange$2(spectrum, max);
  12261. };
  12262. const moveBy$2 = (direction, spectrum, detail) => {
  12263. const f = direction > 0 ? increaseBy : reduceBy;
  12264. const xValue = f(currentValue(detail), minX(detail), maxX(detail), step(detail));
  12265. fireSliderChange$2(spectrum, xValue);
  12266. return Optional.some(xValue);
  12267. };
  12268. const handleMovement$2 = direction => (spectrum, detail) => moveBy$2(direction, spectrum, detail).map(always);
  12269. const getValueFromEvent$2 = simulatedEvent => {
  12270. const pos = getEventSource(simulatedEvent);
  12271. return pos.map(p => p.left);
  12272. };
  12273. const findOffsetOfValue$1 = (spectrum, detail, value, minEdge, maxEdge) => {
  12274. const minOffset = 0;
  12275. const maxOffset = getXScreenRange(spectrum);
  12276. const centerMinEdge = minEdge.bind(edge => Optional.some(getXCenterOffSetOf(edge, spectrum))).getOr(minOffset);
  12277. const centerMaxEdge = maxEdge.bind(edge => Optional.some(getXCenterOffSetOf(edge, spectrum))).getOr(maxOffset);
  12278. const args = {
  12279. min: minX(detail),
  12280. max: maxX(detail),
  12281. range: xRange(detail),
  12282. value,
  12283. hasMinEdge: hasLEdge(detail),
  12284. hasMaxEdge: hasREdge(detail),
  12285. minBound: getMinXBounds(spectrum),
  12286. minOffset,
  12287. maxBound: getMaxXBounds(spectrum),
  12288. maxOffset,
  12289. centerMinEdge,
  12290. centerMaxEdge
  12291. };
  12292. return findOffsetOfValue$2(args);
  12293. };
  12294. const findPositionOfValue$1 = (slider, spectrum, value, minEdge, maxEdge, detail) => {
  12295. const offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  12296. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  12297. };
  12298. const setPositionFromValue$2 = (slider, thumb, detail, edges) => {
  12299. const value = currentValue(detail);
  12300. const pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  12301. const thumbRadius = get$c(thumb.element) / 2;
  12302. set$8(thumb.element, 'left', pos - thumbRadius + 'px');
  12303. };
  12304. const onLeft$2 = handleMovement$2(-1);
  12305. const onRight$2 = handleMovement$2(1);
  12306. const onUp$2 = Optional.none;
  12307. const onDown$2 = Optional.none;
  12308. const edgeActions$2 = {
  12309. 'top-left': Optional.none(),
  12310. 'top': Optional.none(),
  12311. 'top-right': Optional.none(),
  12312. 'right': Optional.some(setToREdge),
  12313. 'bottom-right': Optional.none(),
  12314. 'bottom': Optional.none(),
  12315. 'bottom-left': Optional.none(),
  12316. 'left': Optional.some(setToLEdge)
  12317. };
  12318. var HorizontalModel = /*#__PURE__*/Object.freeze({
  12319. __proto__: null,
  12320. setValueFrom: setValueFrom$2,
  12321. setToMin: setToMin$2,
  12322. setToMax: setToMax$2,
  12323. findValueOfOffset: findValueOfOffset$1,
  12324. getValueFromEvent: getValueFromEvent$2,
  12325. findPositionOfValue: findPositionOfValue$1,
  12326. setPositionFromValue: setPositionFromValue$2,
  12327. onLeft: onLeft$2,
  12328. onRight: onRight$2,
  12329. onUp: onUp$2,
  12330. onDown: onDown$2,
  12331. edgeActions: edgeActions$2
  12332. });
  12333. const fireSliderChange$1 = (spectrum, value) => {
  12334. emitWith(spectrum, sliderChangeEvent(), { value });
  12335. };
  12336. const findValueOfOffset = (spectrum, detail, top) => {
  12337. const args = {
  12338. min: minY(detail),
  12339. max: maxY(detail),
  12340. range: yRange(detail),
  12341. value: top,
  12342. step: step(detail),
  12343. snap: snap(detail),
  12344. snapStart: snapStart(detail),
  12345. rounded: rounded(detail),
  12346. hasMinEdge: hasTEdge(detail),
  12347. hasMaxEdge: hasBEdge(detail),
  12348. minBound: getMinYBounds(spectrum),
  12349. maxBound: getMaxYBounds(spectrum),
  12350. screenRange: getYScreenRange(spectrum)
  12351. };
  12352. return findValueOf(args);
  12353. };
  12354. const setValueFrom$1 = (spectrum, detail, value) => {
  12355. const yValue = findValueOfOffset(spectrum, detail, value);
  12356. const sliderVal = yValue;
  12357. fireSliderChange$1(spectrum, sliderVal);
  12358. return yValue;
  12359. };
  12360. const setToMin$1 = (spectrum, detail) => {
  12361. const min = minY(detail);
  12362. fireSliderChange$1(spectrum, min);
  12363. };
  12364. const setToMax$1 = (spectrum, detail) => {
  12365. const max = maxY(detail);
  12366. fireSliderChange$1(spectrum, max);
  12367. };
  12368. const moveBy$1 = (direction, spectrum, detail) => {
  12369. const f = direction > 0 ? increaseBy : reduceBy;
  12370. const yValue = f(currentValue(detail), minY(detail), maxY(detail), step(detail));
  12371. fireSliderChange$1(spectrum, yValue);
  12372. return Optional.some(yValue);
  12373. };
  12374. const handleMovement$1 = direction => (spectrum, detail) => moveBy$1(direction, spectrum, detail).map(always);
  12375. const getValueFromEvent$1 = simulatedEvent => {
  12376. const pos = getEventSource(simulatedEvent);
  12377. return pos.map(p => {
  12378. return p.top;
  12379. });
  12380. };
  12381. const findOffsetOfValue = (spectrum, detail, value, minEdge, maxEdge) => {
  12382. const minOffset = 0;
  12383. const maxOffset = getYScreenRange(spectrum);
  12384. const centerMinEdge = minEdge.bind(edge => Optional.some(getYCenterOffSetOf(edge, spectrum))).getOr(minOffset);
  12385. const centerMaxEdge = maxEdge.bind(edge => Optional.some(getYCenterOffSetOf(edge, spectrum))).getOr(maxOffset);
  12386. const args = {
  12387. min: minY(detail),
  12388. max: maxY(detail),
  12389. range: yRange(detail),
  12390. value,
  12391. hasMinEdge: hasTEdge(detail),
  12392. hasMaxEdge: hasBEdge(detail),
  12393. minBound: getMinYBounds(spectrum),
  12394. minOffset,
  12395. maxBound: getMaxYBounds(spectrum),
  12396. maxOffset,
  12397. centerMinEdge,
  12398. centerMaxEdge
  12399. };
  12400. return findOffsetOfValue$2(args);
  12401. };
  12402. const findPositionOfValue = (slider, spectrum, value, minEdge, maxEdge, detail) => {
  12403. const offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  12404. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  12405. };
  12406. const setPositionFromValue$1 = (slider, thumb, detail, edges) => {
  12407. const value = currentValue(detail);
  12408. const pos = findPositionOfValue(slider, edges.getSpectrum(slider), value, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  12409. const thumbRadius = get$d(thumb.element) / 2;
  12410. set$8(thumb.element, 'top', pos - thumbRadius + 'px');
  12411. };
  12412. const onLeft$1 = Optional.none;
  12413. const onRight$1 = Optional.none;
  12414. const onUp$1 = handleMovement$1(-1);
  12415. const onDown$1 = handleMovement$1(1);
  12416. const edgeActions$1 = {
  12417. 'top-left': Optional.none(),
  12418. 'top': Optional.some(setToTEdge),
  12419. 'top-right': Optional.none(),
  12420. 'right': Optional.none(),
  12421. 'bottom-right': Optional.none(),
  12422. 'bottom': Optional.some(setToBEdge),
  12423. 'bottom-left': Optional.none(),
  12424. 'left': Optional.none()
  12425. };
  12426. var VerticalModel = /*#__PURE__*/Object.freeze({
  12427. __proto__: null,
  12428. setValueFrom: setValueFrom$1,
  12429. setToMin: setToMin$1,
  12430. setToMax: setToMax$1,
  12431. findValueOfOffset: findValueOfOffset,
  12432. getValueFromEvent: getValueFromEvent$1,
  12433. findPositionOfValue: findPositionOfValue,
  12434. setPositionFromValue: setPositionFromValue$1,
  12435. onLeft: onLeft$1,
  12436. onRight: onRight$1,
  12437. onUp: onUp$1,
  12438. onDown: onDown$1,
  12439. edgeActions: edgeActions$1
  12440. });
  12441. const fireSliderChange = (spectrum, value) => {
  12442. emitWith(spectrum, sliderChangeEvent(), { value });
  12443. };
  12444. const sliderValue = (x, y) => ({
  12445. x,
  12446. y
  12447. });
  12448. const setValueFrom = (spectrum, detail, value) => {
  12449. const xValue = findValueOfOffset$1(spectrum, detail, value.left);
  12450. const yValue = findValueOfOffset(spectrum, detail, value.top);
  12451. const val = sliderValue(xValue, yValue);
  12452. fireSliderChange(spectrum, val);
  12453. return val;
  12454. };
  12455. const moveBy = (direction, isVerticalMovement, spectrum, detail) => {
  12456. const f = direction > 0 ? increaseBy : reduceBy;
  12457. const xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  12458. const yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  12459. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  12460. return Optional.some(xValue);
  12461. };
  12462. const handleMovement = (direction, isVerticalMovement) => (spectrum, detail) => moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  12463. const setToMin = (spectrum, detail) => {
  12464. const mX = minX(detail);
  12465. const mY = minY(detail);
  12466. fireSliderChange(spectrum, sliderValue(mX, mY));
  12467. };
  12468. const setToMax = (spectrum, detail) => {
  12469. const mX = maxX(detail);
  12470. const mY = maxY(detail);
  12471. fireSliderChange(spectrum, sliderValue(mX, mY));
  12472. };
  12473. const getValueFromEvent = simulatedEvent => getEventSource(simulatedEvent);
  12474. const setPositionFromValue = (slider, thumb, detail, edges) => {
  12475. const value = currentValue(detail);
  12476. const xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  12477. const yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  12478. const thumbXRadius = get$c(thumb.element) / 2;
  12479. const thumbYRadius = get$d(thumb.element) / 2;
  12480. set$8(thumb.element, 'left', xPos - thumbXRadius + 'px');
  12481. set$8(thumb.element, 'top', yPos - thumbYRadius + 'px');
  12482. };
  12483. const onLeft = handleMovement(-1, false);
  12484. const onRight = handleMovement(1, false);
  12485. const onUp = handleMovement(-1, true);
  12486. const onDown = handleMovement(1, true);
  12487. const edgeActions = {
  12488. 'top-left': Optional.some(setToTLEdgeXY),
  12489. 'top': Optional.some(setToTEdgeXY),
  12490. 'top-right': Optional.some(setToTREdgeXY),
  12491. 'right': Optional.some(setToREdgeXY),
  12492. 'bottom-right': Optional.some(setToBREdgeXY),
  12493. 'bottom': Optional.some(setToBEdgeXY),
  12494. 'bottom-left': Optional.some(setToBLEdgeXY),
  12495. 'left': Optional.some(setToLEdgeXY)
  12496. };
  12497. var TwoDModel = /*#__PURE__*/Object.freeze({
  12498. __proto__: null,
  12499. setValueFrom: setValueFrom,
  12500. setToMin: setToMin,
  12501. setToMax: setToMax,
  12502. getValueFromEvent: getValueFromEvent,
  12503. setPositionFromValue: setPositionFromValue,
  12504. onLeft: onLeft,
  12505. onRight: onRight,
  12506. onUp: onUp,
  12507. onDown: onDown,
  12508. edgeActions: edgeActions
  12509. });
  12510. const SliderSchema = [
  12511. defaulted('stepSize', 1),
  12512. defaulted('onChange', noop),
  12513. defaulted('onChoose', noop),
  12514. defaulted('onInit', noop),
  12515. defaulted('onDragStart', noop),
  12516. defaulted('onDragEnd', noop),
  12517. defaulted('snapToGrid', false),
  12518. defaulted('rounded', true),
  12519. option$3('snapStart'),
  12520. requiredOf('model', choose$1('mode', {
  12521. x: [
  12522. defaulted('minX', 0),
  12523. defaulted('maxX', 100),
  12524. customField('value', spec => Cell(spec.mode.minX)),
  12525. required$1('getInitialValue'),
  12526. output$1('manager', HorizontalModel)
  12527. ],
  12528. y: [
  12529. defaulted('minY', 0),
  12530. defaulted('maxY', 100),
  12531. customField('value', spec => Cell(spec.mode.minY)),
  12532. required$1('getInitialValue'),
  12533. output$1('manager', VerticalModel)
  12534. ],
  12535. xy: [
  12536. defaulted('minX', 0),
  12537. defaulted('maxX', 100),
  12538. defaulted('minY', 0),
  12539. defaulted('maxY', 100),
  12540. customField('value', spec => Cell({
  12541. x: spec.mode.minX,
  12542. y: spec.mode.minY
  12543. })),
  12544. required$1('getInitialValue'),
  12545. output$1('manager', TwoDModel)
  12546. ]
  12547. })),
  12548. field('sliderBehaviours', [
  12549. Keying,
  12550. Representing
  12551. ]),
  12552. customField('mouseIsDown', () => Cell(false))
  12553. ];
  12554. const sketch$2 = (detail, components, _spec, _externals) => {
  12555. const getThumb = component => getPartOrDie(component, detail, 'thumb');
  12556. const getSpectrum = component => getPartOrDie(component, detail, 'spectrum');
  12557. const getLeftEdge = component => getPart(component, detail, 'left-edge');
  12558. const getRightEdge = component => getPart(component, detail, 'right-edge');
  12559. const getTopEdge = component => getPart(component, detail, 'top-edge');
  12560. const getBottomEdge = component => getPart(component, detail, 'bottom-edge');
  12561. const modelDetail = detail.model;
  12562. const model = modelDetail.manager;
  12563. const refresh = (slider, thumb) => {
  12564. model.setPositionFromValue(slider, thumb, detail, {
  12565. getLeftEdge,
  12566. getRightEdge,
  12567. getTopEdge,
  12568. getBottomEdge,
  12569. getSpectrum
  12570. });
  12571. };
  12572. const setValue = (slider, newValue) => {
  12573. modelDetail.value.set(newValue);
  12574. const thumb = getThumb(slider);
  12575. refresh(slider, thumb);
  12576. };
  12577. const changeValue = (slider, newValue) => {
  12578. setValue(slider, newValue);
  12579. const thumb = getThumb(slider);
  12580. detail.onChange(slider, thumb, newValue);
  12581. return Optional.some(true);
  12582. };
  12583. const resetToMin = slider => {
  12584. model.setToMin(slider, detail);
  12585. };
  12586. const resetToMax = slider => {
  12587. model.setToMax(slider, detail);
  12588. };
  12589. const choose = slider => {
  12590. const fireOnChoose = () => {
  12591. getPart(slider, detail, 'thumb').each(thumb => {
  12592. const value = modelDetail.value.get();
  12593. detail.onChoose(slider, thumb, value);
  12594. });
  12595. };
  12596. const wasDown = detail.mouseIsDown.get();
  12597. detail.mouseIsDown.set(false);
  12598. if (wasDown) {
  12599. fireOnChoose();
  12600. }
  12601. };
  12602. const onDragStart = (slider, simulatedEvent) => {
  12603. simulatedEvent.stop();
  12604. detail.mouseIsDown.set(true);
  12605. detail.onDragStart(slider, getThumb(slider));
  12606. };
  12607. const onDragEnd = (slider, simulatedEvent) => {
  12608. simulatedEvent.stop();
  12609. detail.onDragEnd(slider, getThumb(slider));
  12610. choose(slider);
  12611. };
  12612. return {
  12613. uid: detail.uid,
  12614. dom: detail.dom,
  12615. components,
  12616. behaviours: augment(detail.sliderBehaviours, [
  12617. Keying.config({
  12618. mode: 'special',
  12619. focusIn: slider => {
  12620. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  12621. }
  12622. }),
  12623. Representing.config({
  12624. store: {
  12625. mode: 'manual',
  12626. getValue: _ => {
  12627. return modelDetail.value.get();
  12628. },
  12629. setValue
  12630. }
  12631. }),
  12632. Receiving.config({ channels: { [mouseReleased()]: { onReceive: choose } } })
  12633. ]),
  12634. events: derive$2([
  12635. run$1(sliderChangeEvent(), (slider, simulatedEvent) => {
  12636. changeValue(slider, simulatedEvent.event.value);
  12637. }),
  12638. runOnAttached((slider, _simulatedEvent) => {
  12639. const getInitial = modelDetail.getInitialValue();
  12640. modelDetail.value.set(getInitial);
  12641. const thumb = getThumb(slider);
  12642. refresh(slider, thumb);
  12643. const spectrum = getSpectrum(slider);
  12644. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  12645. }),
  12646. run$1(touchstart(), onDragStart),
  12647. run$1(touchend(), onDragEnd),
  12648. run$1(mousedown(), onDragStart),
  12649. run$1(mouseup(), onDragEnd)
  12650. ]),
  12651. apis: {
  12652. resetToMin,
  12653. resetToMax,
  12654. setValue,
  12655. refresh
  12656. },
  12657. domModification: { styles: { position: 'relative' } }
  12658. };
  12659. };
  12660. const Slider = composite({
  12661. name: 'Slider',
  12662. configFields: SliderSchema,
  12663. partFields: SliderParts,
  12664. factory: sketch$2,
  12665. apis: {
  12666. setValue: (apis, slider, value) => {
  12667. apis.setValue(slider, value);
  12668. },
  12669. resetToMin: (apis, slider) => {
  12670. apis.resetToMin(slider);
  12671. },
  12672. resetToMax: (apis, slider) => {
  12673. apis.resetToMax(slider);
  12674. },
  12675. refresh: (apis, slider) => {
  12676. apis.refresh(slider);
  12677. }
  12678. }
  12679. });
  12680. const fieldsUpdate = generate$6('rgb-hex-update');
  12681. const sliderUpdate = generate$6('slider-update');
  12682. const paletteUpdate = generate$6('palette-update');
  12683. const sliderFactory = (translate, getClass) => {
  12684. const spectrum = Slider.parts.spectrum({
  12685. dom: {
  12686. tag: 'div',
  12687. classes: [getClass('hue-slider-spectrum')],
  12688. attributes: { role: 'presentation' }
  12689. }
  12690. });
  12691. const thumb = Slider.parts.thumb({
  12692. dom: {
  12693. tag: 'div',
  12694. classes: [getClass('hue-slider-thumb')],
  12695. attributes: { role: 'presentation' }
  12696. }
  12697. });
  12698. return Slider.sketch({
  12699. dom: {
  12700. tag: 'div',
  12701. classes: [getClass('hue-slider')],
  12702. attributes: { role: 'presentation' }
  12703. },
  12704. rounded: false,
  12705. model: {
  12706. mode: 'y',
  12707. getInitialValue: constant$1(0)
  12708. },
  12709. components: [
  12710. spectrum,
  12711. thumb
  12712. ],
  12713. sliderBehaviours: derive$1([Focusing.config({})]),
  12714. onChange: (slider, _thumb, value) => {
  12715. emitWith(slider, sliderUpdate, { value });
  12716. }
  12717. });
  12718. };
  12719. const owner$1 = 'form';
  12720. const schema$i = [field('formBehaviours', [Representing])];
  12721. const getPartName$1 = name => '<alloy.field.' + name + '>';
  12722. const sketch$1 = fSpec => {
  12723. const parts = (() => {
  12724. const record = [];
  12725. const field = (name, config) => {
  12726. record.push(name);
  12727. return generateOne$1(owner$1, getPartName$1(name), config);
  12728. };
  12729. return {
  12730. field,
  12731. record: constant$1(record)
  12732. };
  12733. })();
  12734. const spec = fSpec(parts);
  12735. const partNames = parts.record();
  12736. const fieldParts = map$2(partNames, n => required({
  12737. name: n,
  12738. pname: getPartName$1(n)
  12739. }));
  12740. return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
  12741. };
  12742. const toResult = (o, e) => o.fold(() => Result.error(e), Result.value);
  12743. const make$4 = (detail, components) => ({
  12744. uid: detail.uid,
  12745. dom: detail.dom,
  12746. components,
  12747. behaviours: augment(detail.formBehaviours, [Representing.config({
  12748. store: {
  12749. mode: 'manual',
  12750. getValue: form => {
  12751. const resPs = getAllParts(form, detail);
  12752. return map$1(resPs, (resPThunk, pName) => resPThunk().bind(v => {
  12753. const opt = Composing.getCurrent(v);
  12754. return toResult(opt, new Error(`Cannot find a current component to extract the value from for form part '${ pName }': ` + element(v.element)));
  12755. }).map(Representing.getValue));
  12756. },
  12757. setValue: (form, values) => {
  12758. each(values, (newValue, key) => {
  12759. getPart(form, detail, key).each(wrapper => {
  12760. Composing.getCurrent(wrapper).each(field => {
  12761. Representing.setValue(field, newValue);
  12762. });
  12763. });
  12764. });
  12765. }
  12766. }
  12767. })]),
  12768. apis: {
  12769. getField: (form, key) => {
  12770. return getPart(form, detail, key).bind(Composing.getCurrent);
  12771. }
  12772. }
  12773. });
  12774. const Form = {
  12775. getField: makeApi((apis, component, key) => apis.getField(component, key)),
  12776. sketch: sketch$1
  12777. };
  12778. const validInput = generate$6('valid-input');
  12779. const invalidInput = generate$6('invalid-input');
  12780. const validatingInput = generate$6('validating-input');
  12781. const translatePrefix = 'colorcustom.rgb.';
  12782. const rgbFormFactory = (translate, getClass, onValidHexx, onInvalidHexx) => {
  12783. const invalidation = (label, isValid) => Invalidating.config({
  12784. invalidClass: getClass('invalid'),
  12785. notify: {
  12786. onValidate: comp => {
  12787. emitWith(comp, validatingInput, { type: label });
  12788. },
  12789. onValid: comp => {
  12790. emitWith(comp, validInput, {
  12791. type: label,
  12792. value: Representing.getValue(comp)
  12793. });
  12794. },
  12795. onInvalid: comp => {
  12796. emitWith(comp, invalidInput, {
  12797. type: label,
  12798. value: Representing.getValue(comp)
  12799. });
  12800. }
  12801. },
  12802. validator: {
  12803. validate: comp => {
  12804. const value = Representing.getValue(comp);
  12805. const res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  12806. return Future.pure(res);
  12807. },
  12808. validateOnLoad: false
  12809. }
  12810. });
  12811. const renderTextField = (isValid, name, label, description, data) => {
  12812. const helptext = translate(translatePrefix + 'range');
  12813. const pLabel = FormField.parts.label({
  12814. dom: {
  12815. tag: 'label',
  12816. attributes: { 'aria-label': description }
  12817. },
  12818. components: [text$1(label)]
  12819. });
  12820. const pField = FormField.parts.field({
  12821. data,
  12822. factory: Input,
  12823. inputAttributes: {
  12824. type: 'text',
  12825. ...name === 'hex' ? { 'aria-live': 'polite' } : {}
  12826. },
  12827. inputClasses: [getClass('textfield')],
  12828. inputBehaviours: derive$1([
  12829. invalidation(name, isValid),
  12830. Tabstopping.config({})
  12831. ]),
  12832. onSetValue: input => {
  12833. if (Invalidating.isInvalid(input)) {
  12834. const run = Invalidating.run(input);
  12835. run.get(noop);
  12836. }
  12837. }
  12838. });
  12839. const comps = [
  12840. pLabel,
  12841. pField
  12842. ];
  12843. const concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : [];
  12844. const components = comps.concat(concats);
  12845. return {
  12846. dom: {
  12847. tag: 'div',
  12848. attributes: { role: 'presentation' }
  12849. },
  12850. components
  12851. };
  12852. };
  12853. const copyRgbToHex = (form, rgba) => {
  12854. const hex = fromRgba(rgba);
  12855. Form.getField(form, 'hex').each(hexField => {
  12856. if (!Focusing.isFocused(hexField)) {
  12857. Representing.setValue(form, { hex: hex.value });
  12858. }
  12859. });
  12860. return hex;
  12861. };
  12862. const copyRgbToForm = (form, rgb) => {
  12863. const red = rgb.red;
  12864. const green = rgb.green;
  12865. const blue = rgb.blue;
  12866. Representing.setValue(form, {
  12867. red,
  12868. green,
  12869. blue
  12870. });
  12871. };
  12872. const memPreview = record({
  12873. dom: {
  12874. tag: 'div',
  12875. classes: [getClass('rgba-preview')],
  12876. styles: { 'background-color': 'white' },
  12877. attributes: { role: 'presentation' }
  12878. }
  12879. });
  12880. const updatePreview = (anyInSystem, hex) => {
  12881. memPreview.getOpt(anyInSystem).each(preview => {
  12882. set$8(preview.element, 'background-color', '#' + hex.value);
  12883. });
  12884. };
  12885. const factory = () => {
  12886. const state = {
  12887. red: Cell(Optional.some(255)),
  12888. green: Cell(Optional.some(255)),
  12889. blue: Cell(Optional.some(255)),
  12890. hex: Cell(Optional.some('ffffff'))
  12891. };
  12892. const copyHexToRgb = (form, hex) => {
  12893. const rgb = fromHex(hex);
  12894. copyRgbToForm(form, rgb);
  12895. setValueRgb(rgb);
  12896. };
  12897. const get = prop => state[prop].get();
  12898. const set = (prop, value) => {
  12899. state[prop].set(value);
  12900. };
  12901. const getValueRgb = () => get('red').bind(red => get('green').bind(green => get('blue').map(blue => rgbaColour(red, green, blue, 1))));
  12902. const setValueRgb = rgb => {
  12903. const red = rgb.red;
  12904. const green = rgb.green;
  12905. const blue = rgb.blue;
  12906. set('red', Optional.some(red));
  12907. set('green', Optional.some(green));
  12908. set('blue', Optional.some(blue));
  12909. };
  12910. const onInvalidInput = (form, simulatedEvent) => {
  12911. const data = simulatedEvent.event;
  12912. if (data.type !== 'hex') {
  12913. set(data.type, Optional.none());
  12914. } else {
  12915. onInvalidHexx(form);
  12916. }
  12917. };
  12918. const onValidHex = (form, value) => {
  12919. onValidHexx(form);
  12920. const hex = hexColour(value);
  12921. set('hex', Optional.some(value));
  12922. const rgb = fromHex(hex);
  12923. copyRgbToForm(form, rgb);
  12924. setValueRgb(rgb);
  12925. emitWith(form, fieldsUpdate, { hex });
  12926. updatePreview(form, hex);
  12927. };
  12928. const onValidRgb = (form, prop, value) => {
  12929. const val = parseInt(value, 10);
  12930. set(prop, Optional.some(val));
  12931. getValueRgb().each(rgb => {
  12932. const hex = copyRgbToHex(form, rgb);
  12933. emitWith(form, fieldsUpdate, { hex });
  12934. updatePreview(form, hex);
  12935. });
  12936. };
  12937. const isHexInputEvent = data => data.type === 'hex';
  12938. const onValidInput = (form, simulatedEvent) => {
  12939. const data = simulatedEvent.event;
  12940. if (isHexInputEvent(data)) {
  12941. onValidHex(form, data.value);
  12942. } else {
  12943. onValidRgb(form, data.type, data.value);
  12944. }
  12945. };
  12946. const formPartStrings = key => ({
  12947. label: translate(translatePrefix + key + '.label'),
  12948. description: translate(translatePrefix + key + '.description')
  12949. });
  12950. const redStrings = formPartStrings('red');
  12951. const greenStrings = formPartStrings('green');
  12952. const blueStrings = formPartStrings('blue');
  12953. const hexStrings = formPartStrings('hex');
  12954. return deepMerge(Form.sketch(parts => ({
  12955. dom: {
  12956. tag: 'form',
  12957. classes: [getClass('rgb-form')],
  12958. attributes: { 'aria-label': translate('aria.color.picker') }
  12959. },
  12960. components: [
  12961. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  12962. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  12963. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  12964. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  12965. memPreview.asSpec()
  12966. ],
  12967. formBehaviours: derive$1([
  12968. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  12969. config('rgb-form-events', [
  12970. run$1(validInput, onValidInput),
  12971. run$1(invalidInput, onInvalidInput),
  12972. run$1(validatingInput, onInvalidInput)
  12973. ])
  12974. ])
  12975. })), {
  12976. apis: {
  12977. updateHex: (form, hex) => {
  12978. Representing.setValue(form, { hex: hex.value });
  12979. copyHexToRgb(form, hex);
  12980. updatePreview(form, hex);
  12981. }
  12982. }
  12983. });
  12984. };
  12985. const rgbFormSketcher = single({
  12986. factory,
  12987. name: 'RgbForm',
  12988. configFields: [],
  12989. apis: {
  12990. updateHex: (apis, form, hex) => {
  12991. apis.updateHex(form, hex);
  12992. }
  12993. },
  12994. extraApis: {}
  12995. });
  12996. return rgbFormSketcher;
  12997. };
  12998. const paletteFactory = (_translate, getClass) => {
  12999. const spectrumPart = Slider.parts.spectrum({
  13000. dom: {
  13001. tag: 'canvas',
  13002. attributes: { role: 'presentation' },
  13003. classes: [getClass('sv-palette-spectrum')]
  13004. }
  13005. });
  13006. const thumbPart = Slider.parts.thumb({
  13007. dom: {
  13008. tag: 'div',
  13009. attributes: { role: 'presentation' },
  13010. classes: [getClass('sv-palette-thumb')],
  13011. innerHtml: `<div class=${ getClass('sv-palette-inner-thumb') } role="presentation"></div>`
  13012. }
  13013. });
  13014. const setColour = (canvas, rgba) => {
  13015. const {width, height} = canvas;
  13016. const ctx = canvas.getContext('2d');
  13017. if (ctx === null) {
  13018. return;
  13019. }
  13020. ctx.fillStyle = rgba;
  13021. ctx.fillRect(0, 0, width, height);
  13022. const grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  13023. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  13024. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  13025. ctx.fillStyle = grdWhite;
  13026. ctx.fillRect(0, 0, width, height);
  13027. const grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  13028. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  13029. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  13030. ctx.fillStyle = grdBlack;
  13031. ctx.fillRect(0, 0, width, height);
  13032. };
  13033. const setPaletteHue = (slider, hue) => {
  13034. const canvas = slider.components()[0].element.dom;
  13035. const hsv = hsvColour(hue, 100, 100);
  13036. const rgba = fromHsv(hsv);
  13037. setColour(canvas, toString(rgba));
  13038. };
  13039. const setPaletteThumb = (slider, hex) => {
  13040. const hsv = fromRgb(fromHex(hex));
  13041. Slider.setValue(slider, {
  13042. x: hsv.saturation,
  13043. y: 100 - hsv.value
  13044. });
  13045. };
  13046. const factory = _detail => {
  13047. const getInitialValue = constant$1({
  13048. x: 0,
  13049. y: 0
  13050. });
  13051. const onChange = (slider, _thumb, value) => {
  13052. emitWith(slider, paletteUpdate, { value });
  13053. };
  13054. const onInit = (_slider, _thumb, spectrum, _value) => {
  13055. setColour(spectrum.element.dom, toString(red));
  13056. };
  13057. const sliderBehaviours = derive$1([
  13058. Composing.config({ find: Optional.some }),
  13059. Focusing.config({})
  13060. ]);
  13061. return Slider.sketch({
  13062. dom: {
  13063. tag: 'div',
  13064. attributes: { role: 'presentation' },
  13065. classes: [getClass('sv-palette')]
  13066. },
  13067. model: {
  13068. mode: 'xy',
  13069. getInitialValue
  13070. },
  13071. rounded: false,
  13072. components: [
  13073. spectrumPart,
  13074. thumbPart
  13075. ],
  13076. onChange,
  13077. onInit,
  13078. sliderBehaviours
  13079. });
  13080. };
  13081. const saturationBrightnessPaletteSketcher = single({
  13082. factory,
  13083. name: 'SaturationBrightnessPalette',
  13084. configFields: [],
  13085. apis: {
  13086. setHue: (_apis, slider, hue) => {
  13087. setPaletteHue(slider, hue);
  13088. },
  13089. setThumb: (_apis, slider, hex) => {
  13090. setPaletteThumb(slider, hex);
  13091. }
  13092. },
  13093. extraApis: {}
  13094. });
  13095. return saturationBrightnessPaletteSketcher;
  13096. };
  13097. const makeFactory = (translate, getClass) => {
  13098. const factory = detail => {
  13099. const rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  13100. const sbPalette = paletteFactory(translate, getClass);
  13101. const hueSliderToDegrees = hue => (100 - hue) / 100 * 360;
  13102. const hueDegreesToSlider = hue => 100 - hue / 360 * 100;
  13103. const state = {
  13104. paletteRgba: Cell(red),
  13105. paletteHue: Cell(0)
  13106. };
  13107. const memSlider = record(sliderFactory(translate, getClass));
  13108. const memPalette = record(sbPalette.sketch({}));
  13109. const memRgb = record(rgbForm.sketch({}));
  13110. const updatePalette = (anyInSystem, _hex, hue) => {
  13111. memPalette.getOpt(anyInSystem).each(palette => {
  13112. sbPalette.setHue(palette, hue);
  13113. });
  13114. };
  13115. const updateFields = (anyInSystem, hex) => {
  13116. memRgb.getOpt(anyInSystem).each(form => {
  13117. rgbForm.updateHex(form, hex);
  13118. });
  13119. };
  13120. const updateSlider = (anyInSystem, _hex, hue) => {
  13121. memSlider.getOpt(anyInSystem).each(slider => {
  13122. Slider.setValue(slider, hueDegreesToSlider(hue));
  13123. });
  13124. };
  13125. const updatePaletteThumb = (anyInSystem, hex) => {
  13126. memPalette.getOpt(anyInSystem).each(palette => {
  13127. sbPalette.setThumb(palette, hex);
  13128. });
  13129. };
  13130. const updateState = (hex, hue) => {
  13131. const rgba = fromHex(hex);
  13132. state.paletteRgba.set(rgba);
  13133. state.paletteHue.set(hue);
  13134. };
  13135. const runUpdates = (anyInSystem, hex, hue, updates) => {
  13136. updateState(hex, hue);
  13137. each$1(updates, update => {
  13138. update(anyInSystem, hex, hue);
  13139. });
  13140. };
  13141. const onPaletteUpdate = () => {
  13142. const updates = [updateFields];
  13143. return (form, simulatedEvent) => {
  13144. const value = simulatedEvent.event.value;
  13145. const oldHue = state.paletteHue.get();
  13146. const newHsv = hsvColour(oldHue, value.x, 100 - value.y);
  13147. const newHex = hsvToHex(newHsv);
  13148. runUpdates(form, newHex, oldHue, updates);
  13149. };
  13150. };
  13151. const onSliderUpdate = () => {
  13152. const updates = [
  13153. updatePalette,
  13154. updateFields
  13155. ];
  13156. return (form, simulatedEvent) => {
  13157. const hue = hueSliderToDegrees(simulatedEvent.event.value);
  13158. const oldRgb = state.paletteRgba.get();
  13159. const oldHsv = fromRgb(oldRgb);
  13160. const newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value);
  13161. const newHex = hsvToHex(newHsv);
  13162. runUpdates(form, newHex, hue, updates);
  13163. };
  13164. };
  13165. const onFieldsUpdate = () => {
  13166. const updates = [
  13167. updatePalette,
  13168. updateSlider,
  13169. updatePaletteThumb
  13170. ];
  13171. return (form, simulatedEvent) => {
  13172. const hex = simulatedEvent.event.hex;
  13173. const hsv = hexToHsv(hex);
  13174. runUpdates(form, hex, hsv.hue, updates);
  13175. };
  13176. };
  13177. return {
  13178. uid: detail.uid,
  13179. dom: detail.dom,
  13180. components: [
  13181. memPalette.asSpec(),
  13182. memSlider.asSpec(),
  13183. memRgb.asSpec()
  13184. ],
  13185. behaviours: derive$1([
  13186. config('colour-picker-events', [
  13187. run$1(fieldsUpdate, onFieldsUpdate()),
  13188. run$1(paletteUpdate, onPaletteUpdate()),
  13189. run$1(sliderUpdate, onSliderUpdate())
  13190. ]),
  13191. Composing.config({ find: comp => memRgb.getOpt(comp) }),
  13192. Keying.config({ mode: 'acyclic' })
  13193. ])
  13194. };
  13195. };
  13196. const colourPickerSketcher = single({
  13197. name: 'ColourPicker',
  13198. configFields: [
  13199. required$1('dom'),
  13200. defaulted('onValidHex', noop),
  13201. defaulted('onInvalidHex', noop)
  13202. ],
  13203. factory
  13204. });
  13205. return colourPickerSketcher;
  13206. };
  13207. const self = () => Composing.config({ find: Optional.some });
  13208. const memento$1 = mem => Composing.config({ find: mem.getOpt });
  13209. const childAt = index => Composing.config({ find: comp => child$2(comp.element, index).bind(element => comp.getSystem().getByDom(element).toOptional()) });
  13210. const ComposingConfigs = {
  13211. self,
  13212. memento: memento$1,
  13213. childAt
  13214. };
  13215. const processors = objOf([
  13216. defaulted('preprocess', identity),
  13217. defaulted('postprocess', identity)
  13218. ]);
  13219. const memento = (mem, rawProcessors) => {
  13220. const ps = asRawOrDie$1('RepresentingConfigs.memento processors', processors, rawProcessors);
  13221. return Representing.config({
  13222. store: {
  13223. mode: 'manual',
  13224. getValue: comp => {
  13225. const other = mem.get(comp);
  13226. const rawValue = Representing.getValue(other);
  13227. return ps.postprocess(rawValue);
  13228. },
  13229. setValue: (comp, rawValue) => {
  13230. const newValue = ps.preprocess(rawValue);
  13231. const other = mem.get(comp);
  13232. Representing.setValue(other, newValue);
  13233. }
  13234. }
  13235. });
  13236. };
  13237. const withComp = (optInitialValue, getter, setter) => Representing.config({
  13238. store: {
  13239. mode: 'manual',
  13240. ...optInitialValue.map(initialValue => ({ initialValue })).getOr({}),
  13241. getValue: getter,
  13242. setValue: setter
  13243. }
  13244. });
  13245. const withElement = (initialValue, getter, setter) => withComp(initialValue, c => getter(c.element), (c, v) => setter(c.element, v));
  13246. const domValue = optInitialValue => withElement(optInitialValue, get$6, set$5);
  13247. const domHtml = optInitialValue => withElement(optInitialValue, get$9, set$6);
  13248. const memory = initialValue => Representing.config({
  13249. store: {
  13250. mode: 'memory',
  13251. initialValue
  13252. }
  13253. });
  13254. const RepresentingConfigs = {
  13255. memento,
  13256. withElement,
  13257. withComp,
  13258. domValue,
  13259. domHtml,
  13260. memory
  13261. };
  13262. const english = {
  13263. 'colorcustom.rgb.red.label': 'R',
  13264. 'colorcustom.rgb.red.description': 'Red component',
  13265. 'colorcustom.rgb.green.label': 'G',
  13266. 'colorcustom.rgb.green.description': 'Green component',
  13267. 'colorcustom.rgb.blue.label': 'B',
  13268. 'colorcustom.rgb.blue.description': 'Blue component',
  13269. 'colorcustom.rgb.hex.label': '#',
  13270. 'colorcustom.rgb.hex.description': 'Hex color code',
  13271. 'colorcustom.rgb.range': 'Range 0 to 255',
  13272. 'aria.color.picker': 'Color Picker',
  13273. 'aria.input.invalid': 'Invalid input'
  13274. };
  13275. const translate$1 = providerBackstage => key => {
  13276. return providerBackstage.translate(english[key]);
  13277. };
  13278. const renderColorPicker = (_spec, providerBackstage, initialData) => {
  13279. const getClass = key => 'tox-' + key;
  13280. const colourPickerFactory = makeFactory(translate$1(providerBackstage), getClass);
  13281. const onValidHex = form => {
  13282. emitWith(form, formActionEvent, {
  13283. name: 'hex-valid',
  13284. value: true
  13285. });
  13286. };
  13287. const onInvalidHex = form => {
  13288. emitWith(form, formActionEvent, {
  13289. name: 'hex-valid',
  13290. value: false
  13291. });
  13292. };
  13293. const memPicker = record(colourPickerFactory.sketch({
  13294. dom: {
  13295. tag: 'div',
  13296. classes: [getClass('color-picker-container')],
  13297. attributes: { role: 'presentation' }
  13298. },
  13299. onValidHex,
  13300. onInvalidHex
  13301. }));
  13302. return {
  13303. dom: { tag: 'div' },
  13304. components: [memPicker.asSpec()],
  13305. behaviours: derive$1([
  13306. RepresentingConfigs.withComp(initialData, comp => {
  13307. const picker = memPicker.get(comp);
  13308. const optRgbForm = Composing.getCurrent(picker);
  13309. const optHex = optRgbForm.bind(rgbForm => {
  13310. const formValues = Representing.getValue(rgbForm);
  13311. return formValues.hex;
  13312. });
  13313. return optHex.map(hex => '#' + hex).getOr('');
  13314. }, (comp, newValue) => {
  13315. const pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  13316. const m = pattern.exec(newValue);
  13317. const picker = memPicker.get(comp);
  13318. const optRgbForm = Composing.getCurrent(picker);
  13319. optRgbForm.fold(() => {
  13320. console.log('Can not find form');
  13321. }, rgbForm => {
  13322. Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') });
  13323. Form.getField(rgbForm, 'hex').each(hexField => {
  13324. emit(hexField, input());
  13325. });
  13326. });
  13327. }),
  13328. ComposingConfigs.self()
  13329. ])
  13330. };
  13331. };
  13332. var global$2 = tinymce.util.Tools.resolve('tinymce.Resource');
  13333. const isOldCustomEditor = spec => has$2(spec, 'init');
  13334. const renderCustomEditor = spec => {
  13335. const editorApi = value$2();
  13336. const memReplaced = record({ dom: { tag: spec.tag } });
  13337. const initialValue = value$2();
  13338. return {
  13339. dom: {
  13340. tag: 'div',
  13341. classes: ['tox-custom-editor']
  13342. },
  13343. behaviours: derive$1([
  13344. config('custom-editor-events', [runOnAttached(component => {
  13345. memReplaced.getOpt(component).each(ta => {
  13346. (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$2.load(spec.scriptId, spec.scriptUrl).then(init => init(ta.element.dom, spec.settings))).then(ea => {
  13347. initialValue.on(cvalue => {
  13348. ea.setValue(cvalue);
  13349. });
  13350. initialValue.clear();
  13351. editorApi.set(ea);
  13352. });
  13353. });
  13354. })]),
  13355. RepresentingConfigs.withComp(Optional.none(), () => editorApi.get().fold(() => initialValue.get().getOr(''), ed => ed.getValue()), (component, value) => {
  13356. editorApi.get().fold(() => initialValue.set(value), ed => ed.setValue(value));
  13357. }),
  13358. ComposingConfigs.self()
  13359. ]),
  13360. components: [memReplaced.asSpec()]
  13361. };
  13362. };
  13363. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  13364. const filterByExtension = (files, providersBackstage) => {
  13365. const allowedImageFileTypes = global$1.explode(providersBackstage.getOption('images_file_types'));
  13366. const isFileInAllowedTypes = file => exists(allowedImageFileTypes, type => endsWith(file.name.toLowerCase(), `.${ type.toLowerCase() }`));
  13367. return filter$2(from(files), isFileInAllowedTypes);
  13368. };
  13369. const renderDropZone = (spec, providersBackstage, initialData) => {
  13370. const stopper = (_, se) => {
  13371. se.stop();
  13372. };
  13373. const sequence = actions => (comp, se) => {
  13374. each$1(actions, a => {
  13375. a(comp, se);
  13376. });
  13377. };
  13378. const onDrop = (comp, se) => {
  13379. if (!Disabling.isDisabled(comp)) {
  13380. const transferEvent = se.event.raw;
  13381. handleFiles(comp, transferEvent.dataTransfer.files);
  13382. }
  13383. };
  13384. const onSelect = (component, simulatedEvent) => {
  13385. const input = simulatedEvent.event.raw.target;
  13386. handleFiles(component, input.files);
  13387. };
  13388. const handleFiles = (component, files) => {
  13389. Representing.setValue(component, filterByExtension(files, providersBackstage));
  13390. emitWith(component, formChangeEvent, { name: spec.name });
  13391. };
  13392. const memInput = record({
  13393. dom: {
  13394. tag: 'input',
  13395. attributes: {
  13396. type: 'file',
  13397. accept: 'image/*'
  13398. },
  13399. styles: { display: 'none' }
  13400. },
  13401. behaviours: derive$1([config('input-file-events', [
  13402. cutter(click()),
  13403. cutter(tap())
  13404. ])])
  13405. });
  13406. const renderField = s => ({
  13407. uid: s.uid,
  13408. dom: {
  13409. tag: 'div',
  13410. classes: ['tox-dropzone-container']
  13411. },
  13412. behaviours: derive$1([
  13413. RepresentingConfigs.memory(initialData.getOr([])),
  13414. ComposingConfigs.self(),
  13415. Disabling.config({}),
  13416. Toggling.config({
  13417. toggleClass: 'dragenter',
  13418. toggleOnExecute: false
  13419. }),
  13420. config('dropzone-events', [
  13421. run$1('dragenter', sequence([
  13422. stopper,
  13423. Toggling.toggle
  13424. ])),
  13425. run$1('dragleave', sequence([
  13426. stopper,
  13427. Toggling.toggle
  13428. ])),
  13429. run$1('dragover', stopper),
  13430. run$1('drop', sequence([
  13431. stopper,
  13432. onDrop
  13433. ])),
  13434. run$1(change(), onSelect)
  13435. ])
  13436. ]),
  13437. components: [{
  13438. dom: {
  13439. tag: 'div',
  13440. classes: ['tox-dropzone'],
  13441. styles: {}
  13442. },
  13443. components: [
  13444. {
  13445. dom: { tag: 'p' },
  13446. components: [text$1(providersBackstage.translate('Drop an image here'))]
  13447. },
  13448. Button.sketch({
  13449. dom: {
  13450. tag: 'button',
  13451. styles: { position: 'relative' },
  13452. classes: [
  13453. 'tox-button',
  13454. 'tox-button--secondary'
  13455. ]
  13456. },
  13457. components: [
  13458. text$1(providersBackstage.translate('Browse for an image')),
  13459. memInput.asSpec()
  13460. ],
  13461. action: comp => {
  13462. const inputComp = memInput.get(comp);
  13463. inputComp.element.dom.click();
  13464. },
  13465. buttonBehaviours: derive$1([
  13466. Tabstopping.config({}),
  13467. DisablingConfigs.button(providersBackstage.isDisabled),
  13468. receivingConfig()
  13469. ])
  13470. })
  13471. ]
  13472. }]
  13473. });
  13474. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  13475. const pField = FormField.parts.field({ factory: { sketch: renderField } });
  13476. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  13477. };
  13478. const renderGrid = (spec, backstage) => ({
  13479. dom: {
  13480. tag: 'div',
  13481. classes: [
  13482. 'tox-form__grid',
  13483. `tox-form__grid--${ spec.columns }col`
  13484. ]
  13485. },
  13486. components: map$2(spec.items, backstage.interpreter)
  13487. });
  13488. const beforeObject = generate$6('alloy-fake-before-tabstop');
  13489. const afterObject = generate$6('alloy-fake-after-tabstop');
  13490. const craftWithClasses = classes => {
  13491. return {
  13492. dom: {
  13493. tag: 'div',
  13494. styles: {
  13495. width: '1px',
  13496. height: '1px',
  13497. outline: 'none'
  13498. },
  13499. attributes: { tabindex: '0' },
  13500. classes
  13501. },
  13502. behaviours: derive$1([
  13503. Focusing.config({ ignore: true }),
  13504. Tabstopping.config({})
  13505. ])
  13506. };
  13507. };
  13508. const craft = spec => {
  13509. return {
  13510. dom: {
  13511. tag: 'div',
  13512. classes: ['tox-navobj']
  13513. },
  13514. components: [
  13515. craftWithClasses([beforeObject]),
  13516. spec,
  13517. craftWithClasses([afterObject])
  13518. ],
  13519. behaviours: derive$1([ComposingConfigs.childAt(1)])
  13520. };
  13521. };
  13522. const triggerTab = (placeholder, shiftKey) => {
  13523. emitWith(placeholder, keydown(), {
  13524. raw: {
  13525. which: 9,
  13526. shiftKey
  13527. }
  13528. });
  13529. };
  13530. const onFocus = (container, targetComp) => {
  13531. const target = targetComp.element;
  13532. if (has(target, beforeObject)) {
  13533. triggerTab(container, true);
  13534. } else if (has(target, afterObject)) {
  13535. triggerTab(container, false);
  13536. }
  13537. };
  13538. const isPseudoStop = element => {
  13539. return closest(element, [
  13540. '.' + beforeObject,
  13541. '.' + afterObject
  13542. ].join(','), never);
  13543. };
  13544. const getDynamicSource = initialData => {
  13545. const cachedValue = Cell(initialData.getOr(''));
  13546. return {
  13547. getValue: _frameComponent => cachedValue.get(),
  13548. setValue: (frameComponent, html) => {
  13549. if (cachedValue.get() !== html) {
  13550. set$9(frameComponent.element, 'srcdoc', html);
  13551. }
  13552. cachedValue.set(html);
  13553. }
  13554. };
  13555. };
  13556. const renderIFrame = (spec, providersBackstage, initialData) => {
  13557. const isSandbox = spec.sandboxed;
  13558. const attributes = {
  13559. ...spec.label.map(title => ({ title })).getOr({}),
  13560. ...initialData.map(html => ({ srcdoc: html })).getOr({}),
  13561. ...isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {}
  13562. };
  13563. const sourcing = getDynamicSource(initialData);
  13564. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  13565. const factory = newSpec => craft({
  13566. uid: newSpec.uid,
  13567. dom: {
  13568. tag: 'iframe',
  13569. attributes
  13570. },
  13571. behaviours: derive$1([
  13572. Tabstopping.config({}),
  13573. Focusing.config({}),
  13574. RepresentingConfigs.withComp(initialData, sourcing.getValue, sourcing.setValue)
  13575. ])
  13576. });
  13577. const pField = FormField.parts.field({ factory: { sketch: factory } });
  13578. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  13579. };
  13580. const image = image => new Promise((resolve, reject) => {
  13581. const loaded = () => {
  13582. destroy();
  13583. resolve(image);
  13584. };
  13585. const listeners = [
  13586. bind(image, 'load', loaded),
  13587. bind(image, 'error', () => {
  13588. destroy();
  13589. reject('Unable to load data from image: ' + image.dom.src);
  13590. })
  13591. ];
  13592. const destroy = () => each$1(listeners, l => l.unbind());
  13593. if (image.dom.complete) {
  13594. loaded();
  13595. }
  13596. });
  13597. const calculateImagePosition = (panelWidth, panelHeight, imageWidth, imageHeight, zoom) => {
  13598. const width = imageWidth * zoom;
  13599. const height = imageHeight * zoom;
  13600. const left = Math.max(0, panelWidth / 2 - width / 2);
  13601. const top = Math.max(0, panelHeight / 2 - height / 2);
  13602. return {
  13603. left: left.toString() + 'px',
  13604. top: top.toString() + 'px',
  13605. width: width.toString() + 'px',
  13606. height: height.toString() + 'px'
  13607. };
  13608. };
  13609. const zoomToFit = (panel, width, height) => {
  13610. const panelW = get$c(panel);
  13611. const panelH = get$d(panel);
  13612. return Math.min(panelW / width, panelH / height, 1);
  13613. };
  13614. const renderImagePreview = (spec, initialData) => {
  13615. const cachedData = Cell(initialData.getOr({ url: '' }));
  13616. const memImage = record({
  13617. dom: {
  13618. tag: 'img',
  13619. classes: ['tox-imagepreview__image'],
  13620. attributes: initialData.map(data => ({ src: data.url })).getOr({})
  13621. }
  13622. });
  13623. const memContainer = record({
  13624. dom: {
  13625. tag: 'div',
  13626. classes: ['tox-imagepreview__container'],
  13627. attributes: { role: 'presentation' }
  13628. },
  13629. components: [memImage.asSpec()]
  13630. });
  13631. const setValue = (frameComponent, data) => {
  13632. const translatedData = { url: data.url };
  13633. data.zoom.each(z => translatedData.zoom = z);
  13634. data.cachedWidth.each(z => translatedData.cachedWidth = z);
  13635. data.cachedHeight.each(z => translatedData.cachedHeight = z);
  13636. cachedData.set(translatedData);
  13637. const applyFramePositioning = () => {
  13638. const imageWidth = translatedData.cachedWidth;
  13639. const imageHeight = translatedData.cachedHeight;
  13640. if (isUndefined(translatedData.zoom)) {
  13641. const z = zoomToFit(frameComponent.element, imageWidth, imageHeight);
  13642. translatedData.zoom = z;
  13643. }
  13644. const position = calculateImagePosition(get$c(frameComponent.element), get$d(frameComponent.element), imageWidth, imageHeight, translatedData.zoom);
  13645. memContainer.getOpt(frameComponent).each(container => {
  13646. setAll(container.element, position);
  13647. });
  13648. };
  13649. memImage.getOpt(frameComponent).each(imageComponent => {
  13650. const img = imageComponent.element;
  13651. if (data.url !== get$f(img, 'src')) {
  13652. set$9(img, 'src', data.url);
  13653. remove$2(frameComponent.element, 'tox-imagepreview__loaded');
  13654. }
  13655. if (!isUndefined(translatedData.cachedWidth) && !isUndefined(translatedData.cachedHeight)) {
  13656. applyFramePositioning();
  13657. }
  13658. image(img).then(img => {
  13659. if (frameComponent.getSystem().isConnected()) {
  13660. add$2(frameComponent.element, 'tox-imagepreview__loaded');
  13661. translatedData.cachedWidth = img.dom.naturalWidth;
  13662. translatedData.cachedHeight = img.dom.naturalHeight;
  13663. applyFramePositioning();
  13664. }
  13665. });
  13666. });
  13667. };
  13668. const styles = {};
  13669. spec.height.each(h => styles.height = h);
  13670. const fakeValidatedData = initialData.map(d => ({
  13671. url: d.url,
  13672. zoom: Optional.from(d.zoom),
  13673. cachedWidth: Optional.from(d.cachedWidth),
  13674. cachedHeight: Optional.from(d.cachedHeight)
  13675. }));
  13676. return {
  13677. dom: {
  13678. tag: 'div',
  13679. classes: ['tox-imagepreview'],
  13680. styles,
  13681. attributes: { role: 'presentation' }
  13682. },
  13683. components: [memContainer.asSpec()],
  13684. behaviours: derive$1([
  13685. ComposingConfigs.self(),
  13686. RepresentingConfigs.withComp(fakeValidatedData, () => cachedData.get(), setValue)
  13687. ])
  13688. };
  13689. };
  13690. const renderLabel$1 = (spec, backstageShared) => {
  13691. const label = {
  13692. dom: {
  13693. tag: 'label',
  13694. classes: ['tox-label']
  13695. },
  13696. components: [text$1(backstageShared.providers.translate(spec.label))]
  13697. };
  13698. const comps = map$2(spec.items, backstageShared.interpreter);
  13699. return {
  13700. dom: {
  13701. tag: 'div',
  13702. classes: ['tox-form__group']
  13703. },
  13704. components: [
  13705. label,
  13706. ...comps
  13707. ],
  13708. behaviours: derive$1([
  13709. ComposingConfigs.self(),
  13710. Replacing.config({}),
  13711. RepresentingConfigs.domHtml(Optional.none()),
  13712. Keying.config({ mode: 'acyclic' })
  13713. ])
  13714. };
  13715. };
  13716. const internalToolbarButtonExecute = generate$6('toolbar.button.execute');
  13717. const onToolbarButtonExecute = info => runOnExecute$1((comp, _simulatedEvent) => {
  13718. runWithApi(info, comp)(itemApi => {
  13719. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  13720. info.onAction(itemApi);
  13721. });
  13722. });
  13723. const toolbarButtonEventOrder = {
  13724. [execute$5()]: [
  13725. 'disabling',
  13726. 'alloy.base.behaviour',
  13727. 'toggling',
  13728. 'toolbar-button-events'
  13729. ]
  13730. };
  13731. const renderIcon = (iconName, iconsProvider, behaviours) => render$3(iconName, {
  13732. tag: 'span',
  13733. classes: [
  13734. 'tox-icon',
  13735. 'tox-tbtn__icon-wrap'
  13736. ],
  13737. behaviours
  13738. }, iconsProvider);
  13739. const renderIconFromPack = (iconName, iconsProvider) => renderIcon(iconName, iconsProvider, []);
  13740. const renderReplacableIconFromPack = (iconName, iconsProvider) => renderIcon(iconName, iconsProvider, [Replacing.config({})]);
  13741. const renderLabel = (text, prefix, providersBackstage) => ({
  13742. dom: {
  13743. tag: 'span',
  13744. classes: [`${ prefix }__select-label`]
  13745. },
  13746. components: [text$1(providersBackstage.translate(text))],
  13747. behaviours: derive$1([Replacing.config({})])
  13748. });
  13749. const updateMenuText = generate$6('update-menu-text');
  13750. const updateMenuIcon = generate$6('update-menu-icon');
  13751. const renderCommonDropdown = (spec, prefix, sharedBackstage) => {
  13752. const editorOffCell = Cell(noop);
  13753. const optMemDisplayText = spec.text.map(text => record(renderLabel(text, prefix, sharedBackstage.providers)));
  13754. const optMemDisplayIcon = spec.icon.map(iconName => record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons)));
  13755. const onLeftOrRightInMenu = (comp, se) => {
  13756. const dropdown = Representing.getValue(comp);
  13757. Focusing.focus(dropdown);
  13758. emitWith(dropdown, 'keydown', { raw: se.event.raw });
  13759. Dropdown.close(dropdown);
  13760. return Optional.some(true);
  13761. };
  13762. const role = spec.role.fold(() => ({}), role => ({ role }));
  13763. const tooltipAttributes = spec.tooltip.fold(() => ({}), tooltip => {
  13764. const translatedTooltip = sharedBackstage.providers.translate(tooltip);
  13765. return {
  13766. 'title': translatedTooltip,
  13767. 'aria-label': translatedTooltip
  13768. };
  13769. });
  13770. const iconSpec = render$3('chevron-down', {
  13771. tag: 'div',
  13772. classes: [`${ prefix }__select-chevron`]
  13773. }, sharedBackstage.providers.icons);
  13774. const memDropdown = record(Dropdown.sketch({
  13775. ...spec.uid ? { uid: spec.uid } : {},
  13776. ...role,
  13777. dom: {
  13778. tag: 'button',
  13779. classes: [
  13780. prefix,
  13781. `${ prefix }--select`
  13782. ].concat(map$2(spec.classes, c => `${ prefix }--${ c }`)),
  13783. attributes: { ...tooltipAttributes }
  13784. },
  13785. components: componentRenderPipeline([
  13786. optMemDisplayIcon.map(mem => mem.asSpec()),
  13787. optMemDisplayText.map(mem => mem.asSpec()),
  13788. Optional.some(iconSpec)
  13789. ]),
  13790. matchWidth: true,
  13791. useMinWidth: true,
  13792. dropdownBehaviours: derive$1([
  13793. ...spec.dropdownBehaviours,
  13794. DisablingConfigs.button(() => spec.disabled || sharedBackstage.providers.isDisabled()),
  13795. receivingConfig(),
  13796. Unselecting.config({}),
  13797. Replacing.config({}),
  13798. config('dropdown-events', [
  13799. onControlAttached(spec, editorOffCell),
  13800. onControlDetached(spec, editorOffCell)
  13801. ]),
  13802. config('menubutton-update-display-text', [
  13803. run$1(updateMenuText, (comp, se) => {
  13804. optMemDisplayText.bind(mem => mem.getOpt(comp)).each(displayText => {
  13805. Replacing.set(displayText, [text$1(sharedBackstage.providers.translate(se.event.text))]);
  13806. });
  13807. }),
  13808. run$1(updateMenuIcon, (comp, se) => {
  13809. optMemDisplayIcon.bind(mem => mem.getOpt(comp)).each(displayIcon => {
  13810. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
  13811. });
  13812. })
  13813. ])
  13814. ]),
  13815. eventOrder: deepMerge(toolbarButtonEventOrder, {
  13816. mousedown: [
  13817. 'focusing',
  13818. 'alloy.base.behaviour',
  13819. 'item-type-events',
  13820. 'normal-dropdown-events'
  13821. ]
  13822. }),
  13823. sandboxBehaviours: derive$1([Keying.config({
  13824. mode: 'special',
  13825. onLeft: onLeftOrRightInMenu,
  13826. onRight: onLeftOrRightInMenu
  13827. })]),
  13828. lazySink: sharedBackstage.getSink,
  13829. toggleClass: `${ prefix }--active`,
  13830. parts: { menu: part(false, spec.columns, spec.presets) },
  13831. fetch: comp => Future.nu(curry(spec.fetch, comp))
  13832. }));
  13833. return memDropdown.asSpec();
  13834. };
  13835. const isMenuItemReference = item => isString(item);
  13836. const isSeparator$1 = item => item.type === 'separator';
  13837. const isExpandingMenuItem = item => has$2(item, 'getSubmenuItems');
  13838. const separator$2 = { type: 'separator' };
  13839. const unwrapReferences = (items, menuItems) => {
  13840. const realItems = foldl(items, (acc, item) => {
  13841. if (isMenuItemReference(item)) {
  13842. if (item === '') {
  13843. return acc;
  13844. } else if (item === '|') {
  13845. return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
  13846. } else if (has$2(menuItems, item.toLowerCase())) {
  13847. return acc.concat([menuItems[item.toLowerCase()]]);
  13848. } else {
  13849. return acc;
  13850. }
  13851. } else {
  13852. return acc.concat([item]);
  13853. }
  13854. }, []);
  13855. if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
  13856. realItems.pop();
  13857. }
  13858. return realItems;
  13859. };
  13860. const getFromExpandingItem = (item, menuItems) => {
  13861. const submenuItems = item.getSubmenuItems();
  13862. const rest = expand(submenuItems, menuItems);
  13863. const newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  13864. const newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  13865. return {
  13866. item,
  13867. menus: newMenus,
  13868. expansions: newExpansions
  13869. };
  13870. };
  13871. const getFromItem = (item, menuItems) => isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  13872. item,
  13873. menus: {},
  13874. expansions: {}
  13875. };
  13876. const generateValueIfRequired = item => {
  13877. if (isSeparator$1(item)) {
  13878. return item;
  13879. } else {
  13880. const itemValue = get$g(item, 'value').getOrThunk(() => generate$6('generated-menu-item'));
  13881. return deepMerge({ value: itemValue }, item);
  13882. }
  13883. };
  13884. const expand = (items, menuItems) => {
  13885. const realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  13886. return foldr(realItems, (acc, item) => {
  13887. const itemWithValue = generateValueIfRequired(item);
  13888. const newData = getFromItem(itemWithValue, menuItems);
  13889. return {
  13890. menus: deepMerge(acc.menus, newData.menus),
  13891. items: [newData.item].concat(acc.items),
  13892. expansions: deepMerge(acc.expansions, newData.expansions)
  13893. };
  13894. }, {
  13895. menus: {},
  13896. expansions: {},
  13897. items: []
  13898. });
  13899. };
  13900. const build = (items, itemResponse, backstage, isHorizontalMenu) => {
  13901. const primary = generate$6('primary-menu');
  13902. const data = expand(items, backstage.shared.providers.menuItems());
  13903. if (data.items.length === 0) {
  13904. return Optional.none();
  13905. }
  13906. const mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  13907. const submenus = map$1(data.menus, (menuItems, menuName) => createPartialMenu(menuName, menuItems, itemResponse, backstage, false));
  13908. const menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  13909. return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
  13910. };
  13911. const isSingleListItem = item => !has$2(item, 'items');
  13912. const dataAttribute = 'data-value';
  13913. const fetchItems = (dropdownComp, name, items, selectedValue) => map$2(items, item => {
  13914. if (!isSingleListItem(item)) {
  13915. return {
  13916. type: 'nestedmenuitem',
  13917. text: item.text,
  13918. getSubmenuItems: () => fetchItems(dropdownComp, name, item.items, selectedValue)
  13919. };
  13920. } else {
  13921. return {
  13922. type: 'togglemenuitem',
  13923. text: item.text,
  13924. value: item.value,
  13925. active: item.value === selectedValue,
  13926. onAction: () => {
  13927. Representing.setValue(dropdownComp, item.value);
  13928. emitWith(dropdownComp, formChangeEvent, { name });
  13929. Focusing.focus(dropdownComp);
  13930. }
  13931. };
  13932. }
  13933. });
  13934. const findItemByValue = (items, value) => findMap(items, item => {
  13935. if (!isSingleListItem(item)) {
  13936. return findItemByValue(item.items, value);
  13937. } else {
  13938. return someIf(item.value === value, item);
  13939. }
  13940. });
  13941. const renderListBox = (spec, backstage, initialData) => {
  13942. const providersBackstage = backstage.shared.providers;
  13943. const initialItem = initialData.bind(value => findItemByValue(spec.items, value)).orThunk(() => head(spec.items).filter(isSingleListItem));
  13944. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  13945. const pField = FormField.parts.field({
  13946. dom: {},
  13947. factory: {
  13948. sketch: sketchSpec => renderCommonDropdown({
  13949. uid: sketchSpec.uid,
  13950. text: initialItem.map(item => item.text),
  13951. icon: Optional.none(),
  13952. tooltip: spec.label,
  13953. role: Optional.none(),
  13954. fetch: (comp, callback) => {
  13955. const items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
  13956. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  13957. },
  13958. onSetup: constant$1(noop),
  13959. getApi: constant$1({}),
  13960. columns: 1,
  13961. presets: 'normal',
  13962. classes: [],
  13963. dropdownBehaviours: [
  13964. Tabstopping.config({}),
  13965. RepresentingConfigs.withComp(initialItem.map(item => item.value), comp => get$f(comp.element, dataAttribute), (comp, data) => {
  13966. findItemByValue(spec.items, data).each(item => {
  13967. set$9(comp.element, dataAttribute, item.value);
  13968. emitWith(comp, updateMenuText, { text: item.text });
  13969. });
  13970. })
  13971. ]
  13972. }, 'tox-listbox', backstage.shared)
  13973. }
  13974. });
  13975. const listBoxWrap = {
  13976. dom: {
  13977. tag: 'div',
  13978. classes: ['tox-listboxfield']
  13979. },
  13980. components: [pField]
  13981. };
  13982. return FormField.sketch({
  13983. dom: {
  13984. tag: 'div',
  13985. classes: ['tox-form__group']
  13986. },
  13987. components: flatten([
  13988. pLabel.toArray(),
  13989. [listBoxWrap]
  13990. ]),
  13991. fieldBehaviours: derive$1([Disabling.config({
  13992. disabled: constant$1(!spec.enabled),
  13993. onDisabled: comp => {
  13994. FormField.getField(comp).each(Disabling.disable);
  13995. },
  13996. onEnabled: comp => {
  13997. FormField.getField(comp).each(Disabling.enable);
  13998. }
  13999. })])
  14000. });
  14001. };
  14002. const renderPanel = (spec, backstage) => ({
  14003. dom: {
  14004. tag: 'div',
  14005. classes: spec.classes
  14006. },
  14007. components: map$2(spec.items, backstage.shared.interpreter)
  14008. });
  14009. const factory$f = (detail, _spec) => {
  14010. const options = map$2(detail.options, option => ({
  14011. dom: {
  14012. tag: 'option',
  14013. value: option.value,
  14014. innerHtml: option.text
  14015. }
  14016. }));
  14017. const initialValues = detail.data.map(v => wrap$1('initialValue', v)).getOr({});
  14018. return {
  14019. uid: detail.uid,
  14020. dom: {
  14021. tag: 'select',
  14022. classes: detail.selectClasses,
  14023. attributes: detail.selectAttributes
  14024. },
  14025. components: options,
  14026. behaviours: augment(detail.selectBehaviours, [
  14027. Focusing.config({}),
  14028. Representing.config({
  14029. store: {
  14030. mode: 'manual',
  14031. getValue: select => {
  14032. return get$6(select.element);
  14033. },
  14034. setValue: (select, newValue) => {
  14035. const found = find$5(detail.options, opt => opt.value === newValue);
  14036. if (found.isSome()) {
  14037. set$5(select.element, newValue);
  14038. }
  14039. },
  14040. ...initialValues
  14041. }
  14042. })
  14043. ])
  14044. };
  14045. };
  14046. const HtmlSelect = single({
  14047. name: 'HtmlSelect',
  14048. configFields: [
  14049. required$1('options'),
  14050. field('selectBehaviours', [
  14051. Focusing,
  14052. Representing
  14053. ]),
  14054. defaulted('selectClasses', []),
  14055. defaulted('selectAttributes', {}),
  14056. option$3('data')
  14057. ],
  14058. factory: factory$f
  14059. });
  14060. const renderSelectBox = (spec, providersBackstage, initialData) => {
  14061. const translatedOptions = map$2(spec.items, item => ({
  14062. text: providersBackstage.translate(item.text),
  14063. value: item.value
  14064. }));
  14065. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  14066. const pField = FormField.parts.field({
  14067. dom: {},
  14068. ...initialData.map(data => ({ data })).getOr({}),
  14069. selectAttributes: { size: spec.size },
  14070. options: translatedOptions,
  14071. factory: HtmlSelect,
  14072. selectBehaviours: derive$1([
  14073. Disabling.config({ disabled: () => !spec.enabled || providersBackstage.isDisabled() }),
  14074. Tabstopping.config({}),
  14075. config('selectbox-change', [run$1(change(), (component, _) => {
  14076. emitWith(component, formChangeEvent, { name: spec.name });
  14077. })])
  14078. ])
  14079. });
  14080. const chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3('chevron-down', {
  14081. tag: 'div',
  14082. classes: ['tox-selectfield__icon-js']
  14083. }, providersBackstage.icons));
  14084. const selectWrap = {
  14085. dom: {
  14086. tag: 'div',
  14087. classes: ['tox-selectfield']
  14088. },
  14089. components: flatten([
  14090. [pField],
  14091. chevron.toArray()
  14092. ])
  14093. };
  14094. return FormField.sketch({
  14095. dom: {
  14096. tag: 'div',
  14097. classes: ['tox-form__group']
  14098. },
  14099. components: flatten([
  14100. pLabel.toArray(),
  14101. [selectWrap]
  14102. ]),
  14103. fieldBehaviours: derive$1([
  14104. Disabling.config({
  14105. disabled: () => !spec.enabled || providersBackstage.isDisabled(),
  14106. onDisabled: comp => {
  14107. FormField.getField(comp).each(Disabling.disable);
  14108. },
  14109. onEnabled: comp => {
  14110. FormField.getField(comp).each(Disabling.enable);
  14111. }
  14112. }),
  14113. receivingConfig()
  14114. ])
  14115. });
  14116. };
  14117. const schema$h = constant$1([
  14118. defaulted('field1Name', 'field1'),
  14119. defaulted('field2Name', 'field2'),
  14120. onStrictHandler('onLockedChange'),
  14121. markers$1(['lockClass']),
  14122. defaulted('locked', false),
  14123. SketchBehaviours.field('coupledFieldBehaviours', [
  14124. Composing,
  14125. Representing
  14126. ])
  14127. ]);
  14128. const getField = (comp, detail, partName) => getPart(comp, detail, partName).bind(Composing.getCurrent);
  14129. const coupledPart = (selfName, otherName) => required({
  14130. factory: FormField,
  14131. name: selfName,
  14132. overrides: detail => {
  14133. return {
  14134. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run$1(input(), me => {
  14135. getField(me, detail, otherName).each(other => {
  14136. getPart(me, detail, 'lock').each(lock => {
  14137. if (Toggling.isOn(lock)) {
  14138. detail.onLockedChange(me, other, lock);
  14139. }
  14140. });
  14141. });
  14142. })])])
  14143. };
  14144. }
  14145. });
  14146. const parts$c = constant$1([
  14147. coupledPart('field1', 'field2'),
  14148. coupledPart('field2', 'field1'),
  14149. required({
  14150. factory: Button,
  14151. schema: [required$1('dom')],
  14152. name: 'lock',
  14153. overrides: detail => {
  14154. return {
  14155. buttonBehaviours: derive$1([Toggling.config({
  14156. selected: detail.locked,
  14157. toggleClass: detail.markers.lockClass,
  14158. aria: { mode: 'pressed' }
  14159. })])
  14160. };
  14161. }
  14162. })
  14163. ]);
  14164. const factory$e = (detail, components, _spec, _externals) => ({
  14165. uid: detail.uid,
  14166. dom: detail.dom,
  14167. components,
  14168. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  14169. Composing.config({ find: Optional.some }),
  14170. Representing.config({
  14171. store: {
  14172. mode: 'manual',
  14173. getValue: comp => {
  14174. const parts = getPartsOrDie(comp, detail, [
  14175. 'field1',
  14176. 'field2'
  14177. ]);
  14178. return {
  14179. [detail.field1Name]: Representing.getValue(parts.field1()),
  14180. [detail.field2Name]: Representing.getValue(parts.field2())
  14181. };
  14182. },
  14183. setValue: (comp, value) => {
  14184. const parts = getPartsOrDie(comp, detail, [
  14185. 'field1',
  14186. 'field2'
  14187. ]);
  14188. if (hasNonNullableKey(value, detail.field1Name)) {
  14189. Representing.setValue(parts.field1(), value[detail.field1Name]);
  14190. }
  14191. if (hasNonNullableKey(value, detail.field2Name)) {
  14192. Representing.setValue(parts.field2(), value[detail.field2Name]);
  14193. }
  14194. }
  14195. }
  14196. })
  14197. ]),
  14198. apis: {
  14199. getField1: component => getPart(component, detail, 'field1'),
  14200. getField2: component => getPart(component, detail, 'field2'),
  14201. getLock: component => getPart(component, detail, 'lock')
  14202. }
  14203. });
  14204. const FormCoupledInputs = composite({
  14205. name: 'FormCoupledInputs',
  14206. configFields: schema$h(),
  14207. partFields: parts$c(),
  14208. factory: factory$e,
  14209. apis: {
  14210. getField1: (apis, component) => apis.getField1(component),
  14211. getField2: (apis, component) => apis.getField2(component),
  14212. getLock: (apis, component) => apis.getLock(component)
  14213. }
  14214. });
  14215. const formatSize = size => {
  14216. const unitDec = {
  14217. '': 0,
  14218. 'px': 0,
  14219. 'pt': 1,
  14220. 'mm': 1,
  14221. 'pc': 2,
  14222. 'ex': 2,
  14223. 'em': 2,
  14224. 'ch': 2,
  14225. 'rem': 2,
  14226. 'cm': 3,
  14227. 'in': 4,
  14228. '%': 4
  14229. };
  14230. const maxDecimal = unit => unit in unitDec ? unitDec[unit] : 1;
  14231. let numText = size.value.toFixed(maxDecimal(size.unit));
  14232. if (numText.indexOf('.') !== -1) {
  14233. numText = numText.replace(/\.?0*$/, '');
  14234. }
  14235. return numText + size.unit;
  14236. };
  14237. const parseSize = sizeText => {
  14238. const numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  14239. const match = numPattern.exec(sizeText);
  14240. if (match !== null) {
  14241. const value = parseFloat(match[1]);
  14242. const unit = match[2];
  14243. return Result.value({
  14244. value,
  14245. unit
  14246. });
  14247. } else {
  14248. return Result.error(sizeText);
  14249. }
  14250. };
  14251. const convertUnit = (size, unit) => {
  14252. const inInch = {
  14253. '': 96,
  14254. 'px': 96,
  14255. 'pt': 72,
  14256. 'cm': 2.54,
  14257. 'pc': 12,
  14258. 'mm': 25.4,
  14259. 'in': 1
  14260. };
  14261. const supported = u => has$2(inInch, u);
  14262. if (size.unit === unit) {
  14263. return Optional.some(size.value);
  14264. } else if (supported(size.unit) && supported(unit)) {
  14265. if (inInch[size.unit] === inInch[unit]) {
  14266. return Optional.some(size.value);
  14267. } else {
  14268. return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
  14269. }
  14270. } else {
  14271. return Optional.none();
  14272. }
  14273. };
  14274. const noSizeConversion = _input => Optional.none();
  14275. const ratioSizeConversion = (scale, unit) => size => convertUnit(size, unit).map(value => ({
  14276. value: value * scale,
  14277. unit
  14278. }));
  14279. const makeRatioConverter = (currentFieldText, otherFieldText) => {
  14280. const cValue = parseSize(currentFieldText).toOptional();
  14281. const oValue = parseSize(otherFieldText).toOptional();
  14282. return lift2(cValue, oValue, (cSize, oSize) => convertUnit(cSize, oSize.unit).map(val => oSize.value / val).map(r => ratioSizeConversion(r, oSize.unit)).getOr(noSizeConversion)).getOr(noSizeConversion);
  14283. };
  14284. const renderSizeInput = (spec, providersBackstage) => {
  14285. let converter = noSizeConversion;
  14286. const ratioEvent = generate$6('ratio-event');
  14287. const makeIcon = iconName => render$3(iconName, {
  14288. tag: 'span',
  14289. classes: [
  14290. 'tox-icon',
  14291. 'tox-lock-icon__' + iconName
  14292. ]
  14293. }, providersBackstage.icons);
  14294. const pLock = FormCoupledInputs.parts.lock({
  14295. dom: {
  14296. tag: 'button',
  14297. classes: [
  14298. 'tox-lock',
  14299. 'tox-button',
  14300. 'tox-button--naked',
  14301. 'tox-button--icon'
  14302. ],
  14303. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  14304. },
  14305. components: [
  14306. makeIcon('lock'),
  14307. makeIcon('unlock')
  14308. ],
  14309. buttonBehaviours: derive$1([
  14310. Disabling.config({ disabled: () => !spec.enabled || providersBackstage.isDisabled() }),
  14311. receivingConfig(),
  14312. Tabstopping.config({})
  14313. ])
  14314. });
  14315. const formGroup = components => ({
  14316. dom: {
  14317. tag: 'div',
  14318. classes: ['tox-form__group']
  14319. },
  14320. components
  14321. });
  14322. const getFieldPart = isField1 => FormField.parts.field({
  14323. factory: Input,
  14324. inputClasses: ['tox-textfield'],
  14325. inputBehaviours: derive$1([
  14326. Disabling.config({ disabled: () => !spec.enabled || providersBackstage.isDisabled() }),
  14327. receivingConfig(),
  14328. Tabstopping.config({}),
  14329. config('size-input-events', [
  14330. run$1(focusin(), (component, _simulatedEvent) => {
  14331. emitWith(component, ratioEvent, { isField1 });
  14332. }),
  14333. run$1(change(), (component, _simulatedEvent) => {
  14334. emitWith(component, formChangeEvent, { name: spec.name });
  14335. })
  14336. ])
  14337. ]),
  14338. selectOnFocus: false
  14339. });
  14340. const getLabel = label => ({
  14341. dom: {
  14342. tag: 'label',
  14343. classes: ['tox-label']
  14344. },
  14345. components: [text$1(providersBackstage.translate(label))]
  14346. });
  14347. const widthField = FormCoupledInputs.parts.field1(formGroup([
  14348. FormField.parts.label(getLabel('Width')),
  14349. getFieldPart(true)
  14350. ]));
  14351. const heightField = FormCoupledInputs.parts.field2(formGroup([
  14352. FormField.parts.label(getLabel('Height')),
  14353. getFieldPart(false)
  14354. ]));
  14355. return FormCoupledInputs.sketch({
  14356. dom: {
  14357. tag: 'div',
  14358. classes: ['tox-form__group']
  14359. },
  14360. components: [{
  14361. dom: {
  14362. tag: 'div',
  14363. classes: ['tox-form__controls-h-stack']
  14364. },
  14365. components: [
  14366. widthField,
  14367. heightField,
  14368. formGroup([
  14369. getLabel(nbsp),
  14370. pLock
  14371. ])
  14372. ]
  14373. }],
  14374. field1Name: 'width',
  14375. field2Name: 'height',
  14376. locked: true,
  14377. markers: { lockClass: 'tox-locked' },
  14378. onLockedChange: (current, other, _lock) => {
  14379. parseSize(Representing.getValue(current)).each(size => {
  14380. converter(size).each(newSize => {
  14381. Representing.setValue(other, formatSize(newSize));
  14382. });
  14383. });
  14384. },
  14385. coupledFieldBehaviours: derive$1([
  14386. Disabling.config({
  14387. disabled: () => !spec.enabled || providersBackstage.isDisabled(),
  14388. onDisabled: comp => {
  14389. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  14390. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  14391. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  14392. },
  14393. onEnabled: comp => {
  14394. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  14395. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  14396. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  14397. }
  14398. }),
  14399. receivingConfig(),
  14400. config('size-input-events2', [run$1(ratioEvent, (component, simulatedEvent) => {
  14401. const isField1 = simulatedEvent.event.isField1;
  14402. const optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  14403. const optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  14404. const value1 = optCurrent.map(Representing.getValue).getOr('');
  14405. const value2 = optOther.map(Representing.getValue).getOr('');
  14406. converter = makeRatioConverter(value1, value2);
  14407. })])
  14408. ])
  14409. });
  14410. };
  14411. const renderSlider = (spec, providerBackstage, initialData) => {
  14412. const labelPart = Slider.parts.label({
  14413. dom: {
  14414. tag: 'label',
  14415. classes: ['tox-label']
  14416. },
  14417. components: [text$1(providerBackstage.translate(spec.label))]
  14418. });
  14419. const spectrum = Slider.parts.spectrum({
  14420. dom: {
  14421. tag: 'div',
  14422. classes: ['tox-slider__rail'],
  14423. attributes: { role: 'presentation' }
  14424. }
  14425. });
  14426. const thumb = Slider.parts.thumb({
  14427. dom: {
  14428. tag: 'div',
  14429. classes: ['tox-slider__handle'],
  14430. attributes: { role: 'presentation' }
  14431. }
  14432. });
  14433. return Slider.sketch({
  14434. dom: {
  14435. tag: 'div',
  14436. classes: ['tox-slider'],
  14437. attributes: { role: 'presentation' }
  14438. },
  14439. model: {
  14440. mode: 'x',
  14441. minX: spec.min,
  14442. maxX: spec.max,
  14443. getInitialValue: constant$1(initialData.getOrThunk(() => (Math.abs(spec.max) - Math.abs(spec.min)) / 2))
  14444. },
  14445. components: [
  14446. labelPart,
  14447. spectrum,
  14448. thumb
  14449. ],
  14450. sliderBehaviours: derive$1([
  14451. ComposingConfigs.self(),
  14452. Focusing.config({})
  14453. ]),
  14454. onChoose: (component, thumb, value) => {
  14455. emitWith(component, formChangeEvent, {
  14456. name: spec.name,
  14457. value
  14458. });
  14459. }
  14460. });
  14461. };
  14462. const renderTable = (spec, providersBackstage) => {
  14463. const renderTh = text => ({
  14464. dom: {
  14465. tag: 'th',
  14466. innerHtml: providersBackstage.translate(text)
  14467. }
  14468. });
  14469. const renderHeader = header => ({
  14470. dom: { tag: 'thead' },
  14471. components: [{
  14472. dom: { tag: 'tr' },
  14473. components: map$2(header, renderTh)
  14474. }]
  14475. });
  14476. const renderTd = text => ({
  14477. dom: {
  14478. tag: 'td',
  14479. innerHtml: providersBackstage.translate(text)
  14480. }
  14481. });
  14482. const renderTr = row => ({
  14483. dom: { tag: 'tr' },
  14484. components: map$2(row, renderTd)
  14485. });
  14486. const renderRows = rows => ({
  14487. dom: { tag: 'tbody' },
  14488. components: map$2(rows, renderTr)
  14489. });
  14490. return {
  14491. dom: {
  14492. tag: 'table',
  14493. classes: ['tox-dialog__table']
  14494. },
  14495. components: [
  14496. renderHeader(spec.header),
  14497. renderRows(spec.cells)
  14498. ],
  14499. behaviours: derive$1([
  14500. Tabstopping.config({}),
  14501. Focusing.config({})
  14502. ])
  14503. };
  14504. };
  14505. const renderTextField = (spec, providersBackstage) => {
  14506. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  14507. const baseInputBehaviours = [
  14508. Disabling.config({ disabled: () => spec.disabled || providersBackstage.isDisabled() }),
  14509. receivingConfig(),
  14510. Keying.config({
  14511. mode: 'execution',
  14512. useEnter: spec.multiline !== true,
  14513. useControlEnter: spec.multiline === true,
  14514. execute: comp => {
  14515. emit(comp, formSubmitEvent);
  14516. return Optional.some(true);
  14517. }
  14518. }),
  14519. config('textfield-change', [
  14520. run$1(input(), (component, _) => {
  14521. emitWith(component, formChangeEvent, { name: spec.name });
  14522. }),
  14523. run$1(postPaste(), (component, _) => {
  14524. emitWith(component, formChangeEvent, { name: spec.name });
  14525. })
  14526. ]),
  14527. Tabstopping.config({})
  14528. ];
  14529. const validatingBehaviours = spec.validation.map(vl => Invalidating.config({
  14530. getRoot: input => {
  14531. return parentElement(input.element);
  14532. },
  14533. invalidClass: 'tox-invalid',
  14534. validator: {
  14535. validate: input => {
  14536. const v = Representing.getValue(input);
  14537. const result = vl.validator(v);
  14538. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  14539. },
  14540. validateOnLoad: vl.validateOnLoad
  14541. }
  14542. })).toArray();
  14543. const placeholder = spec.placeholder.fold(constant$1({}), p => ({ placeholder: providersBackstage.translate(p) }));
  14544. const inputMode = spec.inputMode.fold(constant$1({}), mode => ({ inputmode: mode }));
  14545. const inputAttributes = {
  14546. ...placeholder,
  14547. ...inputMode
  14548. };
  14549. const pField = FormField.parts.field({
  14550. tag: spec.multiline === true ? 'textarea' : 'input',
  14551. ...spec.data.map(data => ({ data })).getOr({}),
  14552. inputAttributes,
  14553. inputClasses: [spec.classname],
  14554. inputBehaviours: derive$1(flatten([
  14555. baseInputBehaviours,
  14556. validatingBehaviours
  14557. ])),
  14558. selectOnFocus: false,
  14559. factory: Input
  14560. });
  14561. const extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  14562. const extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  14563. const extraBehaviours = [
  14564. Disabling.config({
  14565. disabled: () => spec.disabled || providersBackstage.isDisabled(),
  14566. onDisabled: comp => {
  14567. FormField.getField(comp).each(Disabling.disable);
  14568. },
  14569. onEnabled: comp => {
  14570. FormField.getField(comp).each(Disabling.enable);
  14571. }
  14572. }),
  14573. receivingConfig()
  14574. ];
  14575. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  14576. };
  14577. const renderInput = (spec, providersBackstage, initialData) => renderTextField({
  14578. name: spec.name,
  14579. multiline: false,
  14580. label: spec.label,
  14581. inputMode: spec.inputMode,
  14582. placeholder: spec.placeholder,
  14583. flex: false,
  14584. disabled: !spec.enabled,
  14585. classname: 'tox-textfield',
  14586. validation: Optional.none(),
  14587. maximized: spec.maximized,
  14588. data: initialData
  14589. }, providersBackstage);
  14590. const renderTextarea = (spec, providersBackstage, initialData) => renderTextField({
  14591. name: spec.name,
  14592. multiline: true,
  14593. label: spec.label,
  14594. inputMode: Optional.none(),
  14595. placeholder: spec.placeholder,
  14596. flex: true,
  14597. disabled: !spec.enabled,
  14598. classname: 'tox-textarea',
  14599. validation: Optional.none(),
  14600. maximized: spec.maximized,
  14601. data: initialData
  14602. }, providersBackstage);
  14603. const events$6 = (streamConfig, streamState) => {
  14604. const streams = streamConfig.stream.streams;
  14605. const processor = streams.setup(streamConfig, streamState);
  14606. return derive$2([
  14607. run$1(streamConfig.event, processor),
  14608. runOnDetached(() => streamState.cancel())
  14609. ].concat(streamConfig.cancelEvent.map(e => [run$1(e, () => streamState.cancel())]).getOr([])));
  14610. };
  14611. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  14612. __proto__: null,
  14613. events: events$6
  14614. });
  14615. const first = (fn, rate) => {
  14616. let timer = null;
  14617. const cancel = () => {
  14618. if (!isNull(timer)) {
  14619. clearTimeout(timer);
  14620. timer = null;
  14621. }
  14622. };
  14623. const throttle = (...args) => {
  14624. if (isNull(timer)) {
  14625. timer = setTimeout(() => {
  14626. timer = null;
  14627. fn.apply(null, args);
  14628. }, rate);
  14629. }
  14630. };
  14631. return {
  14632. cancel,
  14633. throttle
  14634. };
  14635. };
  14636. const last = (fn, rate) => {
  14637. let timer = null;
  14638. const cancel = () => {
  14639. if (!isNull(timer)) {
  14640. clearTimeout(timer);
  14641. timer = null;
  14642. }
  14643. };
  14644. const throttle = (...args) => {
  14645. cancel();
  14646. timer = setTimeout(() => {
  14647. timer = null;
  14648. fn.apply(null, args);
  14649. }, rate);
  14650. };
  14651. return {
  14652. cancel,
  14653. throttle
  14654. };
  14655. };
  14656. const throttle = _config => {
  14657. const state = Cell(null);
  14658. const readState = () => ({ timer: state.get() !== null ? 'set' : 'unset' });
  14659. const setTimer = t => {
  14660. state.set(t);
  14661. };
  14662. const cancel = () => {
  14663. const t = state.get();
  14664. if (t !== null) {
  14665. t.cancel();
  14666. }
  14667. };
  14668. return nu$8({
  14669. readState,
  14670. setTimer,
  14671. cancel
  14672. });
  14673. };
  14674. const init$9 = spec => spec.stream.streams.state(spec);
  14675. var StreamingState = /*#__PURE__*/Object.freeze({
  14676. __proto__: null,
  14677. throttle: throttle,
  14678. init: init$9
  14679. });
  14680. const setup$c = (streamInfo, streamState) => {
  14681. const sInfo = streamInfo.stream;
  14682. const throttler = last(streamInfo.onStream, sInfo.delay);
  14683. streamState.setTimer(throttler);
  14684. return (component, simulatedEvent) => {
  14685. throttler.throttle(component, simulatedEvent);
  14686. if (sInfo.stopEvent) {
  14687. simulatedEvent.stop();
  14688. }
  14689. };
  14690. };
  14691. var StreamingSchema = [
  14692. requiredOf('stream', choose$1('mode', {
  14693. throttle: [
  14694. required$1('delay'),
  14695. defaulted('stopEvent', true),
  14696. output$1('streams', {
  14697. setup: setup$c,
  14698. state: throttle
  14699. })
  14700. ]
  14701. })),
  14702. defaulted('event', 'input'),
  14703. option$3('cancelEvent'),
  14704. onStrictHandler('onStream')
  14705. ];
  14706. const Streaming = create$3({
  14707. fields: StreamingSchema,
  14708. name: 'streaming',
  14709. active: ActiveStreaming,
  14710. state: StreamingState
  14711. });
  14712. const setValueFromItem = (model, input, item) => {
  14713. const itemData = Representing.getValue(item);
  14714. Representing.setValue(input, itemData);
  14715. setCursorAtEnd(input);
  14716. };
  14717. const setSelectionOn = (input, f) => {
  14718. const el = input.element;
  14719. const value = get$6(el);
  14720. const node = el.dom;
  14721. if (get$f(el, 'type') !== 'number') {
  14722. f(node, value);
  14723. }
  14724. };
  14725. const setCursorAtEnd = input => {
  14726. setSelectionOn(input, (node, value) => node.setSelectionRange(value.length, value.length));
  14727. };
  14728. const setSelectionToEnd = (input, startOffset) => {
  14729. setSelectionOn(input, (node, value) => node.setSelectionRange(startOffset, value.length));
  14730. };
  14731. const attemptSelectOver = (model, input, item) => {
  14732. if (!model.selectsOver) {
  14733. return Optional.none();
  14734. } else {
  14735. const currentValue = Representing.getValue(input);
  14736. const inputDisplay = model.getDisplayText(currentValue);
  14737. const itemValue = Representing.getValue(item);
  14738. const itemDisplay = model.getDisplayText(itemValue);
  14739. return itemDisplay.indexOf(inputDisplay) === 0 ? Optional.some(() => {
  14740. setValueFromItem(model, input, item);
  14741. setSelectionToEnd(input, inputDisplay.length);
  14742. }) : Optional.none();
  14743. }
  14744. };
  14745. const itemExecute = constant$1('alloy.typeahead.itemexecute');
  14746. const make$3 = (detail, components, spec, externals) => {
  14747. const navigateList = (comp, simulatedEvent, highlighter) => {
  14748. detail.previewing.set(false);
  14749. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  14750. if (Sandboxing.isOpen(sandbox)) {
  14751. Composing.getCurrent(sandbox).each(menu => {
  14752. Highlighting.getHighlighted(menu).fold(() => {
  14753. highlighter(menu);
  14754. }, () => {
  14755. dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
  14756. });
  14757. });
  14758. } else {
  14759. const onOpenSync = sandbox => {
  14760. Composing.getCurrent(sandbox).each(highlighter);
  14761. };
  14762. open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  14763. }
  14764. };
  14765. const focusBehaviours$1 = focusBehaviours(detail);
  14766. const mapFetch = comp => tdata => tdata.map(data => {
  14767. const menus = values(data.menus);
  14768. const items = bind$3(menus, menu => filter$2(menu.items, item => item.type === 'item'));
  14769. const repState = Representing.getState(comp);
  14770. repState.update(map$2(items, item => item.data));
  14771. return data;
  14772. });
  14773. const behaviours = [
  14774. Focusing.config({}),
  14775. Representing.config({
  14776. onSetValue: detail.onSetValue,
  14777. store: {
  14778. mode: 'dataset',
  14779. getDataKey: comp => get$6(comp.element),
  14780. getFallbackEntry: itemString => ({
  14781. value: itemString,
  14782. meta: {}
  14783. }),
  14784. setValue: (comp, data) => {
  14785. set$5(comp.element, detail.model.getDisplayText(data));
  14786. },
  14787. ...detail.initialData.map(d => wrap$1('initialValue', d)).getOr({})
  14788. }
  14789. }),
  14790. Streaming.config({
  14791. stream: {
  14792. mode: 'throttle',
  14793. delay: detail.responseTime,
  14794. stopEvent: false
  14795. },
  14796. onStream: (component, _simulatedEvent) => {
  14797. const sandbox = Coupling.getCoupled(component, 'sandbox');
  14798. const focusInInput = Focusing.isFocused(component);
  14799. if (focusInInput) {
  14800. if (get$6(component.element).length >= detail.minChars) {
  14801. const previousValue = Composing.getCurrent(sandbox).bind(menu => Highlighting.getHighlighted(menu).map(Representing.getValue));
  14802. detail.previewing.set(true);
  14803. const onOpenSync = _sandbox => {
  14804. Composing.getCurrent(sandbox).each(menu => {
  14805. previousValue.fold(() => {
  14806. if (detail.model.selectsOver) {
  14807. Highlighting.highlightFirst(menu);
  14808. }
  14809. }, pv => {
  14810. Highlighting.highlightBy(menu, item => {
  14811. const itemData = Representing.getValue(item);
  14812. return itemData.value === pv.value;
  14813. });
  14814. Highlighting.getHighlighted(menu).orThunk(() => {
  14815. Highlighting.highlightFirst(menu);
  14816. return Optional.none();
  14817. });
  14818. });
  14819. });
  14820. };
  14821. open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  14822. }
  14823. }
  14824. },
  14825. cancelEvent: typeaheadCancel()
  14826. }),
  14827. Keying.config({
  14828. mode: 'special',
  14829. onDown: (comp, simulatedEvent) => {
  14830. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  14831. return Optional.some(true);
  14832. },
  14833. onEscape: comp => {
  14834. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  14835. if (Sandboxing.isOpen(sandbox)) {
  14836. Sandboxing.close(sandbox);
  14837. return Optional.some(true);
  14838. }
  14839. return Optional.none();
  14840. },
  14841. onUp: (comp, simulatedEvent) => {
  14842. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  14843. return Optional.some(true);
  14844. },
  14845. onEnter: comp => {
  14846. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  14847. const sandboxIsOpen = Sandboxing.isOpen(sandbox);
  14848. if (sandboxIsOpen && !detail.previewing.get()) {
  14849. return Composing.getCurrent(sandbox).bind(menu => Highlighting.getHighlighted(menu)).map(item => {
  14850. emitWith(comp, itemExecute(), { item });
  14851. return true;
  14852. });
  14853. } else {
  14854. const currentValue = Representing.getValue(comp);
  14855. emit(comp, typeaheadCancel());
  14856. detail.onExecute(sandbox, comp, currentValue);
  14857. if (sandboxIsOpen) {
  14858. Sandboxing.close(sandbox);
  14859. }
  14860. return Optional.some(true);
  14861. }
  14862. }
  14863. }),
  14864. Toggling.config({
  14865. toggleClass: detail.markers.openClass,
  14866. aria: { mode: 'expanded' }
  14867. }),
  14868. Coupling.config({
  14869. others: {
  14870. sandbox: hotspot => {
  14871. return makeSandbox$1(detail, hotspot, {
  14872. onOpen: () => Toggling.on(hotspot),
  14873. onClose: () => Toggling.off(hotspot)
  14874. });
  14875. }
  14876. }
  14877. }),
  14878. config('typeaheadevents', [
  14879. runOnExecute$1(comp => {
  14880. const onOpenSync = noop;
  14881. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  14882. }),
  14883. run$1(itemExecute(), (comp, se) => {
  14884. const sandbox = Coupling.getCoupled(comp, 'sandbox');
  14885. setValueFromItem(detail.model, comp, se.event.item);
  14886. emit(comp, typeaheadCancel());
  14887. detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
  14888. Sandboxing.close(sandbox);
  14889. setCursorAtEnd(comp);
  14890. })
  14891. ].concat(detail.dismissOnBlur ? [run$1(postBlur(), typeahead => {
  14892. const sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  14893. if (search(sandbox.element).isNone()) {
  14894. Sandboxing.close(sandbox);
  14895. }
  14896. })] : []))
  14897. ];
  14898. return {
  14899. uid: detail.uid,
  14900. dom: dom(deepMerge(detail, {
  14901. inputAttributes: {
  14902. 'role': 'combobox',
  14903. 'aria-autocomplete': 'list',
  14904. 'aria-haspopup': 'true'
  14905. }
  14906. })),
  14907. behaviours: {
  14908. ...focusBehaviours$1,
  14909. ...augment(detail.typeaheadBehaviours, behaviours)
  14910. },
  14911. eventOrder: detail.eventOrder
  14912. };
  14913. };
  14914. const schema$g = constant$1([
  14915. option$3('lazySink'),
  14916. required$1('fetch'),
  14917. defaulted('minChars', 5),
  14918. defaulted('responseTime', 1000),
  14919. onHandler('onOpen'),
  14920. defaulted('getHotspot', Optional.some),
  14921. defaulted('getAnchorOverrides', constant$1({})),
  14922. defaulted('layouts', Optional.none()),
  14923. defaulted('eventOrder', {}),
  14924. defaultedObjOf('model', {}, [
  14925. defaulted('getDisplayText', itemData => itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value),
  14926. defaulted('selectsOver', true),
  14927. defaulted('populateFromBrowse', true)
  14928. ]),
  14929. onHandler('onSetValue'),
  14930. onKeyboardHandler('onExecute'),
  14931. onHandler('onItemExecute'),
  14932. defaulted('inputClasses', []),
  14933. defaulted('inputAttributes', {}),
  14934. defaulted('inputStyles', {}),
  14935. defaulted('matchWidth', true),
  14936. defaulted('useMinWidth', false),
  14937. defaulted('dismissOnBlur', true),
  14938. markers$1(['openClass']),
  14939. option$3('initialData'),
  14940. field('typeaheadBehaviours', [
  14941. Focusing,
  14942. Representing,
  14943. Streaming,
  14944. Keying,
  14945. Toggling,
  14946. Coupling
  14947. ]),
  14948. customField('previewing', () => Cell(true))
  14949. ].concat(schema$k()).concat(sandboxFields()));
  14950. const parts$b = constant$1([external({
  14951. schema: [tieredMenuMarkers()],
  14952. name: 'menu',
  14953. overrides: detail => {
  14954. return {
  14955. fakeFocus: true,
  14956. onHighlight: (menu, item) => {
  14957. if (!detail.previewing.get()) {
  14958. menu.getSystem().getByUid(detail.uid).each(input => {
  14959. if (detail.model.populateFromBrowse) {
  14960. setValueFromItem(detail.model, input, item);
  14961. }
  14962. });
  14963. } else {
  14964. menu.getSystem().getByUid(detail.uid).each(input => {
  14965. attemptSelectOver(detail.model, input, item).fold(() => Highlighting.dehighlight(menu, item), fn => fn());
  14966. });
  14967. }
  14968. detail.previewing.set(false);
  14969. },
  14970. onExecute: (menu, item) => {
  14971. return menu.getSystem().getByUid(detail.uid).toOptional().map(typeahead => {
  14972. emitWith(typeahead, itemExecute(), { item });
  14973. return true;
  14974. });
  14975. },
  14976. onHover: (menu, item) => {
  14977. detail.previewing.set(false);
  14978. menu.getSystem().getByUid(detail.uid).each(input => {
  14979. if (detail.model.populateFromBrowse) {
  14980. setValueFromItem(detail.model, input, item);
  14981. }
  14982. });
  14983. }
  14984. };
  14985. }
  14986. })]);
  14987. const Typeahead = composite({
  14988. name: 'Typeahead',
  14989. configFields: schema$g(),
  14990. partFields: parts$b(),
  14991. factory: make$3
  14992. });
  14993. const wrap = delegate => {
  14994. const toCached = () => {
  14995. return wrap(delegate.toCached());
  14996. };
  14997. const bindFuture = f => {
  14998. return wrap(delegate.bind(resA => resA.fold(err => Future.pure(Result.error(err)), a => f(a))));
  14999. };
  15000. const bindResult = f => {
  15001. return wrap(delegate.map(resA => resA.bind(f)));
  15002. };
  15003. const mapResult = f => {
  15004. return wrap(delegate.map(resA => resA.map(f)));
  15005. };
  15006. const mapError = f => {
  15007. return wrap(delegate.map(resA => resA.mapError(f)));
  15008. };
  15009. const foldResult = (whenError, whenValue) => {
  15010. return delegate.map(res => res.fold(whenError, whenValue));
  15011. };
  15012. const withTimeout = (timeout, errorThunk) => {
  15013. return wrap(Future.nu(callback => {
  15014. let timedOut = false;
  15015. const timer = setTimeout(() => {
  15016. timedOut = true;
  15017. callback(Result.error(errorThunk()));
  15018. }, timeout);
  15019. delegate.get(result => {
  15020. if (!timedOut) {
  15021. clearTimeout(timer);
  15022. callback(result);
  15023. }
  15024. });
  15025. }));
  15026. };
  15027. return {
  15028. ...delegate,
  15029. toCached,
  15030. bindFuture,
  15031. bindResult,
  15032. mapResult,
  15033. mapError,
  15034. foldResult,
  15035. withTimeout
  15036. };
  15037. };
  15038. const nu$1 = worker => {
  15039. return wrap(Future.nu(worker));
  15040. };
  15041. const value = value => {
  15042. return wrap(Future.pure(Result.value(value)));
  15043. };
  15044. const error = error => {
  15045. return wrap(Future.pure(Result.error(error)));
  15046. };
  15047. const fromResult = result => {
  15048. return wrap(Future.pure(result));
  15049. };
  15050. const fromFuture = future => {
  15051. return wrap(future.map(Result.value));
  15052. };
  15053. const fromPromise = promise => {
  15054. return nu$1(completer => {
  15055. promise.then(value => {
  15056. completer(Result.value(value));
  15057. }, error => {
  15058. completer(Result.error(error));
  15059. });
  15060. });
  15061. };
  15062. const FutureResult = {
  15063. nu: nu$1,
  15064. wrap,
  15065. pure: value,
  15066. value,
  15067. error,
  15068. fromResult,
  15069. fromFuture,
  15070. fromPromise
  15071. };
  15072. const getMenuButtonApi = component => ({
  15073. isEnabled: () => !Disabling.isDisabled(component),
  15074. setEnabled: state => Disabling.set(component, !state),
  15075. setActive: state => {
  15076. const elm = component.element;
  15077. if (state) {
  15078. add$2(elm, 'tox-tbtn--enabled');
  15079. set$9(elm, 'aria-pressed', true);
  15080. } else {
  15081. remove$2(elm, 'tox-tbtn--enabled');
  15082. remove$7(elm, 'aria-pressed');
  15083. }
  15084. },
  15085. isActive: () => has(component.element, 'tox-tbtn--enabled')
  15086. });
  15087. const renderMenuButton = (spec, prefix, backstage, role) => renderCommonDropdown({
  15088. text: spec.text,
  15089. icon: spec.icon,
  15090. tooltip: spec.tooltip,
  15091. role,
  15092. fetch: (_comp, callback) => {
  15093. spec.fetch(items => {
  15094. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  15095. });
  15096. },
  15097. onSetup: spec.onSetup,
  15098. getApi: getMenuButtonApi,
  15099. columns: 1,
  15100. presets: 'normal',
  15101. classes: [],
  15102. dropdownBehaviours: [Tabstopping.config({})]
  15103. }, prefix, backstage.shared);
  15104. const getFetch = (items, getButton, backstage) => {
  15105. const getMenuItemAction = item => api => {
  15106. const newValue = !api.isActive();
  15107. api.setActive(newValue);
  15108. item.storage.set(newValue);
  15109. backstage.shared.getSink().each(sink => {
  15110. getButton().getOpt(sink).each(orig => {
  15111. focus$3(orig.element);
  15112. emitWith(orig, formActionEvent, {
  15113. name: item.name,
  15114. value: item.storage.get()
  15115. });
  15116. });
  15117. });
  15118. };
  15119. const getMenuItemSetup = item => api => {
  15120. api.setActive(item.storage.get());
  15121. };
  15122. return success => {
  15123. success(map$2(items, item => {
  15124. const text = item.text.fold(() => ({}), text => ({ text }));
  15125. return {
  15126. type: item.type,
  15127. active: false,
  15128. ...text,
  15129. onAction: getMenuItemAction(item),
  15130. onSetup: getMenuItemSetup(item)
  15131. };
  15132. }));
  15133. };
  15134. };
  15135. const renderCommonSpec = (spec, actionOpt, extraBehaviours = [], dom, components, providersBackstage) => {
  15136. const action = actionOpt.fold(() => ({}), action => ({ action }));
  15137. const common = {
  15138. buttonBehaviours: derive$1([
  15139. DisablingConfigs.button(() => !spec.enabled || providersBackstage.isDisabled()),
  15140. receivingConfig(),
  15141. Tabstopping.config({}),
  15142. config('button press', [
  15143. preventDefault('click'),
  15144. preventDefault('mousedown')
  15145. ])
  15146. ].concat(extraBehaviours)),
  15147. eventOrder: {
  15148. click: [
  15149. 'button press',
  15150. 'alloy.base.behaviour'
  15151. ],
  15152. mousedown: [
  15153. 'button press',
  15154. 'alloy.base.behaviour'
  15155. ]
  15156. },
  15157. ...action
  15158. };
  15159. const domFinal = deepMerge(common, { dom });
  15160. return deepMerge(domFinal, { components });
  15161. };
  15162. const renderIconButtonSpec = (spec, action, providersBackstage, extraBehaviours = []) => {
  15163. const tooltipAttributes = spec.tooltip.map(tooltip => ({
  15164. 'aria-label': providersBackstage.translate(tooltip),
  15165. 'title': providersBackstage.translate(tooltip)
  15166. })).getOr({});
  15167. const dom = {
  15168. tag: 'button',
  15169. classes: ['tox-tbtn'],
  15170. attributes: tooltipAttributes
  15171. };
  15172. const icon = spec.icon.map(iconName => renderIconFromPack(iconName, providersBackstage.icons));
  15173. const components = componentRenderPipeline([icon]);
  15174. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  15175. };
  15176. const calculateClassesFromButtonType = buttonType => {
  15177. switch (buttonType) {
  15178. case 'primary':
  15179. return ['tox-button'];
  15180. case 'toolbar':
  15181. return ['tox-tbtn'];
  15182. case 'secondary':
  15183. default:
  15184. return [
  15185. 'tox-button',
  15186. 'tox-button--secondary'
  15187. ];
  15188. }
  15189. };
  15190. const renderButtonSpec = (spec, action, providersBackstage, extraBehaviours = [], extraClasses = []) => {
  15191. const translatedText = providersBackstage.translate(spec.text);
  15192. const icon = spec.icon.map(iconName => renderIconFromPack(iconName, providersBackstage.icons));
  15193. const components = [icon.getOrThunk(() => text$1(translatedText))];
  15194. const buttonType = spec.buttonType.getOr(!spec.primary && !spec.borderless ? 'secondary' : 'primary');
  15195. const baseClasses = calculateClassesFromButtonType(buttonType);
  15196. const classes = [
  15197. ...baseClasses,
  15198. ...icon.isSome() ? ['tox-button--icon'] : [],
  15199. ...spec.borderless ? ['tox-button--naked'] : [],
  15200. ...extraClasses
  15201. ];
  15202. const dom = {
  15203. tag: 'button',
  15204. classes,
  15205. attributes: { title: translatedText }
  15206. };
  15207. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  15208. };
  15209. const renderButton = (spec, action, providersBackstage, extraBehaviours = [], extraClasses = []) => {
  15210. const buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
  15211. return Button.sketch(buttonSpec);
  15212. };
  15213. const getAction = (name, buttonType) => comp => {
  15214. if (buttonType === 'custom') {
  15215. emitWith(comp, formActionEvent, {
  15216. name,
  15217. value: {}
  15218. });
  15219. } else if (buttonType === 'submit') {
  15220. emit(comp, formSubmitEvent);
  15221. } else if (buttonType === 'cancel') {
  15222. emit(comp, formCancelEvent);
  15223. } else {
  15224. console.error('Unknown button type: ', buttonType);
  15225. }
  15226. };
  15227. const isMenuFooterButtonSpec = (spec, buttonType) => buttonType === 'menu';
  15228. const isNormalFooterButtonSpec = (spec, buttonType) => buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  15229. const renderFooterButton = (spec, buttonType, backstage) => {
  15230. if (isMenuFooterButtonSpec(spec, buttonType)) {
  15231. const getButton = () => memButton;
  15232. const menuButtonSpec = spec;
  15233. const fixedSpec = {
  15234. ...spec,
  15235. onSetup: api => {
  15236. api.setEnabled(spec.enabled);
  15237. return noop;
  15238. },
  15239. fetch: getFetch(menuButtonSpec.items, getButton, backstage)
  15240. };
  15241. const memButton = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none()));
  15242. return memButton.asSpec();
  15243. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  15244. const action = getAction(spec.name, buttonType);
  15245. const buttonSpec = {
  15246. ...spec,
  15247. borderless: false
  15248. };
  15249. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  15250. } else {
  15251. console.error('Unknown footer button type: ', buttonType);
  15252. }
  15253. };
  15254. const renderDialogButton = (spec, providersBackstage) => {
  15255. const action = getAction(spec.name, 'custom');
  15256. return renderFormField(Optional.none(), FormField.parts.field({
  15257. factory: Button,
  15258. ...renderButtonSpec(spec, Optional.some(action), providersBackstage, [
  15259. RepresentingConfigs.memory(''),
  15260. ComposingConfigs.self()
  15261. ])
  15262. }));
  15263. };
  15264. const separator$1 = { type: 'separator' };
  15265. const toMenuItem = target => ({
  15266. type: 'menuitem',
  15267. value: target.url,
  15268. text: target.title,
  15269. meta: { attach: target.attach },
  15270. onAction: noop
  15271. });
  15272. const staticMenuItem = (title, url) => ({
  15273. type: 'menuitem',
  15274. value: url,
  15275. text: title,
  15276. meta: { attach: undefined },
  15277. onAction: noop
  15278. });
  15279. const toMenuItems = targets => map$2(targets, toMenuItem);
  15280. const filterLinkTargets = (type, targets) => filter$2(targets, target => target.type === type);
  15281. const filteredTargets = (type, targets) => toMenuItems(filterLinkTargets(type, targets));
  15282. const headerTargets = linkInfo => filteredTargets('header', linkInfo.targets);
  15283. const anchorTargets = linkInfo => filteredTargets('anchor', linkInfo.targets);
  15284. const anchorTargetTop = linkInfo => Optional.from(linkInfo.anchorTop).map(url => staticMenuItem('<top>', url)).toArray();
  15285. const anchorTargetBottom = linkInfo => Optional.from(linkInfo.anchorBottom).map(url => staticMenuItem('<bottom>', url)).toArray();
  15286. const historyTargets = history => map$2(history, url => staticMenuItem(url, url));
  15287. const joinMenuLists = items => {
  15288. return foldl(items, (a, b) => {
  15289. const bothEmpty = a.length === 0 || b.length === 0;
  15290. return bothEmpty ? a.concat(b) : a.concat(separator$1, b);
  15291. }, []);
  15292. };
  15293. const filterByQuery = (term, menuItems) => {
  15294. const lowerCaseTerm = term.toLowerCase();
  15295. return filter$2(menuItems, item => {
  15296. const text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  15297. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  15298. });
  15299. };
  15300. const getItems = (fileType, input, urlBackstage) => {
  15301. const urlInputValue = Representing.getValue(input);
  15302. const term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  15303. const info = urlBackstage.getLinkInformation();
  15304. return info.fold(() => [], linkInfo => {
  15305. const history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  15306. return fileType === 'file' ? joinMenuLists([
  15307. history,
  15308. filterByQuery(term, headerTargets(linkInfo)),
  15309. filterByQuery(term, flatten([
  15310. anchorTargetTop(linkInfo),
  15311. anchorTargets(linkInfo),
  15312. anchorTargetBottom(linkInfo)
  15313. ]))
  15314. ]) : history;
  15315. });
  15316. };
  15317. const errorId = generate$6('aria-invalid');
  15318. const renderUrlInput = (spec, backstage, urlBackstage, initialData) => {
  15319. const providersBackstage = backstage.shared.providers;
  15320. const updateHistory = component => {
  15321. const urlEntry = Representing.getValue(component);
  15322. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  15323. };
  15324. const pField = FormField.parts.field({
  15325. factory: Typeahead,
  15326. ...initialData.map(initialData => ({ initialData })).getOr({}),
  15327. dismissOnBlur: true,
  15328. inputClasses: ['tox-textfield'],
  15329. sandboxClasses: ['tox-dialog__popups'],
  15330. inputAttributes: {
  15331. 'aria-errormessage': errorId,
  15332. 'type': 'url'
  15333. },
  15334. minChars: 0,
  15335. responseTime: 0,
  15336. fetch: input => {
  15337. const items = getItems(spec.filetype, input, urlBackstage);
  15338. const tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  15339. return Future.pure(tdata);
  15340. },
  15341. getHotspot: comp => memUrlBox.getOpt(comp),
  15342. onSetValue: (comp, _newValue) => {
  15343. if (comp.hasConfigured(Invalidating)) {
  15344. Invalidating.run(comp).get(noop);
  15345. }
  15346. },
  15347. typeaheadBehaviours: derive$1(flatten([
  15348. urlBackstage.getValidationHandler().map(handler => Invalidating.config({
  15349. getRoot: comp => parentElement(comp.element),
  15350. invalidClass: 'tox-control-wrap--status-invalid',
  15351. notify: {
  15352. onInvalid: (comp, err) => {
  15353. memInvalidIcon.getOpt(comp).each(invalidComp => {
  15354. set$9(invalidComp.element, 'title', providersBackstage.translate(err));
  15355. });
  15356. }
  15357. },
  15358. validator: {
  15359. validate: input => {
  15360. const urlEntry = Representing.getValue(input);
  15361. return FutureResult.nu(completer => {
  15362. handler({
  15363. type: spec.filetype,
  15364. url: urlEntry.value
  15365. }, validation => {
  15366. if (validation.status === 'invalid') {
  15367. const err = Result.error(validation.message);
  15368. completer(err);
  15369. } else {
  15370. const val = Result.value(validation.message);
  15371. completer(val);
  15372. }
  15373. });
  15374. });
  15375. },
  15376. validateOnLoad: false
  15377. }
  15378. })).toArray(),
  15379. [
  15380. Disabling.config({ disabled: () => !spec.enabled || providersBackstage.isDisabled() }),
  15381. Tabstopping.config({}),
  15382. config('urlinput-events', flatten([
  15383. spec.filetype === 'file' ? [run$1(input(), comp => {
  15384. emitWith(comp, formChangeEvent, { name: spec.name });
  15385. })] : [],
  15386. [
  15387. run$1(change(), comp => {
  15388. emitWith(comp, formChangeEvent, { name: spec.name });
  15389. updateHistory(comp);
  15390. }),
  15391. run$1(postPaste(), comp => {
  15392. emitWith(comp, formChangeEvent, { name: spec.name });
  15393. updateHistory(comp);
  15394. })
  15395. ]
  15396. ]))
  15397. ]
  15398. ])),
  15399. eventOrder: {
  15400. [input()]: [
  15401. 'streaming',
  15402. 'urlinput-events',
  15403. 'invalidating'
  15404. ]
  15405. },
  15406. model: {
  15407. getDisplayText: itemData => itemData.value,
  15408. selectsOver: false,
  15409. populateFromBrowse: false
  15410. },
  15411. markers: { openClass: 'tox-textfield--popup-open' },
  15412. lazySink: backstage.shared.getSink,
  15413. parts: { menu: part(false, 1, 'normal') },
  15414. onExecute: (_menu, component, _entry) => {
  15415. emitWith(component, formSubmitEvent, {});
  15416. },
  15417. onItemExecute: (typeahead, _sandbox, _item, _value) => {
  15418. updateHistory(typeahead);
  15419. emitWith(typeahead, formChangeEvent, { name: spec.name });
  15420. }
  15421. });
  15422. const pLabel = spec.label.map(label => renderLabel$2(label, providersBackstage));
  15423. const makeIcon = (name, errId, icon = name, label = name) => render$3(icon, {
  15424. tag: 'div',
  15425. classes: [
  15426. 'tox-icon',
  15427. 'tox-control-wrap__status-icon-' + name
  15428. ],
  15429. attributes: {
  15430. 'title': providersBackstage.translate(label),
  15431. 'aria-live': 'polite',
  15432. ...errId.fold(() => ({}), id => ({ id }))
  15433. }
  15434. }, providersBackstage.icons);
  15435. const memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
  15436. const memStatus = record({
  15437. dom: {
  15438. tag: 'div',
  15439. classes: ['tox-control-wrap__status-icon-wrap']
  15440. },
  15441. components: [memInvalidIcon.asSpec()]
  15442. });
  15443. const optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  15444. const browseUrlEvent = generate$6('browser.url.event');
  15445. const memUrlBox = record({
  15446. dom: {
  15447. tag: 'div',
  15448. classes: ['tox-control-wrap']
  15449. },
  15450. components: [
  15451. pField,
  15452. memStatus.asSpec()
  15453. ],
  15454. behaviours: derive$1([Disabling.config({ disabled: () => !spec.enabled || providersBackstage.isDisabled() })])
  15455. });
  15456. const memUrlPickerButton = record(renderButton({
  15457. name: spec.name,
  15458. icon: Optional.some('browse'),
  15459. text: spec.label.getOr(''),
  15460. enabled: spec.enabled,
  15461. primary: false,
  15462. buttonType: Optional.none(),
  15463. borderless: true
  15464. }, component => emit(component, browseUrlEvent), providersBackstage, [], ['tox-browse-url']));
  15465. const controlHWrapper = () => ({
  15466. dom: {
  15467. tag: 'div',
  15468. classes: ['tox-form__controls-h-stack']
  15469. },
  15470. components: flatten([
  15471. [memUrlBox.asSpec()],
  15472. optUrlPicker.map(() => memUrlPickerButton.asSpec()).toArray()
  15473. ])
  15474. });
  15475. const openUrlPicker = comp => {
  15476. Composing.getCurrent(comp).each(field => {
  15477. const componentData = Representing.getValue(field);
  15478. const urlData = {
  15479. fieldname: spec.name,
  15480. ...componentData
  15481. };
  15482. optUrlPicker.each(picker => {
  15483. picker(urlData).get(chosenData => {
  15484. Representing.setValue(field, chosenData);
  15485. emitWith(comp, formChangeEvent, { name: spec.name });
  15486. });
  15487. });
  15488. });
  15489. };
  15490. return FormField.sketch({
  15491. dom: renderFormFieldDom(),
  15492. components: pLabel.toArray().concat([controlHWrapper()]),
  15493. fieldBehaviours: derive$1([
  15494. Disabling.config({
  15495. disabled: () => !spec.enabled || providersBackstage.isDisabled(),
  15496. onDisabled: comp => {
  15497. FormField.getField(comp).each(Disabling.disable);
  15498. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  15499. },
  15500. onEnabled: comp => {
  15501. FormField.getField(comp).each(Disabling.enable);
  15502. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  15503. }
  15504. }),
  15505. receivingConfig(),
  15506. config('url-input-events', [run$1(browseUrlEvent, openUrlPicker)])
  15507. ])
  15508. });
  15509. };
  15510. const renderAlertBanner = (spec, providersBackstage) => Container.sketch({
  15511. dom: {
  15512. tag: 'div',
  15513. attributes: { role: 'alert' },
  15514. classes: [
  15515. 'tox-notification',
  15516. 'tox-notification--in',
  15517. `tox-notification--${ spec.level }`
  15518. ]
  15519. },
  15520. components: [
  15521. {
  15522. dom: {
  15523. tag: 'div',
  15524. classes: ['tox-notification__icon']
  15525. },
  15526. components: [Button.sketch({
  15527. dom: {
  15528. tag: 'button',
  15529. classes: [
  15530. 'tox-button',
  15531. 'tox-button--naked',
  15532. 'tox-button--icon'
  15533. ],
  15534. innerHtml: get$2(spec.icon, providersBackstage.icons),
  15535. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  15536. },
  15537. action: comp => {
  15538. emitWith(comp, formActionEvent, {
  15539. name: 'alert-banner',
  15540. value: spec.url
  15541. });
  15542. },
  15543. buttonBehaviours: derive$1([addFocusableBehaviour()])
  15544. })]
  15545. },
  15546. {
  15547. dom: {
  15548. tag: 'div',
  15549. classes: ['tox-notification__body'],
  15550. innerHtml: providersBackstage.translate(spec.text)
  15551. }
  15552. }
  15553. ]
  15554. });
  15555. const set$1 = (element, status) => {
  15556. element.dom.checked = status;
  15557. };
  15558. const get$1 = element => element.dom.checked;
  15559. const renderCheckbox = (spec, providerBackstage, initialData) => {
  15560. const toggleCheckboxHandler = comp => {
  15561. comp.element.dom.click();
  15562. return Optional.some(true);
  15563. };
  15564. const pField = FormField.parts.field({
  15565. factory: { sketch: identity },
  15566. dom: {
  15567. tag: 'input',
  15568. classes: ['tox-checkbox__input'],
  15569. attributes: { type: 'checkbox' }
  15570. },
  15571. behaviours: derive$1([
  15572. ComposingConfigs.self(),
  15573. Disabling.config({ disabled: () => !spec.enabled || providerBackstage.isDisabled() }),
  15574. Tabstopping.config({}),
  15575. Focusing.config({}),
  15576. RepresentingConfigs.withElement(initialData, get$1, set$1),
  15577. Keying.config({
  15578. mode: 'special',
  15579. onEnter: toggleCheckboxHandler,
  15580. onSpace: toggleCheckboxHandler,
  15581. stopSpaceKeyup: true
  15582. }),
  15583. config('checkbox-events', [run$1(change(), (component, _) => {
  15584. emitWith(component, formChangeEvent, { name: spec.name });
  15585. })])
  15586. ])
  15587. });
  15588. const pLabel = FormField.parts.label({
  15589. dom: {
  15590. tag: 'span',
  15591. classes: ['tox-checkbox__label']
  15592. },
  15593. components: [text$1(providerBackstage.translate(spec.label))],
  15594. behaviours: derive$1([Unselecting.config({})])
  15595. });
  15596. const makeIcon = className => {
  15597. const iconName = className === 'checked' ? 'selected' : 'unselected';
  15598. return render$3(iconName, {
  15599. tag: 'span',
  15600. classes: [
  15601. 'tox-icon',
  15602. 'tox-checkbox-icon__' + className
  15603. ]
  15604. }, providerBackstage.icons);
  15605. };
  15606. const memIcons = record({
  15607. dom: {
  15608. tag: 'div',
  15609. classes: ['tox-checkbox__icons']
  15610. },
  15611. components: [
  15612. makeIcon('checked'),
  15613. makeIcon('unchecked')
  15614. ]
  15615. });
  15616. return FormField.sketch({
  15617. dom: {
  15618. tag: 'label',
  15619. classes: ['tox-checkbox']
  15620. },
  15621. components: [
  15622. pField,
  15623. memIcons.asSpec(),
  15624. pLabel
  15625. ],
  15626. fieldBehaviours: derive$1([
  15627. Disabling.config({
  15628. disabled: () => !spec.enabled || providerBackstage.isDisabled(),
  15629. disableClass: 'tox-checkbox--disabled',
  15630. onDisabled: comp => {
  15631. FormField.getField(comp).each(Disabling.disable);
  15632. },
  15633. onEnabled: comp => {
  15634. FormField.getField(comp).each(Disabling.enable);
  15635. }
  15636. }),
  15637. receivingConfig()
  15638. ])
  15639. });
  15640. };
  15641. const renderHtmlPanel = spec => {
  15642. if (spec.presets === 'presentation') {
  15643. return Container.sketch({
  15644. dom: {
  15645. tag: 'div',
  15646. classes: ['tox-form__group'],
  15647. innerHtml: spec.html
  15648. }
  15649. });
  15650. } else {
  15651. return Container.sketch({
  15652. dom: {
  15653. tag: 'div',
  15654. classes: ['tox-form__group'],
  15655. innerHtml: spec.html,
  15656. attributes: { role: 'document' }
  15657. },
  15658. containerBehaviours: derive$1([
  15659. Tabstopping.config({}),
  15660. Focusing.config({})
  15661. ])
  15662. });
  15663. }
  15664. };
  15665. const make$2 = render => {
  15666. return (parts, spec, dialogData, backstage) => get$g(spec, 'name').fold(() => render(spec, backstage, Optional.none()), fieldName => parts.field(fieldName, render(spec, backstage, get$g(dialogData, fieldName))));
  15667. };
  15668. const makeIframe = render => (parts, spec, dialogData, backstage) => {
  15669. const iframeSpec = deepMerge(spec, { source: 'dynamic' });
  15670. return make$2(render)(parts, iframeSpec, dialogData, backstage);
  15671. };
  15672. const factories = {
  15673. bar: make$2((spec, backstage) => renderBar(spec, backstage.shared)),
  15674. collection: make$2((spec, backstage, data) => renderCollection(spec, backstage.shared.providers, data)),
  15675. alertbanner: make$2((spec, backstage) => renderAlertBanner(spec, backstage.shared.providers)),
  15676. input: make$2((spec, backstage, data) => renderInput(spec, backstage.shared.providers, data)),
  15677. textarea: make$2((spec, backstage, data) => renderTextarea(spec, backstage.shared.providers, data)),
  15678. label: make$2((spec, backstage) => renderLabel$1(spec, backstage.shared)),
  15679. iframe: makeIframe((spec, backstage, data) => renderIFrame(spec, backstage.shared.providers, data)),
  15680. button: make$2((spec, backstage) => renderDialogButton(spec, backstage.shared.providers)),
  15681. checkbox: make$2((spec, backstage, data) => renderCheckbox(spec, backstage.shared.providers, data)),
  15682. colorinput: make$2((spec, backstage, data) => renderColorInput(spec, backstage.shared, backstage.colorinput, data)),
  15683. colorpicker: make$2((spec, backstage, data) => renderColorPicker(spec, backstage.shared.providers, data)),
  15684. dropzone: make$2((spec, backstage, data) => renderDropZone(spec, backstage.shared.providers, data)),
  15685. grid: make$2((spec, backstage) => renderGrid(spec, backstage.shared)),
  15686. listbox: make$2((spec, backstage, data) => renderListBox(spec, backstage, data)),
  15687. selectbox: make$2((spec, backstage, data) => renderSelectBox(spec, backstage.shared.providers, data)),
  15688. sizeinput: make$2((spec, backstage) => renderSizeInput(spec, backstage.shared.providers)),
  15689. slider: make$2((spec, backstage, data) => renderSlider(spec, backstage.shared.providers, data)),
  15690. urlinput: make$2((spec, backstage, data) => renderUrlInput(spec, backstage, backstage.urlinput, data)),
  15691. customeditor: make$2(renderCustomEditor),
  15692. htmlpanel: make$2(renderHtmlPanel),
  15693. imagepreview: make$2((spec, _, data) => renderImagePreview(spec, data)),
  15694. table: make$2((spec, backstage) => renderTable(spec, backstage.shared.providers)),
  15695. panel: make$2((spec, backstage) => renderPanel(spec, backstage))
  15696. };
  15697. const noFormParts = {
  15698. field: (_name, spec) => spec,
  15699. record: constant$1([])
  15700. };
  15701. const interpretInForm = (parts, spec, dialogData, oldBackstage) => {
  15702. const newBackstage = deepMerge(oldBackstage, { shared: { interpreter: childSpec => interpretParts(parts, childSpec, dialogData, newBackstage) } });
  15703. return interpretParts(parts, spec, dialogData, newBackstage);
  15704. };
  15705. const interpretParts = (parts, spec, dialogData, backstage) => get$g(factories, spec.type).fold(() => {
  15706. console.error(`Unknown factory type "${ spec.type }", defaulting to container: `, spec);
  15707. return spec;
  15708. }, factory => factory(parts, spec, dialogData, backstage));
  15709. const interpretWithoutForm = (spec, dialogData, backstage) => interpretParts(noFormParts, spec, dialogData, backstage);
  15710. const labelPrefix = 'layout-inset';
  15711. const westEdgeX = anchor => anchor.x;
  15712. const middleX = (anchor, element) => anchor.x + anchor.width / 2 - element.width / 2;
  15713. const eastEdgeX = (anchor, element) => anchor.x + anchor.width - element.width;
  15714. const northY = anchor => anchor.y;
  15715. const southY = (anchor, element) => anchor.y + anchor.height - element.height;
  15716. const centreY = (anchor, element) => anchor.y + anchor.height / 2 - element.height / 2;
  15717. const southwest = (anchor, element, bubbles) => nu$6(eastEdgeX(anchor, element), southY(anchor, element), bubbles.insetSouthwest(), northwest$3(), 'southwest', boundsRestriction(anchor, {
  15718. right: 0,
  15719. bottom: 3
  15720. }), labelPrefix);
  15721. const southeast = (anchor, element, bubbles) => nu$6(westEdgeX(anchor), southY(anchor, element), bubbles.insetSoutheast(), northeast$3(), 'southeast', boundsRestriction(anchor, {
  15722. left: 1,
  15723. bottom: 3
  15724. }), labelPrefix);
  15725. const northwest = (anchor, element, bubbles) => nu$6(eastEdgeX(anchor, element), northY(anchor), bubbles.insetNorthwest(), southwest$3(), 'northwest', boundsRestriction(anchor, {
  15726. right: 0,
  15727. top: 2
  15728. }), labelPrefix);
  15729. const northeast = (anchor, element, bubbles) => nu$6(westEdgeX(anchor), northY(anchor), bubbles.insetNortheast(), southeast$3(), 'northeast', boundsRestriction(anchor, {
  15730. left: 1,
  15731. top: 2
  15732. }), labelPrefix);
  15733. const north = (anchor, element, bubbles) => nu$6(middleX(anchor, element), northY(anchor), bubbles.insetNorth(), south$3(), 'north', boundsRestriction(anchor, { top: 2 }), labelPrefix);
  15734. const south = (anchor, element, bubbles) => nu$6(middleX(anchor, element), southY(anchor, element), bubbles.insetSouth(), north$3(), 'south', boundsRestriction(anchor, { bottom: 3 }), labelPrefix);
  15735. const east = (anchor, element, bubbles) => nu$6(eastEdgeX(anchor, element), centreY(anchor, element), bubbles.insetEast(), west$3(), 'east', boundsRestriction(anchor, { right: 0 }), labelPrefix);
  15736. const west = (anchor, element, bubbles) => nu$6(westEdgeX(anchor), centreY(anchor, element), bubbles.insetWest(), east$3(), 'west', boundsRestriction(anchor, { left: 1 }), labelPrefix);
  15737. const lookupPreserveLayout = lastPlacement => {
  15738. switch (lastPlacement) {
  15739. case 'north':
  15740. return north;
  15741. case 'northeast':
  15742. return northeast;
  15743. case 'northwest':
  15744. return northwest;
  15745. case 'south':
  15746. return south;
  15747. case 'southeast':
  15748. return southeast;
  15749. case 'southwest':
  15750. return southwest;
  15751. case 'east':
  15752. return east;
  15753. case 'west':
  15754. return west;
  15755. }
  15756. };
  15757. const preserve = (anchor, element, bubbles, placee, bounds) => {
  15758. const layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
  15759. return layout(anchor, element, bubbles, placee, bounds);
  15760. };
  15761. const lookupFlippedLayout = lastPlacement => {
  15762. switch (lastPlacement) {
  15763. case 'north':
  15764. return south;
  15765. case 'northeast':
  15766. return southeast;
  15767. case 'northwest':
  15768. return southwest;
  15769. case 'south':
  15770. return north;
  15771. case 'southeast':
  15772. return northeast;
  15773. case 'southwest':
  15774. return northwest;
  15775. case 'east':
  15776. return west;
  15777. case 'west':
  15778. return east;
  15779. }
  15780. };
  15781. const flip = (anchor, element, bubbles, placee, bounds) => {
  15782. const layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
  15783. return layout(anchor, element, bubbles, placee, bounds);
  15784. };
  15785. const bubbleAlignments$2 = {
  15786. valignCentre: [],
  15787. alignCentre: [],
  15788. alignLeft: [],
  15789. alignRight: [],
  15790. right: [],
  15791. left: [],
  15792. bottom: [],
  15793. top: []
  15794. };
  15795. const getInlineDialogAnchor = (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) => {
  15796. const bubbleSize = 12;
  15797. const overrides = { maxHeightFunction: expandable$1() };
  15798. const editableAreaAnchor = () => ({
  15799. type: 'node',
  15800. root: getContentContainer(contentAreaElement()),
  15801. node: Optional.from(contentAreaElement()),
  15802. bubble: nu$5(bubbleSize, bubbleSize, bubbleAlignments$2),
  15803. layouts: {
  15804. onRtl: () => [northeast],
  15805. onLtr: () => [northwest]
  15806. },
  15807. overrides
  15808. });
  15809. const standardAnchor = () => ({
  15810. type: 'hotspot',
  15811. hotspot: lazyAnchorbar(),
  15812. bubble: nu$5(-bubbleSize, bubbleSize, bubbleAlignments$2),
  15813. layouts: {
  15814. onRtl: () => [southeast$2],
  15815. onLtr: () => [southwest$2]
  15816. },
  15817. overrides
  15818. });
  15819. return () => lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  15820. };
  15821. const getBannerAnchor = (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) => {
  15822. const editableAreaAnchor = () => ({
  15823. type: 'node',
  15824. root: getContentContainer(contentAreaElement()),
  15825. node: Optional.from(contentAreaElement()),
  15826. layouts: {
  15827. onRtl: () => [north],
  15828. onLtr: () => [north]
  15829. }
  15830. });
  15831. const standardAnchor = () => ({
  15832. type: 'hotspot',
  15833. hotspot: lazyAnchorbar(),
  15834. layouts: {
  15835. onRtl: () => [south$2],
  15836. onLtr: () => [south$2]
  15837. }
  15838. });
  15839. return () => lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  15840. };
  15841. const getCursorAnchor = (editor, bodyElement) => () => ({
  15842. type: 'selection',
  15843. root: bodyElement(),
  15844. getSelection: () => {
  15845. const rng = editor.selection.getRng();
  15846. return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  15847. }
  15848. });
  15849. const getNodeAnchor$1 = bodyElement => element => ({
  15850. type: 'node',
  15851. root: bodyElement(),
  15852. node: element
  15853. });
  15854. const getAnchors = (editor, lazyAnchorbar, isToolbarTop) => {
  15855. const useFixedToolbarContainer = useFixedContainer(editor);
  15856. const bodyElement = () => SugarElement.fromDom(editor.getBody());
  15857. const contentAreaElement = () => SugarElement.fromDom(editor.getContentAreaContainer());
  15858. const lazyUseEditableAreaAnchor = () => useFixedToolbarContainer || !isToolbarTop();
  15859. return {
  15860. inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  15861. banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  15862. cursor: getCursorAnchor(editor, bodyElement),
  15863. node: getNodeAnchor$1(bodyElement)
  15864. };
  15865. };
  15866. const colorPicker = editor => (callback, value) => {
  15867. const dialog = colorPickerDialog(editor);
  15868. dialog(callback, value);
  15869. };
  15870. const hasCustomColors = editor => () => hasCustomColors$1(editor);
  15871. const getColors = editor => () => getColors$2(editor);
  15872. const getColorCols = editor => () => getColorCols$1(editor);
  15873. const ColorInputBackstage = editor => ({
  15874. colorPicker: colorPicker(editor),
  15875. hasCustomColors: hasCustomColors(editor),
  15876. getColors: getColors(editor),
  15877. getColorCols: getColorCols(editor)
  15878. });
  15879. const isDraggableModal = editor => () => isDraggableModal$1(editor);
  15880. const DialogBackstage = editor => ({ isDraggableModal: isDraggableModal(editor) });
  15881. const HeaderBackstage = editor => {
  15882. const mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  15883. return {
  15884. isPositionedAtTop: () => mode.get() === 'top',
  15885. getDockingMode: mode.get,
  15886. setDockingMode: mode.set
  15887. };
  15888. };
  15889. const defaultStyleFormats = [
  15890. {
  15891. title: 'Headings',
  15892. items: [
  15893. {
  15894. title: 'Heading 1',
  15895. format: 'h1'
  15896. },
  15897. {
  15898. title: 'Heading 2',
  15899. format: 'h2'
  15900. },
  15901. {
  15902. title: 'Heading 3',
  15903. format: 'h3'
  15904. },
  15905. {
  15906. title: 'Heading 4',
  15907. format: 'h4'
  15908. },
  15909. {
  15910. title: 'Heading 5',
  15911. format: 'h5'
  15912. },
  15913. {
  15914. title: 'Heading 6',
  15915. format: 'h6'
  15916. }
  15917. ]
  15918. },
  15919. {
  15920. title: 'Inline',
  15921. items: [
  15922. {
  15923. title: 'Bold',
  15924. format: 'bold'
  15925. },
  15926. {
  15927. title: 'Italic',
  15928. format: 'italic'
  15929. },
  15930. {
  15931. title: 'Underline',
  15932. format: 'underline'
  15933. },
  15934. {
  15935. title: 'Strikethrough',
  15936. format: 'strikethrough'
  15937. },
  15938. {
  15939. title: 'Superscript',
  15940. format: 'superscript'
  15941. },
  15942. {
  15943. title: 'Subscript',
  15944. format: 'subscript'
  15945. },
  15946. {
  15947. title: 'Code',
  15948. format: 'code'
  15949. }
  15950. ]
  15951. },
  15952. {
  15953. title: 'Blocks',
  15954. items: [
  15955. {
  15956. title: 'Paragraph',
  15957. format: 'p'
  15958. },
  15959. {
  15960. title: 'Blockquote',
  15961. format: 'blockquote'
  15962. },
  15963. {
  15964. title: 'Div',
  15965. format: 'div'
  15966. },
  15967. {
  15968. title: 'Pre',
  15969. format: 'pre'
  15970. }
  15971. ]
  15972. },
  15973. {
  15974. title: 'Align',
  15975. items: [
  15976. {
  15977. title: 'Left',
  15978. format: 'alignleft'
  15979. },
  15980. {
  15981. title: 'Center',
  15982. format: 'aligncenter'
  15983. },
  15984. {
  15985. title: 'Right',
  15986. format: 'alignright'
  15987. },
  15988. {
  15989. title: 'Justify',
  15990. format: 'alignjustify'
  15991. }
  15992. ]
  15993. }
  15994. ];
  15995. const isNestedFormat = format => has$2(format, 'items');
  15996. const isBlockFormat = format => has$2(format, 'block');
  15997. const isInlineFormat = format => has$2(format, 'inline');
  15998. const isSelectorFormat = format => has$2(format, 'selector');
  15999. const mapFormats = userFormats => foldl(userFormats, (acc, fmt) => {
  16000. if (isNestedFormat(fmt)) {
  16001. const result = mapFormats(fmt.items);
  16002. return {
  16003. customFormats: acc.customFormats.concat(result.customFormats),
  16004. formats: acc.formats.concat([{
  16005. title: fmt.title,
  16006. items: result.formats
  16007. }])
  16008. };
  16009. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  16010. const formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
  16011. const formatNameWithPrefix = `custom-${ formatName }`;
  16012. return {
  16013. customFormats: acc.customFormats.concat([{
  16014. name: formatNameWithPrefix,
  16015. format: fmt
  16016. }]),
  16017. formats: acc.formats.concat([{
  16018. title: fmt.title,
  16019. format: formatNameWithPrefix,
  16020. icon: fmt.icon
  16021. }])
  16022. };
  16023. } else {
  16024. return {
  16025. ...acc,
  16026. formats: acc.formats.concat(fmt)
  16027. };
  16028. }
  16029. }, {
  16030. customFormats: [],
  16031. formats: []
  16032. });
  16033. const registerCustomFormats = (editor, userFormats) => {
  16034. const result = mapFormats(userFormats);
  16035. const registerFormats = customFormats => {
  16036. each$1(customFormats, fmt => {
  16037. if (!editor.formatter.has(fmt.name)) {
  16038. editor.formatter.register(fmt.name, fmt.format);
  16039. }
  16040. });
  16041. };
  16042. if (editor.formatter) {
  16043. registerFormats(result.customFormats);
  16044. } else {
  16045. editor.on('init', () => {
  16046. registerFormats(result.customFormats);
  16047. });
  16048. }
  16049. return result.formats;
  16050. };
  16051. const getStyleFormats = editor => getUserStyleFormats(editor).map(userFormats => {
  16052. const registeredUserFormats = registerCustomFormats(editor, userFormats);
  16053. return shouldMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  16054. }).getOr(defaultStyleFormats);
  16055. const processBasic = (item, isSelectedFor, getPreviewFor) => {
  16056. const formatterSpec = {
  16057. type: 'formatter',
  16058. isSelected: isSelectedFor(item.format),
  16059. getStylePreview: getPreviewFor(item.format)
  16060. };
  16061. return deepMerge(item, formatterSpec);
  16062. };
  16063. const register$a = (editor, formats, isSelectedFor, getPreviewFor) => {
  16064. const enrichSupported = item => processBasic(item, isSelectedFor, getPreviewFor);
  16065. const enrichMenu = item => {
  16066. const submenuSpec = { type: 'submenu' };
  16067. return deepMerge(item, submenuSpec);
  16068. };
  16069. const enrichCustom = item => {
  16070. const formatName = isString(item.name) ? item.name : generate$6(item.title);
  16071. const formatNameWithPrefix = `custom-${ formatName }`;
  16072. const customSpec = {
  16073. type: 'formatter',
  16074. format: formatNameWithPrefix,
  16075. isSelected: isSelectedFor(formatNameWithPrefix),
  16076. getStylePreview: getPreviewFor(formatNameWithPrefix)
  16077. };
  16078. const newItem = deepMerge(item, customSpec);
  16079. editor.formatter.register(formatName, newItem);
  16080. return newItem;
  16081. };
  16082. const doEnrich = items => map$2(items, item => {
  16083. const keys$1 = keys(item);
  16084. if (hasNonNullableKey(item, 'items')) {
  16085. const newItems = doEnrich(item.items);
  16086. return deepMerge(enrichMenu(item), { getStyleItems: constant$1(newItems) });
  16087. } else if (hasNonNullableKey(item, 'format')) {
  16088. return enrichSupported(item);
  16089. } else if (keys$1.length === 1 && contains$2(keys$1, 'title')) {
  16090. return deepMerge(item, { type: 'separator' });
  16091. } else {
  16092. return enrichCustom(item);
  16093. }
  16094. });
  16095. return doEnrich(formats);
  16096. };
  16097. const init$8 = editor => {
  16098. const isSelectedFor = format => () => editor.formatter.match(format);
  16099. const getPreviewFor = format => () => {
  16100. const fmt = editor.formatter.get(format);
  16101. return fmt !== undefined ? Optional.some({
  16102. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  16103. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  16104. }) : Optional.none();
  16105. };
  16106. const flatten = fmt => {
  16107. const subs = fmt.items;
  16108. return subs !== undefined && subs.length > 0 ? bind$3(subs, flatten) : [fmt.format];
  16109. };
  16110. const settingsFormats = Cell([]);
  16111. const settingsFlattenedFormats = Cell([]);
  16112. const eventsFormats = Cell([]);
  16113. const eventsFlattenedFormats = Cell([]);
  16114. const replaceSettings = Cell(false);
  16115. editor.on('PreInit', _e => {
  16116. const formats = getStyleFormats(editor);
  16117. const enriched = register$a(editor, formats, isSelectedFor, getPreviewFor);
  16118. settingsFormats.set(enriched);
  16119. settingsFlattenedFormats.set(bind$3(enriched, flatten));
  16120. });
  16121. editor.on('addStyleModifications', e => {
  16122. const modifications = register$a(editor, e.items, isSelectedFor, getPreviewFor);
  16123. eventsFormats.set(modifications);
  16124. replaceSettings.set(e.replace);
  16125. eventsFlattenedFormats.set(bind$3(modifications, flatten));
  16126. });
  16127. const getData = () => {
  16128. const fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  16129. const fromEvents = eventsFormats.get();
  16130. return fromSettings.concat(fromEvents);
  16131. };
  16132. const getFlattenedKeys = () => {
  16133. const fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  16134. const fromEvents = eventsFlattenedFormats.get();
  16135. return fromSettings.concat(fromEvents);
  16136. };
  16137. return {
  16138. getData,
  16139. getFlattenedKeys
  16140. };
  16141. };
  16142. const isElement = node => isNonNullable(node) && node.nodeType === 1;
  16143. const trim = global$1.trim;
  16144. const hasContentEditableState = value => {
  16145. return node => {
  16146. if (isElement(node)) {
  16147. if (node.contentEditable === value) {
  16148. return true;
  16149. }
  16150. if (node.getAttribute('data-mce-contenteditable') === value) {
  16151. return true;
  16152. }
  16153. }
  16154. return false;
  16155. };
  16156. };
  16157. const isContentEditableTrue = hasContentEditableState('true');
  16158. const isContentEditableFalse = hasContentEditableState('false');
  16159. const create = (type, title, url, level, attach) => {
  16160. return {
  16161. type,
  16162. title,
  16163. url,
  16164. level,
  16165. attach
  16166. };
  16167. };
  16168. const isChildOfContentEditableTrue = node => {
  16169. while (node = node.parentNode) {
  16170. const value = node.contentEditable;
  16171. if (value && value !== 'inherit') {
  16172. return isContentEditableTrue(node);
  16173. }
  16174. }
  16175. return false;
  16176. };
  16177. const select = (selector, root) => {
  16178. return map$2(descendants(SugarElement.fromDom(root), selector), element => {
  16179. return element.dom;
  16180. });
  16181. };
  16182. const getElementText = elm => {
  16183. return elm.innerText || elm.textContent;
  16184. };
  16185. const getOrGenerateId = elm => {
  16186. return elm.id ? elm.id : generate$6('h');
  16187. };
  16188. const isAnchor = elm => {
  16189. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  16190. };
  16191. const isValidAnchor = elm => {
  16192. return isAnchor(elm) && isEditable(elm);
  16193. };
  16194. const isHeader = elm => {
  16195. return elm && /^(H[1-6])$/.test(elm.nodeName);
  16196. };
  16197. const isEditable = elm => {
  16198. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  16199. };
  16200. const isValidHeader = elm => {
  16201. return isHeader(elm) && isEditable(elm);
  16202. };
  16203. const getLevel = elm => {
  16204. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  16205. };
  16206. const headerTarget = elm => {
  16207. const headerId = getOrGenerateId(elm);
  16208. const attach = () => {
  16209. elm.id = headerId;
  16210. };
  16211. return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  16212. };
  16213. const anchorTarget = elm => {
  16214. const anchorId = elm.id || elm.name;
  16215. const anchorText = getElementText(elm);
  16216. return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  16217. };
  16218. const getHeaderTargets = elms => {
  16219. return map$2(filter$2(elms, isValidHeader), headerTarget);
  16220. };
  16221. const getAnchorTargets = elms => {
  16222. return map$2(filter$2(elms, isValidAnchor), anchorTarget);
  16223. };
  16224. const getTargetElements = elm => {
  16225. const elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  16226. return elms;
  16227. };
  16228. const hasTitle = target => {
  16229. return trim(target.title).length > 0;
  16230. };
  16231. const find = elm => {
  16232. const elms = getTargetElements(elm);
  16233. return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  16234. };
  16235. const LinkTargets = { find };
  16236. const STORAGE_KEY = 'tinymce-url-history';
  16237. const HISTORY_LENGTH = 5;
  16238. const isHttpUrl = url => isString(url) && /^https?/.test(url);
  16239. const isArrayOfUrl = a => isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  16240. const isRecordOfUrlArray = r => isObject(r) && find$4(r, value => !isArrayOfUrl(value)).isNone();
  16241. const getAllHistory = () => {
  16242. const unparsedHistory = global$4.getItem(STORAGE_KEY);
  16243. if (unparsedHistory === null) {
  16244. return {};
  16245. }
  16246. let history;
  16247. try {
  16248. history = JSON.parse(unparsedHistory);
  16249. } catch (e) {
  16250. if (e instanceof SyntaxError) {
  16251. console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  16252. return {};
  16253. }
  16254. throw e;
  16255. }
  16256. if (!isRecordOfUrlArray(history)) {
  16257. console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  16258. return {};
  16259. }
  16260. return history;
  16261. };
  16262. const setAllHistory = history => {
  16263. if (!isRecordOfUrlArray(history)) {
  16264. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  16265. }
  16266. global$4.setItem(STORAGE_KEY, JSON.stringify(history));
  16267. };
  16268. const getHistory = fileType => {
  16269. const history = getAllHistory();
  16270. return get$g(history, fileType).getOr([]);
  16271. };
  16272. const addToHistory = (url, fileType) => {
  16273. if (!isHttpUrl(url)) {
  16274. return;
  16275. }
  16276. const history = getAllHistory();
  16277. const items = get$g(history, fileType).getOr([]);
  16278. const itemsWithoutUrl = filter$2(items, item => item !== url);
  16279. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  16280. setAllHistory(history);
  16281. };
  16282. const isTruthy = value => !!value;
  16283. const makeMap = value => map$1(global$1.makeMap(value, /[, ]/), isTruthy);
  16284. const getPicker = editor => Optional.from(getFilePickerCallback(editor));
  16285. const getPickerTypes = editor => {
  16286. const optFileTypes = Optional.from(getFilePickerTypes(editor)).filter(isTruthy).map(makeMap);
  16287. return getPicker(editor).fold(never, _picker => optFileTypes.fold(always, types => keys(types).length > 0 ? types : false));
  16288. };
  16289. const getPickerSetting = (editor, filetype) => {
  16290. const pickerTypes = getPickerTypes(editor);
  16291. if (isBoolean(pickerTypes)) {
  16292. return pickerTypes ? getPicker(editor) : Optional.none();
  16293. } else {
  16294. return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
  16295. }
  16296. };
  16297. const getUrlPicker = (editor, filetype) => getPickerSetting(editor, filetype).map(picker => entry => Future.nu(completer => {
  16298. const handler = (value, meta) => {
  16299. if (!isString(value)) {
  16300. throw new Error('Expected value to be string');
  16301. }
  16302. if (meta !== undefined && !isObject(meta)) {
  16303. throw new Error('Expected meta to be a object');
  16304. }
  16305. const r = {
  16306. value,
  16307. meta
  16308. };
  16309. completer(r);
  16310. };
  16311. const meta = {
  16312. filetype,
  16313. fieldname: entry.fieldname,
  16314. ...Optional.from(entry.meta).getOr({})
  16315. };
  16316. picker.call(editor, handler, entry.value, meta);
  16317. }));
  16318. const getTextSetting = value => Optional.from(value).filter(isString).getOrUndefined();
  16319. const getLinkInformation = editor => {
  16320. if (!useTypeaheadUrls(editor)) {
  16321. return Optional.none();
  16322. }
  16323. return Optional.some({
  16324. targets: LinkTargets.find(editor.getBody()),
  16325. anchorTop: getTextSetting(getAnchorTop(editor)),
  16326. anchorBottom: getTextSetting(getAnchorBottom(editor))
  16327. });
  16328. };
  16329. const getValidationHandler = editor => Optional.from(getFilePickerValidatorHandler(editor));
  16330. const UrlInputBackstage = editor => ({
  16331. getHistory,
  16332. addToHistory,
  16333. getLinkInformation: () => getLinkInformation(editor),
  16334. getValidationHandler: () => getValidationHandler(editor),
  16335. getUrlPicker: filetype => getUrlPicker(editor, filetype)
  16336. });
  16337. const init$7 = (lazySink, editor, lazyAnchorbar) => {
  16338. const contextMenuState = Cell(false);
  16339. const toolbar = HeaderBackstage(editor);
  16340. const backstage = {
  16341. shared: {
  16342. providers: {
  16343. icons: () => editor.ui.registry.getAll().icons,
  16344. menuItems: () => editor.ui.registry.getAll().menuItems,
  16345. translate: global$8.translate,
  16346. isDisabled: () => editor.mode.isReadOnly() || !editor.ui.isEnabled(),
  16347. getOption: editor.options.get
  16348. },
  16349. interpreter: s => interpretWithoutForm(s, {}, backstage),
  16350. anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  16351. header: toolbar,
  16352. getSink: lazySink
  16353. },
  16354. urlinput: UrlInputBackstage(editor),
  16355. styles: init$8(editor),
  16356. colorinput: ColorInputBackstage(editor),
  16357. dialog: DialogBackstage(editor),
  16358. isContextMenuOpen: () => contextMenuState.get(),
  16359. setContextMenuState: state => contextMenuState.set(state)
  16360. };
  16361. return backstage;
  16362. };
  16363. const setup$b = (editor, mothership, uiMothership) => {
  16364. const broadcastEvent = (name, evt) => {
  16365. each$1([
  16366. mothership,
  16367. uiMothership
  16368. ], ship => {
  16369. ship.broadcastEvent(name, evt);
  16370. });
  16371. };
  16372. const broadcastOn = (channel, message) => {
  16373. each$1([
  16374. mothership,
  16375. uiMothership
  16376. ], ship => {
  16377. ship.broadcastOn([channel], message);
  16378. });
  16379. };
  16380. const fireDismissPopups = evt => broadcastOn(dismissPopups(), { target: evt.target });
  16381. const doc = getDocument();
  16382. const onTouchstart = bind(doc, 'touchstart', fireDismissPopups);
  16383. const onTouchmove = bind(doc, 'touchmove', evt => broadcastEvent(documentTouchmove(), evt));
  16384. const onTouchend = bind(doc, 'touchend', evt => broadcastEvent(documentTouchend(), evt));
  16385. const onMousedown = bind(doc, 'mousedown', fireDismissPopups);
  16386. const onMouseup = bind(doc, 'mouseup', evt => {
  16387. if (evt.raw.button === 0) {
  16388. broadcastOn(mouseReleased(), { target: evt.target });
  16389. }
  16390. });
  16391. const onContentClick = raw => broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
  16392. const onContentMouseup = raw => {
  16393. if (raw.button === 0) {
  16394. broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
  16395. }
  16396. };
  16397. const onContentMousedown = () => {
  16398. each$1(editor.editorManager.get(), loopEditor => {
  16399. if (editor !== loopEditor) {
  16400. loopEditor.dispatch('DismissPopups', { relatedTarget: editor });
  16401. }
  16402. });
  16403. };
  16404. const onWindowScroll = evt => broadcastEvent(windowScroll(), fromRawEvent(evt));
  16405. const onWindowResize = evt => {
  16406. broadcastOn(repositionPopups(), {});
  16407. broadcastEvent(windowResize(), fromRawEvent(evt));
  16408. };
  16409. const onEditorResize = () => broadcastOn(repositionPopups(), {});
  16410. const onEditorProgress = evt => {
  16411. if (evt.state) {
  16412. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
  16413. }
  16414. };
  16415. const onDismissPopups = event => {
  16416. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
  16417. };
  16418. editor.on('PostRender', () => {
  16419. editor.on('click', onContentClick);
  16420. editor.on('tap', onContentClick);
  16421. editor.on('mouseup', onContentMouseup);
  16422. editor.on('mousedown', onContentMousedown);
  16423. editor.on('ScrollWindow', onWindowScroll);
  16424. editor.on('ResizeWindow', onWindowResize);
  16425. editor.on('ResizeEditor', onEditorResize);
  16426. editor.on('AfterProgressState', onEditorProgress);
  16427. editor.on('DismissPopups', onDismissPopups);
  16428. });
  16429. editor.on('remove', () => {
  16430. editor.off('click', onContentClick);
  16431. editor.off('tap', onContentClick);
  16432. editor.off('mouseup', onContentMouseup);
  16433. editor.off('mousedown', onContentMousedown);
  16434. editor.off('ScrollWindow', onWindowScroll);
  16435. editor.off('ResizeWindow', onWindowResize);
  16436. editor.off('ResizeEditor', onEditorResize);
  16437. editor.off('AfterProgressState', onEditorProgress);
  16438. editor.off('DismissPopups', onDismissPopups);
  16439. onMousedown.unbind();
  16440. onTouchstart.unbind();
  16441. onTouchmove.unbind();
  16442. onTouchend.unbind();
  16443. onMouseup.unbind();
  16444. });
  16445. editor.on('detach', () => {
  16446. detachSystem(mothership);
  16447. detachSystem(uiMothership);
  16448. mothership.destroy();
  16449. uiMothership.destroy();
  16450. });
  16451. };
  16452. const parts$a = AlloyParts;
  16453. const partType = PartType;
  16454. const schema$f = constant$1([
  16455. defaulted('shell', false),
  16456. required$1('makeItem'),
  16457. defaulted('setupItem', noop),
  16458. SketchBehaviours.field('listBehaviours', [Replacing])
  16459. ]);
  16460. const customListDetail = () => ({ behaviours: derive$1([Replacing.config({})]) });
  16461. const itemsPart = optional({
  16462. name: 'items',
  16463. overrides: customListDetail
  16464. });
  16465. const parts$9 = constant$1([itemsPart]);
  16466. const name = constant$1('CustomList');
  16467. const factory$d = (detail, components, _spec, _external) => {
  16468. const setItems = (list, items) => {
  16469. getListContainer(list).fold(() => {
  16470. console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  16471. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  16472. }, container => {
  16473. const itemComps = Replacing.contents(container);
  16474. const numListsRequired = items.length;
  16475. const numListsToAdd = numListsRequired - itemComps.length;
  16476. const itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, () => detail.makeItem()) : [];
  16477. const itemsToRemove = itemComps.slice(numListsRequired);
  16478. each$1(itemsToRemove, item => Replacing.remove(container, item));
  16479. each$1(itemsToAdd, item => Replacing.append(container, item));
  16480. const builtLists = Replacing.contents(container);
  16481. each$1(builtLists, (item, i) => {
  16482. detail.setupItem(list, item, items[i], i);
  16483. });
  16484. });
  16485. };
  16486. const extra = detail.shell ? {
  16487. behaviours: [Replacing.config({})],
  16488. components: []
  16489. } : {
  16490. behaviours: [],
  16491. components
  16492. };
  16493. const getListContainer = component => detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
  16494. return {
  16495. uid: detail.uid,
  16496. dom: detail.dom,
  16497. components: extra.components,
  16498. behaviours: augment(detail.listBehaviours, extra.behaviours),
  16499. apis: { setItems }
  16500. };
  16501. };
  16502. const CustomList = composite({
  16503. name: name(),
  16504. configFields: schema$f(),
  16505. partFields: parts$9(),
  16506. factory: factory$d,
  16507. apis: {
  16508. setItems: (apis, list, items) => {
  16509. apis.setItems(list, items);
  16510. }
  16511. }
  16512. });
  16513. const schema$e = constant$1([
  16514. required$1('dom'),
  16515. defaulted('shell', true),
  16516. field('toolbarBehaviours', [Replacing])
  16517. ]);
  16518. const enhanceGroups = () => ({ behaviours: derive$1([Replacing.config({})]) });
  16519. const parts$8 = constant$1([optional({
  16520. name: 'groups',
  16521. overrides: enhanceGroups
  16522. })]);
  16523. const factory$c = (detail, components, _spec, _externals) => {
  16524. const setGroups = (toolbar, groups) => {
  16525. getGroupContainer(toolbar).fold(() => {
  16526. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  16527. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  16528. }, container => {
  16529. Replacing.set(container, groups);
  16530. });
  16531. };
  16532. const getGroupContainer = component => detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  16533. const extra = detail.shell ? {
  16534. behaviours: [Replacing.config({})],
  16535. components: []
  16536. } : {
  16537. behaviours: [],
  16538. components
  16539. };
  16540. return {
  16541. uid: detail.uid,
  16542. dom: detail.dom,
  16543. components: extra.components,
  16544. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  16545. apis: { setGroups },
  16546. domModification: { attributes: { role: 'group' } }
  16547. };
  16548. };
  16549. const Toolbar = composite({
  16550. name: 'Toolbar',
  16551. configFields: schema$e(),
  16552. partFields: parts$8(),
  16553. factory: factory$c,
  16554. apis: {
  16555. setGroups: (apis, toolbar, groups) => {
  16556. apis.setGroups(toolbar, groups);
  16557. }
  16558. }
  16559. });
  16560. const setup$a = noop;
  16561. const isDocked$2 = never;
  16562. const getBehaviours$1 = constant$1([]);
  16563. var StaticHeader = /*#__PURE__*/Object.freeze({
  16564. __proto__: null,
  16565. setup: setup$a,
  16566. isDocked: isDocked$2,
  16567. getBehaviours: getBehaviours$1
  16568. });
  16569. const getOffsetParent = element => {
  16570. const isFixed = is$1(getRaw(element, 'position'), 'fixed');
  16571. const offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
  16572. return offsetParent$1.orThunk(() => {
  16573. const marker = SugarElement.fromTag('span');
  16574. return parent(element).bind(parent => {
  16575. append$2(parent, marker);
  16576. const offsetParent$1 = offsetParent(marker);
  16577. remove$5(marker);
  16578. return offsetParent$1;
  16579. });
  16580. });
  16581. };
  16582. const getOrigin = element => getOffsetParent(element).map(absolute$3).getOrThunk(() => SugarPosition(0, 0));
  16583. const morphAdt = Adt.generate([
  16584. { static: [] },
  16585. { absolute: ['positionCss'] },
  16586. { fixed: ['positionCss'] }
  16587. ]);
  16588. const appear = (component, contextualInfo) => {
  16589. const elem = component.element;
  16590. add$2(elem, contextualInfo.transitionClass);
  16591. remove$2(elem, contextualInfo.fadeOutClass);
  16592. add$2(elem, contextualInfo.fadeInClass);
  16593. contextualInfo.onShow(component);
  16594. };
  16595. const disappear = (component, contextualInfo) => {
  16596. const elem = component.element;
  16597. add$2(elem, contextualInfo.transitionClass);
  16598. remove$2(elem, contextualInfo.fadeInClass);
  16599. add$2(elem, contextualInfo.fadeOutClass);
  16600. contextualInfo.onHide(component);
  16601. };
  16602. const isPartiallyVisible = (box, viewport) => box.y < viewport.bottom && box.bottom > viewport.y;
  16603. const isTopCompletelyVisible = (box, viewport) => box.y >= viewport.y;
  16604. const isBottomCompletelyVisible = (box, viewport) => box.bottom <= viewport.bottom;
  16605. const isVisibleForModes = (modes, box, viewport) => forall(modes, mode => {
  16606. switch (mode) {
  16607. case 'bottom':
  16608. return isBottomCompletelyVisible(box, viewport);
  16609. case 'top':
  16610. return isTopCompletelyVisible(box, viewport);
  16611. }
  16612. });
  16613. const getPrior = (elem, state) => state.getInitialPos().map(pos => bounds(pos.bounds.x, pos.bounds.y, get$c(elem), get$d(elem)));
  16614. const storePrior = (elem, box, state) => {
  16615. state.setInitialPos({
  16616. style: getAllRaw(elem),
  16617. position: get$e(elem, 'position') || 'static',
  16618. bounds: box
  16619. });
  16620. };
  16621. const revertToOriginal = (elem, box, state) => state.getInitialPos().bind(position => {
  16622. state.clearInitialPos();
  16623. switch (position.position) {
  16624. case 'static':
  16625. return Optional.some(morphAdt.static());
  16626. case 'absolute':
  16627. const offsetBox = getOffsetParent(elem).map(box$1).getOrThunk(() => box$1(body()));
  16628. return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$g(position.style, 'left').map(_left => box.x - offsetBox.x), get$g(position.style, 'top').map(_top => box.y - offsetBox.y), get$g(position.style, 'right').map(_right => offsetBox.right - box.right), get$g(position.style, 'bottom').map(_bottom => offsetBox.bottom - box.bottom))));
  16629. default:
  16630. return Optional.none();
  16631. }
  16632. });
  16633. const morphToOriginal = (elem, viewport, state) => getPrior(elem, state).filter(box => isVisibleForModes(state.getModes(), box, viewport)).bind(box => revertToOriginal(elem, box, state));
  16634. const morphToFixed = (elem, viewport, state) => {
  16635. const box = box$1(elem);
  16636. if (!isVisibleForModes(state.getModes(), box, viewport)) {
  16637. storePrior(elem, box, state);
  16638. const winBox = win();
  16639. const left = box.x - winBox.x;
  16640. const top = viewport.y - winBox.y;
  16641. const bottom = winBox.bottom - viewport.bottom;
  16642. const isTop = box.y <= viewport.y;
  16643. return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none())));
  16644. } else {
  16645. return Optional.none();
  16646. }
  16647. };
  16648. const getMorph = (component, viewport, state) => {
  16649. const elem = component.element;
  16650. const isDocked = is$1(getRaw(elem, 'position'), 'fixed');
  16651. return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  16652. };
  16653. const getMorphToOriginal = (component, state) => {
  16654. const elem = component.element;
  16655. return getPrior(elem, state).bind(box => revertToOriginal(elem, box, state));
  16656. };
  16657. const morphToStatic = (component, config, state) => {
  16658. state.setDocked(false);
  16659. each$1([
  16660. 'left',
  16661. 'right',
  16662. 'top',
  16663. 'bottom',
  16664. 'position'
  16665. ], prop => remove$6(component.element, prop));
  16666. config.onUndocked(component);
  16667. };
  16668. const morphToCoord = (component, config, state, position) => {
  16669. const isDocked = position.position === 'fixed';
  16670. state.setDocked(isDocked);
  16671. applyPositionCss(component.element, position);
  16672. const method = isDocked ? config.onDocked : config.onUndocked;
  16673. method(component);
  16674. };
  16675. const updateVisibility = (component, config, state, viewport, morphToDocked = false) => {
  16676. config.contextual.each(contextInfo => {
  16677. contextInfo.lazyContext(component).each(box => {
  16678. const isVisible = isPartiallyVisible(box, viewport);
  16679. if (isVisible !== state.isVisible()) {
  16680. state.setVisible(isVisible);
  16681. if (morphToDocked && !isVisible) {
  16682. add$1(component.element, [contextInfo.fadeOutClass]);
  16683. contextInfo.onHide(component);
  16684. } else {
  16685. const method = isVisible ? appear : disappear;
  16686. method(component, contextInfo);
  16687. }
  16688. }
  16689. });
  16690. });
  16691. };
  16692. const refreshInternal = (component, config, state) => {
  16693. const viewport = config.lazyViewport(component);
  16694. const isDocked = state.isDocked();
  16695. if (isDocked) {
  16696. updateVisibility(component, config, state, viewport);
  16697. }
  16698. getMorph(component, viewport, state).each(morph => {
  16699. morph.fold(() => morphToStatic(component, config, state), position => morphToCoord(component, config, state, position), position => {
  16700. updateVisibility(component, config, state, viewport, true);
  16701. morphToCoord(component, config, state, position);
  16702. });
  16703. });
  16704. };
  16705. const resetInternal = (component, config, state) => {
  16706. const elem = component.element;
  16707. state.setDocked(false);
  16708. getMorphToOriginal(component, state).each(morph => {
  16709. morph.fold(() => morphToStatic(component, config, state), position => morphToCoord(component, config, state, position), noop);
  16710. });
  16711. state.setVisible(true);
  16712. config.contextual.each(contextInfo => {
  16713. remove$1(elem, [
  16714. contextInfo.fadeInClass,
  16715. contextInfo.fadeOutClass,
  16716. contextInfo.transitionClass
  16717. ]);
  16718. contextInfo.onShow(component);
  16719. });
  16720. refresh$4(component, config, state);
  16721. };
  16722. const refresh$4 = (component, config, state) => {
  16723. if (component.getSystem().isConnected()) {
  16724. refreshInternal(component, config, state);
  16725. }
  16726. };
  16727. const reset = (component, config, state) => {
  16728. if (state.isDocked()) {
  16729. resetInternal(component, config, state);
  16730. }
  16731. };
  16732. const isDocked$1 = (component, config, state) => state.isDocked();
  16733. const setModes = (component, config, state, modes) => state.setModes(modes);
  16734. const getModes = (component, config, state) => state.getModes();
  16735. var DockingApis = /*#__PURE__*/Object.freeze({
  16736. __proto__: null,
  16737. refresh: refresh$4,
  16738. reset: reset,
  16739. isDocked: isDocked$1,
  16740. getModes: getModes,
  16741. setModes: setModes
  16742. });
  16743. const events$5 = (dockInfo, dockState) => derive$2([
  16744. runOnSource(transitionend(), (component, simulatedEvent) => {
  16745. dockInfo.contextual.each(contextInfo => {
  16746. if (has(component.element, contextInfo.transitionClass)) {
  16747. remove$1(component.element, [
  16748. contextInfo.transitionClass,
  16749. contextInfo.fadeInClass
  16750. ]);
  16751. const notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  16752. notify(component);
  16753. }
  16754. simulatedEvent.stop();
  16755. });
  16756. }),
  16757. run$1(windowScroll(), (component, _) => {
  16758. refresh$4(component, dockInfo, dockState);
  16759. }),
  16760. run$1(windowResize(), (component, _) => {
  16761. reset(component, dockInfo, dockState);
  16762. })
  16763. ]);
  16764. var ActiveDocking = /*#__PURE__*/Object.freeze({
  16765. __proto__: null,
  16766. events: events$5
  16767. });
  16768. var DockingSchema = [
  16769. optionObjOf('contextual', [
  16770. requiredString('fadeInClass'),
  16771. requiredString('fadeOutClass'),
  16772. requiredString('transitionClass'),
  16773. requiredFunction('lazyContext'),
  16774. onHandler('onShow'),
  16775. onHandler('onShown'),
  16776. onHandler('onHide'),
  16777. onHandler('onHidden')
  16778. ]),
  16779. defaultedFunction('lazyViewport', win),
  16780. defaultedArrayOf('modes', [
  16781. 'top',
  16782. 'bottom'
  16783. ], string),
  16784. onHandler('onDocked'),
  16785. onHandler('onUndocked')
  16786. ];
  16787. const init$6 = spec => {
  16788. const docked = Cell(false);
  16789. const visible = Cell(true);
  16790. const initialBounds = value$2();
  16791. const modes = Cell(spec.modes);
  16792. const readState = () => `docked: ${ docked.get() }, visible: ${ visible.get() }, modes: ${ modes.get().join(',') }`;
  16793. return nu$8({
  16794. isDocked: docked.get,
  16795. setDocked: docked.set,
  16796. getInitialPos: initialBounds.get,
  16797. setInitialPos: initialBounds.set,
  16798. clearInitialPos: initialBounds.clear,
  16799. isVisible: visible.get,
  16800. setVisible: visible.set,
  16801. getModes: modes.get,
  16802. setModes: modes.set,
  16803. readState
  16804. });
  16805. };
  16806. var DockingState = /*#__PURE__*/Object.freeze({
  16807. __proto__: null,
  16808. init: init$6
  16809. });
  16810. const Docking = create$3({
  16811. fields: DockingSchema,
  16812. name: 'docking',
  16813. active: ActiveDocking,
  16814. apis: DockingApis,
  16815. state: DockingState
  16816. });
  16817. const toolbarHeightChange = constant$1(generate$6('toolbar-height-change'));
  16818. const visibility = {
  16819. fadeInClass: 'tox-editor-dock-fadein',
  16820. fadeOutClass: 'tox-editor-dock-fadeout',
  16821. transitionClass: 'tox-editor-dock-transition'
  16822. };
  16823. const editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  16824. const editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  16825. const scrollFromBehindHeader = (e, containerHeader) => {
  16826. const doc = owner$4(containerHeader);
  16827. const viewHeight = doc.dom.defaultView.innerHeight;
  16828. const scrollPos = get$b(doc);
  16829. const markerElement = SugarElement.fromDom(e.elm);
  16830. const markerPos = absolute$2(markerElement);
  16831. const markerHeight = get$d(markerElement);
  16832. const markerTop = markerPos.y;
  16833. const markerBottom = markerTop + markerHeight;
  16834. const editorHeaderPos = absolute$3(containerHeader);
  16835. const editorHeaderHeight = get$d(containerHeader);
  16836. const editorHeaderTop = editorHeaderPos.top;
  16837. const editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  16838. const editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
  16839. const editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
  16840. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  16841. to(scrollPos.left, markerTop - editorHeaderHeight, doc);
  16842. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  16843. const y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  16844. to(scrollPos.left, y, doc);
  16845. }
  16846. };
  16847. const isDockedMode = (header, mode) => contains$2(Docking.getModes(header), mode);
  16848. const updateIframeContentFlow = header => {
  16849. const getOccupiedHeight = elm => getOuter$2(elm) + (parseInt(get$e(elm, 'margin-top'), 10) || 0) + (parseInt(get$e(elm, 'margin-bottom'), 10) || 0);
  16850. const elm = header.element;
  16851. parent(elm).each(parentElem => {
  16852. const padding = 'padding-' + Docking.getModes(header)[0];
  16853. if (Docking.isDocked(header)) {
  16854. const parentWidth = get$c(parentElem);
  16855. set$8(elm, 'width', parentWidth + 'px');
  16856. set$8(parentElem, padding, getOccupiedHeight(elm) + 'px');
  16857. } else {
  16858. remove$6(elm, 'width');
  16859. remove$6(parentElem, padding);
  16860. }
  16861. });
  16862. };
  16863. const updateSinkVisibility = (sinkElem, visible) => {
  16864. if (visible) {
  16865. remove$2(sinkElem, visibility.fadeOutClass);
  16866. add$1(sinkElem, [
  16867. visibility.transitionClass,
  16868. visibility.fadeInClass
  16869. ]);
  16870. } else {
  16871. remove$2(sinkElem, visibility.fadeInClass);
  16872. add$1(sinkElem, [
  16873. visibility.fadeOutClass,
  16874. visibility.transitionClass
  16875. ]);
  16876. }
  16877. };
  16878. const updateEditorClasses = (editor, docked) => {
  16879. const editorContainer = SugarElement.fromDom(editor.getContainer());
  16880. if (docked) {
  16881. add$2(editorContainer, editorStickyOnClass);
  16882. remove$2(editorContainer, editorStickyOffClass);
  16883. } else {
  16884. add$2(editorContainer, editorStickyOffClass);
  16885. remove$2(editorContainer, editorStickyOnClass);
  16886. }
  16887. };
  16888. const restoreFocus = (headerElem, focusedElem) => {
  16889. const ownerDoc = owner$4(focusedElem);
  16890. active$1(ownerDoc).filter(activeElm => !eq(focusedElem, activeElm)).filter(activeElm => eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm)).each(() => focus$3(focusedElem));
  16891. };
  16892. const findFocusedElem = (rootElm, lazySink) => search(rootElm).orThunk(() => lazySink().toOptional().bind(sink => search(sink.element)));
  16893. const setup$9 = (editor, sharedBackstage, lazyHeader) => {
  16894. if (!editor.inline) {
  16895. if (!sharedBackstage.header.isPositionedAtTop()) {
  16896. editor.on('ResizeEditor', () => {
  16897. lazyHeader().each(Docking.reset);
  16898. });
  16899. }
  16900. editor.on('ResizeWindow ResizeEditor', () => {
  16901. lazyHeader().each(updateIframeContentFlow);
  16902. });
  16903. editor.on('SkinLoaded', () => {
  16904. lazyHeader().each(comp => {
  16905. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  16906. });
  16907. });
  16908. editor.on('FullscreenStateChanged', () => {
  16909. lazyHeader().each(Docking.reset);
  16910. });
  16911. }
  16912. editor.on('AfterScrollIntoView', e => {
  16913. lazyHeader().each(header => {
  16914. Docking.refresh(header);
  16915. const headerElem = header.element;
  16916. if (isVisible(headerElem)) {
  16917. scrollFromBehindHeader(e, headerElem);
  16918. }
  16919. });
  16920. });
  16921. editor.on('PostRender', () => {
  16922. updateEditorClasses(editor, false);
  16923. });
  16924. };
  16925. const isDocked = lazyHeader => lazyHeader().map(Docking.isDocked).getOr(false);
  16926. const getIframeBehaviours = () => [Receiving.config({ channels: { [toolbarHeightChange()]: { onReceive: updateIframeContentFlow } } })];
  16927. const getBehaviours = (editor, sharedBackstage) => {
  16928. const focusedElm = value$2();
  16929. const lazySink = sharedBackstage.getSink;
  16930. const runOnSinkElement = f => {
  16931. lazySink().each(sink => f(sink.element));
  16932. };
  16933. const onDockingSwitch = comp => {
  16934. if (!editor.inline) {
  16935. updateIframeContentFlow(comp);
  16936. }
  16937. updateEditorClasses(editor, Docking.isDocked(comp));
  16938. comp.getSystem().broadcastOn([repositionPopups()], {});
  16939. lazySink().each(sink => sink.getSystem().broadcastOn([repositionPopups()], {}));
  16940. };
  16941. const additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  16942. return [
  16943. Focusing.config({}),
  16944. Docking.config({
  16945. contextual: {
  16946. lazyContext: comp => {
  16947. const headerHeight = getOuter$2(comp.element);
  16948. const container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  16949. const box = box$1(SugarElement.fromDom(container));
  16950. const boxHeight = box.height - headerHeight;
  16951. const topBound = box.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  16952. return Optional.some(bounds(box.x, topBound, box.width, boxHeight));
  16953. },
  16954. onShow: () => {
  16955. runOnSinkElement(elem => updateSinkVisibility(elem, true));
  16956. },
  16957. onShown: comp => {
  16958. runOnSinkElement(elem => remove$1(elem, [
  16959. visibility.transitionClass,
  16960. visibility.fadeInClass
  16961. ]));
  16962. focusedElm.get().each(elem => {
  16963. restoreFocus(comp.element, elem);
  16964. focusedElm.clear();
  16965. });
  16966. },
  16967. onHide: comp => {
  16968. findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
  16969. runOnSinkElement(elem => updateSinkVisibility(elem, false));
  16970. },
  16971. onHidden: () => {
  16972. runOnSinkElement(elem => remove$1(elem, [visibility.transitionClass]));
  16973. },
  16974. ...visibility
  16975. },
  16976. lazyViewport: comp => {
  16977. const win$1 = win();
  16978. const offset = getStickyToolbarOffset(editor);
  16979. const top = win$1.y + (isDockedMode(comp, 'top') ? offset : 0);
  16980. const height = win$1.height - (isDockedMode(comp, 'bottom') ? offset : 0);
  16981. return bounds(win$1.x, top, win$1.width, height);
  16982. },
  16983. modes: [sharedBackstage.header.getDockingMode()],
  16984. onDocked: onDockingSwitch,
  16985. onUndocked: onDockingSwitch
  16986. }),
  16987. ...additionalBehaviours
  16988. ];
  16989. };
  16990. var StickyHeader = /*#__PURE__*/Object.freeze({
  16991. __proto__: null,
  16992. setup: setup$9,
  16993. isDocked: isDocked,
  16994. getBehaviours: getBehaviours
  16995. });
  16996. const renderHeader = spec => {
  16997. const editor = spec.editor;
  16998. const getBehaviours$2 = spec.sticky ? getBehaviours : getBehaviours$1;
  16999. return {
  17000. uid: spec.uid,
  17001. dom: spec.dom,
  17002. components: spec.components,
  17003. behaviours: derive$1(getBehaviours$2(editor, spec.sharedBackstage))
  17004. };
  17005. };
  17006. const groupToolbarButtonSchema = objOf([
  17007. type,
  17008. requiredOf('items', oneOf([
  17009. arrOfObj([
  17010. name$1,
  17011. requiredArrayOf('items', string)
  17012. ]),
  17013. string
  17014. ]))
  17015. ].concat(baseToolbarButtonFields));
  17016. const createGroupToolbarButton = spec => asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  17017. const baseMenuButtonFields = [
  17018. optionString('text'),
  17019. optionString('tooltip'),
  17020. optionString('icon'),
  17021. requiredFunction('fetch'),
  17022. defaultedFunction('onSetup', () => noop)
  17023. ];
  17024. const MenuButtonSchema = objOf([
  17025. type,
  17026. ...baseMenuButtonFields
  17027. ]);
  17028. const createMenuButton = spec => asRaw('menubutton', MenuButtonSchema, spec);
  17029. const splitButtonSchema = objOf([
  17030. type,
  17031. optionalTooltip,
  17032. optionalIcon,
  17033. optionalText,
  17034. optionalSelect,
  17035. fetch$1,
  17036. onSetup,
  17037. defaultedStringEnum('presets', 'normal', [
  17038. 'normal',
  17039. 'color',
  17040. 'listpreview'
  17041. ]),
  17042. defaultedColumns(1),
  17043. onAction,
  17044. onItemAction
  17045. ]);
  17046. const createSplitButton = spec => asRaw('SplitButton', splitButtonSchema, spec);
  17047. const factory$b = (detail, spec) => {
  17048. const setMenus = (comp, menus) => {
  17049. const newMenus = map$2(menus, m => {
  17050. const buttonSpec = {
  17051. type: 'menubutton',
  17052. text: m.text,
  17053. fetch: callback => {
  17054. callback(m.getItems());
  17055. }
  17056. };
  17057. const internal = createMenuButton(buttonSpec).mapError(errInfo => formatError(errInfo)).getOrDie();
  17058. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
  17059. });
  17060. Replacing.set(comp, newMenus);
  17061. };
  17062. const apis = {
  17063. focus: Keying.focusIn,
  17064. setMenus
  17065. };
  17066. return {
  17067. uid: detail.uid,
  17068. dom: detail.dom,
  17069. components: [],
  17070. behaviours: derive$1([
  17071. Replacing.config({}),
  17072. config('menubar-events', [
  17073. runOnAttached(component => {
  17074. detail.onSetup(component);
  17075. }),
  17076. run$1(mouseover(), (comp, se) => {
  17077. descendant(comp.element, '.' + 'tox-mbtn--active').each(activeButton => {
  17078. closest$1(se.event.target, '.' + 'tox-mbtn').each(hoveredButton => {
  17079. if (!eq(activeButton, hoveredButton)) {
  17080. comp.getSystem().getByDom(activeButton).each(activeComp => {
  17081. comp.getSystem().getByDom(hoveredButton).each(hoveredComp => {
  17082. Dropdown.expand(hoveredComp);
  17083. Dropdown.close(activeComp);
  17084. Focusing.focus(hoveredComp);
  17085. });
  17086. });
  17087. }
  17088. });
  17089. });
  17090. }),
  17091. run$1(focusShifted(), (comp, se) => {
  17092. se.event.prevFocus.bind(prev => comp.getSystem().getByDom(prev).toOptional()).each(prev => {
  17093. se.event.newFocus.bind(nu => comp.getSystem().getByDom(nu).toOptional()).each(nu => {
  17094. if (Dropdown.isOpen(prev)) {
  17095. Dropdown.expand(nu);
  17096. Dropdown.close(prev);
  17097. }
  17098. });
  17099. });
  17100. })
  17101. ]),
  17102. Keying.config({
  17103. mode: 'flow',
  17104. selector: '.' + 'tox-mbtn',
  17105. onEscape: comp => {
  17106. detail.onEscape(comp);
  17107. return Optional.some(true);
  17108. }
  17109. }),
  17110. Tabstopping.config({})
  17111. ]),
  17112. apis,
  17113. domModification: { attributes: { role: 'menubar' } }
  17114. };
  17115. };
  17116. var SilverMenubar = single({
  17117. factory: factory$b,
  17118. name: 'silver.Menubar',
  17119. configFields: [
  17120. required$1('dom'),
  17121. required$1('uid'),
  17122. required$1('onEscape'),
  17123. required$1('backstage'),
  17124. defaulted('onSetup', noop)
  17125. ],
  17126. apis: {
  17127. focus: (apis, comp) => {
  17128. apis.focus(comp);
  17129. },
  17130. setMenus: (apis, comp, menus) => {
  17131. apis.setMenus(comp, menus);
  17132. }
  17133. }
  17134. });
  17135. const getAnimationRoot = (component, slideConfig) => slideConfig.getAnimationRoot.fold(() => component.element, get => get(component));
  17136. const getDimensionProperty = slideConfig => slideConfig.dimension.property;
  17137. const getDimension = (slideConfig, elem) => slideConfig.dimension.getDimension(elem);
  17138. const disableTransitions = (component, slideConfig) => {
  17139. const root = getAnimationRoot(component, slideConfig);
  17140. remove$1(root, [
  17141. slideConfig.shrinkingClass,
  17142. slideConfig.growingClass
  17143. ]);
  17144. };
  17145. const setShrunk = (component, slideConfig) => {
  17146. remove$2(component.element, slideConfig.openClass);
  17147. add$2(component.element, slideConfig.closedClass);
  17148. set$8(component.element, getDimensionProperty(slideConfig), '0px');
  17149. reflow(component.element);
  17150. };
  17151. const setGrown = (component, slideConfig) => {
  17152. remove$2(component.element, slideConfig.closedClass);
  17153. add$2(component.element, slideConfig.openClass);
  17154. remove$6(component.element, getDimensionProperty(slideConfig));
  17155. };
  17156. const doImmediateShrink = (component, slideConfig, slideState, _calculatedSize) => {
  17157. slideState.setCollapsed();
  17158. set$8(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  17159. reflow(component.element);
  17160. disableTransitions(component, slideConfig);
  17161. setShrunk(component, slideConfig);
  17162. slideConfig.onStartShrink(component);
  17163. slideConfig.onShrunk(component);
  17164. };
  17165. const doStartShrink = (component, slideConfig, slideState, calculatedSize) => {
  17166. const size = calculatedSize.getOrThunk(() => getDimension(slideConfig, component.element));
  17167. slideState.setCollapsed();
  17168. set$8(component.element, getDimensionProperty(slideConfig), size);
  17169. reflow(component.element);
  17170. const root = getAnimationRoot(component, slideConfig);
  17171. remove$2(root, slideConfig.growingClass);
  17172. add$2(root, slideConfig.shrinkingClass);
  17173. setShrunk(component, slideConfig);
  17174. slideConfig.onStartShrink(component);
  17175. };
  17176. const doStartSmartShrink = (component, slideConfig, slideState) => {
  17177. const size = getDimension(slideConfig, component.element);
  17178. const shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  17179. shrinker(component, slideConfig, slideState, Optional.some(size));
  17180. };
  17181. const doStartGrow = (component, slideConfig, slideState) => {
  17182. const root = getAnimationRoot(component, slideConfig);
  17183. const wasShrinking = has(root, slideConfig.shrinkingClass);
  17184. const beforeSize = getDimension(slideConfig, component.element);
  17185. setGrown(component, slideConfig);
  17186. const fullSize = getDimension(slideConfig, component.element);
  17187. const startPartialGrow = () => {
  17188. set$8(component.element, getDimensionProperty(slideConfig), beforeSize);
  17189. reflow(component.element);
  17190. };
  17191. const startCompleteGrow = () => {
  17192. setShrunk(component, slideConfig);
  17193. };
  17194. const setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  17195. setStartSize();
  17196. remove$2(root, slideConfig.shrinkingClass);
  17197. add$2(root, slideConfig.growingClass);
  17198. setGrown(component, slideConfig);
  17199. set$8(component.element, getDimensionProperty(slideConfig), fullSize);
  17200. slideState.setExpanded();
  17201. slideConfig.onStartGrow(component);
  17202. };
  17203. const refresh$3 = (component, slideConfig, slideState) => {
  17204. if (slideState.isExpanded()) {
  17205. remove$6(component.element, getDimensionProperty(slideConfig));
  17206. const fullSize = getDimension(slideConfig, component.element);
  17207. set$8(component.element, getDimensionProperty(slideConfig), fullSize);
  17208. }
  17209. };
  17210. const grow = (component, slideConfig, slideState) => {
  17211. if (!slideState.isExpanded()) {
  17212. doStartGrow(component, slideConfig, slideState);
  17213. }
  17214. };
  17215. const shrink = (component, slideConfig, slideState) => {
  17216. if (slideState.isExpanded()) {
  17217. doStartSmartShrink(component, slideConfig, slideState);
  17218. }
  17219. };
  17220. const immediateShrink = (component, slideConfig, slideState) => {
  17221. if (slideState.isExpanded()) {
  17222. doImmediateShrink(component, slideConfig, slideState);
  17223. }
  17224. };
  17225. const hasGrown = (component, slideConfig, slideState) => slideState.isExpanded();
  17226. const hasShrunk = (component, slideConfig, slideState) => slideState.isCollapsed();
  17227. const isGrowing = (component, slideConfig, _slideState) => {
  17228. const root = getAnimationRoot(component, slideConfig);
  17229. return has(root, slideConfig.growingClass) === true;
  17230. };
  17231. const isShrinking = (component, slideConfig, _slideState) => {
  17232. const root = getAnimationRoot(component, slideConfig);
  17233. return has(root, slideConfig.shrinkingClass) === true;
  17234. };
  17235. const isTransitioning = (component, slideConfig, slideState) => isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  17236. const toggleGrow = (component, slideConfig, slideState) => {
  17237. const f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  17238. f(component, slideConfig, slideState);
  17239. };
  17240. var SlidingApis = /*#__PURE__*/Object.freeze({
  17241. __proto__: null,
  17242. refresh: refresh$3,
  17243. grow: grow,
  17244. shrink: shrink,
  17245. immediateShrink: immediateShrink,
  17246. hasGrown: hasGrown,
  17247. hasShrunk: hasShrunk,
  17248. isGrowing: isGrowing,
  17249. isShrinking: isShrinking,
  17250. isTransitioning: isTransitioning,
  17251. toggleGrow: toggleGrow,
  17252. disableTransitions: disableTransitions
  17253. });
  17254. const exhibit = (base, slideConfig, _slideState) => {
  17255. const expanded = slideConfig.expanded;
  17256. return expanded ? nu$7({
  17257. classes: [slideConfig.openClass],
  17258. styles: {}
  17259. }) : nu$7({
  17260. classes: [slideConfig.closedClass],
  17261. styles: wrap$1(slideConfig.dimension.property, '0px')
  17262. });
  17263. };
  17264. const events$4 = (slideConfig, slideState) => derive$2([runOnSource(transitionend(), (component, simulatedEvent) => {
  17265. const raw = simulatedEvent.event.raw;
  17266. if (raw.propertyName === slideConfig.dimension.property) {
  17267. disableTransitions(component, slideConfig);
  17268. if (slideState.isExpanded()) {
  17269. remove$6(component.element, slideConfig.dimension.property);
  17270. }
  17271. const notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  17272. notify(component);
  17273. }
  17274. })]);
  17275. var ActiveSliding = /*#__PURE__*/Object.freeze({
  17276. __proto__: null,
  17277. exhibit: exhibit,
  17278. events: events$4
  17279. });
  17280. var SlidingSchema = [
  17281. required$1('closedClass'),
  17282. required$1('openClass'),
  17283. required$1('shrinkingClass'),
  17284. required$1('growingClass'),
  17285. option$3('getAnimationRoot'),
  17286. onHandler('onShrunk'),
  17287. onHandler('onStartShrink'),
  17288. onHandler('onGrown'),
  17289. onHandler('onStartGrow'),
  17290. defaulted('expanded', false),
  17291. requiredOf('dimension', choose$1('property', {
  17292. width: [
  17293. output$1('property', 'width'),
  17294. output$1('getDimension', elem => get$c(elem) + 'px')
  17295. ],
  17296. height: [
  17297. output$1('property', 'height'),
  17298. output$1('getDimension', elem => get$d(elem) + 'px')
  17299. ]
  17300. }))
  17301. ];
  17302. const init$5 = spec => {
  17303. const state = Cell(spec.expanded);
  17304. const readState = () => 'expanded: ' + state.get();
  17305. return nu$8({
  17306. isExpanded: () => state.get() === true,
  17307. isCollapsed: () => state.get() === false,
  17308. setCollapsed: curry(state.set, false),
  17309. setExpanded: curry(state.set, true),
  17310. readState
  17311. });
  17312. };
  17313. var SlidingState = /*#__PURE__*/Object.freeze({
  17314. __proto__: null,
  17315. init: init$5
  17316. });
  17317. const Sliding = create$3({
  17318. fields: SlidingSchema,
  17319. name: 'sliding',
  17320. active: ActiveSliding,
  17321. apis: SlidingApis,
  17322. state: SlidingState
  17323. });
  17324. const owner = 'container';
  17325. const schema$d = [field('slotBehaviours', [])];
  17326. const getPartName = name => '<alloy.field.' + name + '>';
  17327. const sketch = sSpec => {
  17328. const parts = (() => {
  17329. const record = [];
  17330. const slot = (name, config) => {
  17331. record.push(name);
  17332. return generateOne$1(owner, getPartName(name), config);
  17333. };
  17334. return {
  17335. slot,
  17336. record: constant$1(record)
  17337. };
  17338. })();
  17339. const spec = sSpec(parts);
  17340. const partNames = parts.record();
  17341. const fieldParts = map$2(partNames, n => required({
  17342. name: n,
  17343. pname: getPartName(n)
  17344. }));
  17345. return composite$1(owner, schema$d, fieldParts, make$1, spec);
  17346. };
  17347. const make$1 = (detail, components) => {
  17348. const getSlotNames = _ => getAllPartNames(detail);
  17349. const getSlot = (container, key) => getPart(container, detail, key);
  17350. const onSlot = (f, def) => (container, key) => getPart(container, detail, key).map(slot => f(slot, key)).getOr(def);
  17351. const onSlots = f => (container, keys) => {
  17352. each$1(keys, key => f(container, key));
  17353. };
  17354. const doShowing = (comp, _key) => get$f(comp.element, 'aria-hidden') !== 'true';
  17355. const doShow = (comp, key) => {
  17356. if (!doShowing(comp)) {
  17357. const element = comp.element;
  17358. remove$6(element, 'display');
  17359. remove$7(element, 'aria-hidden');
  17360. emitWith(comp, slotVisibility(), {
  17361. name: key,
  17362. visible: true
  17363. });
  17364. }
  17365. };
  17366. const doHide = (comp, key) => {
  17367. if (doShowing(comp)) {
  17368. const element = comp.element;
  17369. set$8(element, 'display', 'none');
  17370. set$9(element, 'aria-hidden', 'true');
  17371. emitWith(comp, slotVisibility(), {
  17372. name: key,
  17373. visible: false
  17374. });
  17375. }
  17376. };
  17377. const isShowing = onSlot(doShowing, false);
  17378. const hideSlot = onSlot(doHide);
  17379. const hideSlots = onSlots(hideSlot);
  17380. const hideAllSlots = container => hideSlots(container, getSlotNames());
  17381. const showSlot = onSlot(doShow);
  17382. const apis = {
  17383. getSlotNames,
  17384. getSlot,
  17385. isShowing,
  17386. hideSlot,
  17387. hideAllSlots,
  17388. showSlot
  17389. };
  17390. return {
  17391. uid: detail.uid,
  17392. dom: detail.dom,
  17393. components,
  17394. behaviours: get$3(detail.slotBehaviours),
  17395. apis
  17396. };
  17397. };
  17398. const slotApis = map$1({
  17399. getSlotNames: (apis, c) => apis.getSlotNames(c),
  17400. getSlot: (apis, c, key) => apis.getSlot(c, key),
  17401. isShowing: (apis, c, key) => apis.isShowing(c, key),
  17402. hideSlot: (apis, c, key) => apis.hideSlot(c, key),
  17403. hideAllSlots: (apis, c) => apis.hideAllSlots(c),
  17404. showSlot: (apis, c, key) => apis.showSlot(c, key)
  17405. }, value => makeApi(value));
  17406. const SlotContainer = {
  17407. ...slotApis,
  17408. ...{ sketch }
  17409. };
  17410. const sidebarSchema = objOf([
  17411. optionalIcon,
  17412. optionalTooltip,
  17413. defaultedFunction('onShow', noop),
  17414. defaultedFunction('onHide', noop),
  17415. onSetup
  17416. ]);
  17417. const createSidebar = spec => asRaw('sidebar', sidebarSchema, spec);
  17418. const setup$8 = editor => {
  17419. const {sidebars} = editor.ui.registry.getAll();
  17420. each$1(keys(sidebars), name => {
  17421. const spec = sidebars[name];
  17422. const isActive = () => is$1(Optional.from(editor.queryCommandValue('ToggleSidebar')), name);
  17423. editor.ui.registry.addToggleButton(name, {
  17424. icon: spec.icon,
  17425. tooltip: spec.tooltip,
  17426. onAction: buttonApi => {
  17427. editor.execCommand('ToggleSidebar', false, name);
  17428. buttonApi.setActive(isActive());
  17429. },
  17430. onSetup: buttonApi => {
  17431. const handleToggle = () => buttonApi.setActive(isActive());
  17432. editor.on('ToggleSidebar', handleToggle);
  17433. return () => {
  17434. editor.off('ToggleSidebar', handleToggle);
  17435. };
  17436. }
  17437. });
  17438. });
  17439. };
  17440. const getApi = comp => ({ element: () => comp.element.dom });
  17441. const makePanels = (parts, panelConfigs) => {
  17442. const specs = map$2(keys(panelConfigs), name => {
  17443. const spec = panelConfigs[name];
  17444. const bridged = getOrDie(createSidebar(spec));
  17445. return {
  17446. name,
  17447. getApi,
  17448. onSetup: bridged.onSetup,
  17449. onShow: bridged.onShow,
  17450. onHide: bridged.onHide
  17451. };
  17452. });
  17453. return map$2(specs, spec => {
  17454. const editorOffCell = Cell(noop);
  17455. return parts.slot(spec.name, {
  17456. dom: {
  17457. tag: 'div',
  17458. classes: ['tox-sidebar__pane']
  17459. },
  17460. behaviours: SimpleBehaviours.unnamedEvents([
  17461. onControlAttached(spec, editorOffCell),
  17462. onControlDetached(spec, editorOffCell),
  17463. run$1(slotVisibility(), (sidepanel, se) => {
  17464. const data = se.event;
  17465. const optSidePanelSpec = find$5(specs, config => config.name === data.name);
  17466. optSidePanelSpec.each(sidePanelSpec => {
  17467. const handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  17468. handler(sidePanelSpec.getApi(sidepanel));
  17469. });
  17470. })
  17471. ])
  17472. });
  17473. });
  17474. };
  17475. const makeSidebar = panelConfigs => SlotContainer.sketch(parts => ({
  17476. dom: {
  17477. tag: 'div',
  17478. classes: ['tox-sidebar__pane-container']
  17479. },
  17480. components: makePanels(parts, panelConfigs),
  17481. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(slotContainer => SlotContainer.hideAllSlots(slotContainer))])
  17482. }));
  17483. const setSidebar = (sidebar, panelConfigs) => {
  17484. const optSlider = Composing.getCurrent(sidebar);
  17485. optSlider.each(slider => Replacing.set(slider, [makeSidebar(panelConfigs)]));
  17486. };
  17487. const toggleSidebar = (sidebar, name) => {
  17488. const optSlider = Composing.getCurrent(sidebar);
  17489. optSlider.each(slider => {
  17490. const optSlotContainer = Composing.getCurrent(slider);
  17491. optSlotContainer.each(slotContainer => {
  17492. if (Sliding.hasGrown(slider)) {
  17493. if (SlotContainer.isShowing(slotContainer, name)) {
  17494. Sliding.shrink(slider);
  17495. } else {
  17496. SlotContainer.hideAllSlots(slotContainer);
  17497. SlotContainer.showSlot(slotContainer, name);
  17498. }
  17499. } else {
  17500. SlotContainer.hideAllSlots(slotContainer);
  17501. SlotContainer.showSlot(slotContainer, name);
  17502. Sliding.grow(slider);
  17503. }
  17504. });
  17505. });
  17506. };
  17507. const whichSidebar = sidebar => {
  17508. const optSlider = Composing.getCurrent(sidebar);
  17509. return optSlider.bind(slider => {
  17510. const sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  17511. if (sidebarOpen) {
  17512. const optSlotContainer = Composing.getCurrent(slider);
  17513. return optSlotContainer.bind(slotContainer => find$5(SlotContainer.getSlotNames(slotContainer), name => SlotContainer.isShowing(slotContainer, name)));
  17514. } else {
  17515. return Optional.none();
  17516. }
  17517. });
  17518. };
  17519. const fixSize = generate$6('FixSizeEvent');
  17520. const autoSize = generate$6('AutoSizeEvent');
  17521. const renderSidebar = spec => ({
  17522. uid: spec.uid,
  17523. dom: {
  17524. tag: 'div',
  17525. classes: ['tox-sidebar'],
  17526. attributes: { role: 'complementary' }
  17527. },
  17528. components: [{
  17529. dom: {
  17530. tag: 'div',
  17531. classes: ['tox-sidebar__slider']
  17532. },
  17533. components: [],
  17534. behaviours: derive$1([
  17535. Tabstopping.config({}),
  17536. Focusing.config({}),
  17537. Sliding.config({
  17538. dimension: { property: 'width' },
  17539. closedClass: 'tox-sidebar--sliding-closed',
  17540. openClass: 'tox-sidebar--sliding-open',
  17541. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  17542. growingClass: 'tox-sidebar--sliding-growing',
  17543. onShrunk: slider => {
  17544. const optSlotContainer = Composing.getCurrent(slider);
  17545. optSlotContainer.each(SlotContainer.hideAllSlots);
  17546. emit(slider, autoSize);
  17547. },
  17548. onGrown: slider => {
  17549. emit(slider, autoSize);
  17550. },
  17551. onStartGrow: slider => {
  17552. emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
  17553. },
  17554. onStartShrink: slider => {
  17555. emitWith(slider, fixSize, { width: get$c(slider.element) + 'px' });
  17556. }
  17557. }),
  17558. Replacing.config({}),
  17559. Composing.config({
  17560. find: comp => {
  17561. const children = Replacing.contents(comp);
  17562. return head(children);
  17563. }
  17564. })
  17565. ])
  17566. }],
  17567. behaviours: derive$1([
  17568. ComposingConfigs.childAt(0),
  17569. config('sidebar-sliding-events', [
  17570. run$1(fixSize, (comp, se) => {
  17571. set$8(comp.element, 'width', se.event.width);
  17572. }),
  17573. run$1(autoSize, (comp, _se) => {
  17574. remove$6(comp.element, 'width');
  17575. })
  17576. ])
  17577. ])
  17578. });
  17579. const block = (component, config, state, getBusySpec) => {
  17580. set$9(component.element, 'aria-busy', true);
  17581. const root = config.getRoot(component).getOr(component);
  17582. const blockerBehaviours = derive$1([
  17583. Keying.config({
  17584. mode: 'special',
  17585. onTab: () => Optional.some(true),
  17586. onShiftTab: () => Optional.some(true)
  17587. }),
  17588. Focusing.config({})
  17589. ]);
  17590. const blockSpec = getBusySpec(root, blockerBehaviours);
  17591. const blocker = root.getSystem().build(blockSpec);
  17592. Replacing.append(root, premade(blocker));
  17593. if (blocker.hasConfigured(Keying) && config.focus) {
  17594. Keying.focusIn(blocker);
  17595. }
  17596. if (!state.isBlocked()) {
  17597. config.onBlock(component);
  17598. }
  17599. state.blockWith(() => Replacing.remove(root, blocker));
  17600. };
  17601. const unblock = (component, config, state) => {
  17602. remove$7(component.element, 'aria-busy');
  17603. if (state.isBlocked()) {
  17604. config.onUnblock(component);
  17605. }
  17606. state.clear();
  17607. };
  17608. var BlockingApis = /*#__PURE__*/Object.freeze({
  17609. __proto__: null,
  17610. block: block,
  17611. unblock: unblock
  17612. });
  17613. var BlockingSchema = [
  17614. defaultedFunction('getRoot', Optional.none),
  17615. defaultedBoolean('focus', true),
  17616. onHandler('onBlock'),
  17617. onHandler('onUnblock')
  17618. ];
  17619. const init$4 = () => {
  17620. const blocker = destroyable();
  17621. const blockWith = destroy => {
  17622. blocker.set({ destroy });
  17623. };
  17624. return nu$8({
  17625. readState: blocker.isSet,
  17626. blockWith,
  17627. clear: blocker.clear,
  17628. isBlocked: blocker.isSet
  17629. });
  17630. };
  17631. var BlockingState = /*#__PURE__*/Object.freeze({
  17632. __proto__: null,
  17633. init: init$4
  17634. });
  17635. const Blocking = create$3({
  17636. fields: BlockingSchema,
  17637. name: 'blocking',
  17638. apis: BlockingApis,
  17639. state: BlockingState
  17640. });
  17641. const getAttrs = elem => {
  17642. const attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  17643. return foldl(attributes, (b, attr) => {
  17644. if (attr.name === 'class') {
  17645. return b;
  17646. } else {
  17647. return {
  17648. ...b,
  17649. [attr.name]: attr.value
  17650. };
  17651. }
  17652. }, {});
  17653. };
  17654. const getClasses = elem => Array.prototype.slice.call(elem.dom.classList, 0);
  17655. const fromHtml = html => {
  17656. const elem = SugarElement.fromHtml(html);
  17657. const children$1 = children(elem);
  17658. const attrs = getAttrs(elem);
  17659. const classes = getClasses(elem);
  17660. const contents = children$1.length === 0 ? {} : { innerHtml: get$9(elem) };
  17661. return {
  17662. tag: name$3(elem),
  17663. classes,
  17664. attributes: attrs,
  17665. ...contents
  17666. };
  17667. };
  17668. const getBusySpec$1 = providerBackstage => (_root, _behaviours) => ({
  17669. dom: {
  17670. tag: 'div',
  17671. attributes: {
  17672. 'aria-label': providerBackstage.translate('Loading...'),
  17673. 'tabindex': '0'
  17674. },
  17675. classes: ['tox-throbber__busy-spinner']
  17676. },
  17677. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  17678. });
  17679. const focusBusyComponent = throbber => Composing.getCurrent(throbber).each(comp => focus$3(comp.element));
  17680. const toggleEditorTabIndex = (editor, state) => {
  17681. const tabIndexAttr = 'tabindex';
  17682. const dataTabIndexAttr = `data-mce-${ tabIndexAttr }`;
  17683. Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(iframe => {
  17684. if (state) {
  17685. getOpt(iframe, tabIndexAttr).each(tabIndex => set$9(iframe, dataTabIndexAttr, tabIndex));
  17686. set$9(iframe, tabIndexAttr, -1);
  17687. } else {
  17688. remove$7(iframe, tabIndexAttr);
  17689. getOpt(iframe, dataTabIndexAttr).each(tabIndex => {
  17690. set$9(iframe, tabIndexAttr, tabIndex);
  17691. remove$7(iframe, dataTabIndexAttr);
  17692. });
  17693. }
  17694. });
  17695. };
  17696. const toggleThrobber = (editor, comp, state, providerBackstage) => {
  17697. const element = comp.element;
  17698. toggleEditorTabIndex(editor, state);
  17699. if (state) {
  17700. Blocking.block(comp, getBusySpec$1(providerBackstage));
  17701. remove$6(element, 'display');
  17702. remove$7(element, 'aria-hidden');
  17703. if (editor.hasFocus()) {
  17704. focusBusyComponent(comp);
  17705. }
  17706. } else {
  17707. const throbberFocus = Composing.getCurrent(comp).exists(busyComp => hasFocus(busyComp.element));
  17708. Blocking.unblock(comp);
  17709. set$8(element, 'display', 'none');
  17710. set$9(element, 'aria-hidden', 'true');
  17711. if (throbberFocus) {
  17712. editor.focus();
  17713. }
  17714. }
  17715. };
  17716. const renderThrobber = spec => ({
  17717. uid: spec.uid,
  17718. dom: {
  17719. tag: 'div',
  17720. attributes: { 'aria-hidden': 'true' },
  17721. classes: ['tox-throbber'],
  17722. styles: { display: 'none' }
  17723. },
  17724. behaviours: derive$1([
  17725. Replacing.config({}),
  17726. Blocking.config({ focus: false }),
  17727. Composing.config({ find: comp => head(comp.components()) })
  17728. ]),
  17729. components: []
  17730. });
  17731. const isFocusEvent = event => event.type === 'focusin';
  17732. const isPasteBinTarget = event => {
  17733. if (isFocusEvent(event)) {
  17734. const node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
  17735. return node.map(SugarElement.fromDom).filter(isElement$1).exists(targetElm => has(targetElm, 'mce-pastebin'));
  17736. } else {
  17737. return false;
  17738. }
  17739. };
  17740. const setup$7 = (editor, lazyThrobber, sharedBackstage) => {
  17741. const throbberState = Cell(false);
  17742. const timer = value$2();
  17743. const stealFocus = e => {
  17744. if (throbberState.get() && !isPasteBinTarget(e)) {
  17745. e.preventDefault();
  17746. focusBusyComponent(lazyThrobber());
  17747. editor.editorManager.setActive(editor);
  17748. }
  17749. };
  17750. if (!editor.inline) {
  17751. editor.on('PreInit', () => {
  17752. editor.dom.bind(editor.getWin(), 'focusin', stealFocus);
  17753. editor.on('BeforeExecCommand', e => {
  17754. if (e.command.toLowerCase() === 'mcefocus' && e.value !== true) {
  17755. stealFocus(e);
  17756. }
  17757. });
  17758. });
  17759. }
  17760. const toggle = state => {
  17761. if (state !== throbberState.get()) {
  17762. throbberState.set(state);
  17763. toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
  17764. editor.dispatch('AfterProgressState', { state });
  17765. }
  17766. };
  17767. editor.on('ProgressState', e => {
  17768. timer.on(clearTimeout);
  17769. if (isNumber(e.time)) {
  17770. const timerId = global$9.setEditorTimeout(editor, () => toggle(e.state), e.time);
  17771. timer.set(timerId);
  17772. } else {
  17773. toggle(e.state);
  17774. timer.clear();
  17775. }
  17776. });
  17777. };
  17778. const generate$1 = (xs, f) => {
  17779. const init = {
  17780. len: 0,
  17781. list: []
  17782. };
  17783. const r = foldl(xs, (b, a) => {
  17784. const value = f(a, b.len);
  17785. return value.fold(constant$1(b), v => ({
  17786. len: v.finish,
  17787. list: b.list.concat([v])
  17788. }));
  17789. }, init);
  17790. return r.list;
  17791. };
  17792. const output = (within, extra, withinWidth) => ({
  17793. within,
  17794. extra,
  17795. withinWidth
  17796. });
  17797. const apportion = (units, total, len) => {
  17798. const parray = generate$1(units, (unit, current) => {
  17799. const width = len(unit);
  17800. return Optional.some({
  17801. element: unit,
  17802. start: current,
  17803. finish: current + width,
  17804. width
  17805. });
  17806. });
  17807. const within = filter$2(parray, unit => unit.finish <= total);
  17808. const withinWidth = foldr(within, (acc, el) => acc + el.width, 0);
  17809. const extra = parray.slice(within.length);
  17810. return {
  17811. within,
  17812. extra,
  17813. withinWidth
  17814. };
  17815. };
  17816. const toUnit = parray => map$2(parray, unit => unit.element);
  17817. const fitLast = (within, extra, withinWidth) => {
  17818. const fits = toUnit(within.concat(extra));
  17819. return output(fits, [], withinWidth);
  17820. };
  17821. const overflow = (within, extra, overflower, withinWidth) => {
  17822. const fits = toUnit(within).concat([overflower]);
  17823. return output(fits, toUnit(extra), withinWidth);
  17824. };
  17825. const fitAll = (within, extra, withinWidth) => output(toUnit(within), [], withinWidth);
  17826. const tryFit = (total, units, len) => {
  17827. const divide = apportion(units, total, len);
  17828. return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
  17829. };
  17830. const partition = (total, units, len, overflower) => {
  17831. const divide = tryFit(total, units, len).getOrThunk(() => apportion(units, total - len(overflower), len));
  17832. const within = divide.within;
  17833. const extra = divide.extra;
  17834. const withinWidth = divide.withinWidth;
  17835. if (extra.length === 1 && extra[0].width <= len(overflower)) {
  17836. return fitLast(within, extra, withinWidth);
  17837. } else if (extra.length >= 1) {
  17838. return overflow(within, extra, overflower, withinWidth);
  17839. } else {
  17840. return fitAll(within, extra, withinWidth);
  17841. }
  17842. };
  17843. const setGroups$1 = (toolbar, storedGroups) => {
  17844. const bGroups = map$2(storedGroups, g => premade(g));
  17845. Toolbar.setGroups(toolbar, bGroups);
  17846. };
  17847. const findFocusedComp = comps => findMap(comps, comp => search(comp.element).bind(focusedElm => comp.getSystem().getByDom(focusedElm).toOptional()));
  17848. const refresh$2 = (toolbar, detail, setOverflow) => {
  17849. const builtGroups = detail.builtGroups.get();
  17850. if (builtGroups.length === 0) {
  17851. return;
  17852. }
  17853. const primary = getPartOrDie(toolbar, detail, 'primary');
  17854. const overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  17855. set$8(primary.element, 'visibility', 'hidden');
  17856. const groups = builtGroups.concat([overflowGroup]);
  17857. const focusedComp = findFocusedComp(groups);
  17858. setOverflow([]);
  17859. setGroups$1(primary, groups);
  17860. const availableWidth = get$c(primary.element);
  17861. const overflows = partition(availableWidth, detail.builtGroups.get(), comp => get$c(comp.element), overflowGroup);
  17862. if (overflows.extra.length === 0) {
  17863. Replacing.remove(primary, overflowGroup);
  17864. setOverflow([]);
  17865. } else {
  17866. setGroups$1(primary, overflows.within);
  17867. setOverflow(overflows.extra);
  17868. }
  17869. remove$6(primary.element, 'visibility');
  17870. reflow(primary.element);
  17871. focusedComp.each(Focusing.focus);
  17872. };
  17873. const schema$c = constant$1([
  17874. field('splitToolbarBehaviours', [Coupling]),
  17875. customField('builtGroups', () => Cell([]))
  17876. ]);
  17877. const schema$b = constant$1([
  17878. markers$1(['overflowToggledClass']),
  17879. optionFunction('getOverflowBounds'),
  17880. required$1('lazySink'),
  17881. customField('overflowGroups', () => Cell([]))
  17882. ].concat(schema$c()));
  17883. const parts$7 = constant$1([
  17884. required({
  17885. factory: Toolbar,
  17886. schema: schema$e(),
  17887. name: 'primary'
  17888. }),
  17889. external({
  17890. schema: schema$e(),
  17891. name: 'overflow'
  17892. }),
  17893. external({ name: 'overflow-button' }),
  17894. external({ name: 'overflow-group' })
  17895. ]);
  17896. const expandable = constant$1((element, available) => {
  17897. setMax(element, Math.floor(available));
  17898. });
  17899. const schema$a = constant$1([
  17900. markers$1(['toggledClass']),
  17901. required$1('lazySink'),
  17902. requiredFunction('fetch'),
  17903. optionFunction('getBounds'),
  17904. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  17905. schema$y()
  17906. ]);
  17907. const parts$6 = constant$1([
  17908. external({
  17909. name: 'button',
  17910. overrides: detail => ({
  17911. dom: { attributes: { 'aria-haspopup': 'true' } },
  17912. buttonBehaviours: derive$1([Toggling.config({
  17913. toggleClass: detail.markers.toggledClass,
  17914. aria: { mode: 'expanded' },
  17915. toggleOnExecute: false
  17916. })])
  17917. })
  17918. }),
  17919. external({
  17920. factory: Toolbar,
  17921. schema: schema$e(),
  17922. name: 'toolbar',
  17923. overrides: detail => {
  17924. return {
  17925. toolbarBehaviours: derive$1([Keying.config({
  17926. mode: 'cyclic',
  17927. onEscape: comp => {
  17928. getPart(comp, detail, 'button').each(Focusing.focus);
  17929. return Optional.none();
  17930. }
  17931. })])
  17932. };
  17933. }
  17934. })
  17935. ]);
  17936. const toggle = (button, externals) => {
  17937. const toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  17938. if (Sandboxing.isOpen(toolbarSandbox)) {
  17939. Sandboxing.close(toolbarSandbox);
  17940. } else {
  17941. Sandboxing.open(toolbarSandbox, externals.toolbar());
  17942. }
  17943. };
  17944. const position = (button, toolbar, detail, layouts) => {
  17945. const bounds = detail.getBounds.map(bounder => bounder());
  17946. const sink = detail.lazySink(button).getOrDie();
  17947. Positioning.positionWithinBounds(sink, toolbar, {
  17948. anchor: {
  17949. type: 'hotspot',
  17950. hotspot: button,
  17951. layouts,
  17952. overrides: { maxWidthFunction: expandable() }
  17953. }
  17954. }, bounds);
  17955. };
  17956. const setGroups = (button, toolbar, detail, layouts, groups) => {
  17957. Toolbar.setGroups(toolbar, groups);
  17958. position(button, toolbar, detail, layouts);
  17959. Toggling.on(button);
  17960. };
  17961. const makeSandbox = (button, spec, detail) => {
  17962. const ariaControls = manager();
  17963. const onOpen = (sandbox, toolbar) => {
  17964. detail.fetch().get(groups => {
  17965. setGroups(button, toolbar, detail, spec.layouts, groups);
  17966. ariaControls.link(button.element);
  17967. Keying.focusIn(toolbar);
  17968. });
  17969. };
  17970. const onClose = () => {
  17971. Toggling.off(button);
  17972. Focusing.focus(button);
  17973. ariaControls.unlink(button.element);
  17974. };
  17975. return {
  17976. dom: {
  17977. tag: 'div',
  17978. attributes: { id: ariaControls.id }
  17979. },
  17980. behaviours: derive$1([
  17981. Keying.config({
  17982. mode: 'special',
  17983. onEscape: comp => {
  17984. Sandboxing.close(comp);
  17985. return Optional.some(true);
  17986. }
  17987. }),
  17988. Sandboxing.config({
  17989. onOpen,
  17990. onClose,
  17991. isPartOf: (container, data, queryElem) => {
  17992. return isPartOf$1(data, queryElem) || isPartOf$1(button, queryElem);
  17993. },
  17994. getAttachPoint: () => {
  17995. return detail.lazySink(button).getOrDie();
  17996. }
  17997. }),
  17998. Receiving.config({
  17999. channels: {
  18000. ...receivingChannel$1({
  18001. isExtraPart: never,
  18002. ...detail.fireDismissalEventInstead.map(fe => ({ fireEventInstead: { event: fe.event } })).getOr({})
  18003. }),
  18004. ...receivingChannel({
  18005. doReposition: () => {
  18006. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(toolbar => {
  18007. position(button, toolbar, detail, spec.layouts);
  18008. });
  18009. }
  18010. })
  18011. }
  18012. })
  18013. ])
  18014. };
  18015. };
  18016. const factory$a = (detail, components, spec, externals) => ({
  18017. ...Button.sketch({
  18018. ...externals.button(),
  18019. action: button => {
  18020. toggle(button, externals);
  18021. },
  18022. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  18023. others: {
  18024. toolbarSandbox: button => {
  18025. return makeSandbox(button, spec, detail);
  18026. }
  18027. }
  18028. })])
  18029. }),
  18030. apis: {
  18031. setGroups: (button, groups) => {
  18032. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(toolbar => {
  18033. setGroups(button, toolbar, detail, spec.layouts, groups);
  18034. });
  18035. },
  18036. reposition: button => {
  18037. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(toolbar => {
  18038. position(button, toolbar, detail, spec.layouts);
  18039. });
  18040. },
  18041. toggle: button => {
  18042. toggle(button, externals);
  18043. },
  18044. getToolbar: button => {
  18045. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  18046. },
  18047. isOpen: button => {
  18048. return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
  18049. }
  18050. }
  18051. });
  18052. const FloatingToolbarButton = composite({
  18053. name: 'FloatingToolbarButton',
  18054. factory: factory$a,
  18055. configFields: schema$a(),
  18056. partFields: parts$6(),
  18057. apis: {
  18058. setGroups: (apis, button, groups) => {
  18059. apis.setGroups(button, groups);
  18060. },
  18061. reposition: (apis, button) => {
  18062. apis.reposition(button);
  18063. },
  18064. toggle: (apis, button) => {
  18065. apis.toggle(button);
  18066. },
  18067. getToolbar: (apis, button) => apis.getToolbar(button),
  18068. isOpen: (apis, button) => apis.isOpen(button)
  18069. }
  18070. });
  18071. const schema$9 = constant$1([
  18072. required$1('items'),
  18073. markers$1(['itemSelector']),
  18074. field('tgroupBehaviours', [Keying])
  18075. ]);
  18076. const parts$5 = constant$1([group({
  18077. name: 'items',
  18078. unit: 'item'
  18079. })]);
  18080. const factory$9 = (detail, components, _spec, _externals) => ({
  18081. uid: detail.uid,
  18082. dom: detail.dom,
  18083. components,
  18084. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  18085. mode: 'flow',
  18086. selector: detail.markers.itemSelector
  18087. })]),
  18088. domModification: { attributes: { role: 'toolbar' } }
  18089. });
  18090. const ToolbarGroup = composite({
  18091. name: 'ToolbarGroup',
  18092. configFields: schema$9(),
  18093. partFields: parts$5(),
  18094. factory: factory$9
  18095. });
  18096. const buildGroups = comps => map$2(comps, g => premade(g));
  18097. const refresh$1 = (toolbar, memFloatingToolbarButton, detail) => {
  18098. refresh$2(toolbar, detail, overflowGroups => {
  18099. detail.overflowGroups.set(overflowGroups);
  18100. memFloatingToolbarButton.getOpt(toolbar).each(floatingToolbarButton => {
  18101. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  18102. });
  18103. });
  18104. };
  18105. const factory$8 = (detail, components, spec, externals) => {
  18106. const memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  18107. fetch: () => Future.nu(resolve => {
  18108. resolve(buildGroups(detail.overflowGroups.get()));
  18109. }),
  18110. layouts: {
  18111. onLtr: () => [
  18112. southwest$2,
  18113. southeast$2
  18114. ],
  18115. onRtl: () => [
  18116. southeast$2,
  18117. southwest$2
  18118. ],
  18119. onBottomLtr: () => [
  18120. northwest$2,
  18121. northeast$2
  18122. ],
  18123. onBottomRtl: () => [
  18124. northeast$2,
  18125. northwest$2
  18126. ]
  18127. },
  18128. getBounds: spec.getOverflowBounds,
  18129. lazySink: detail.lazySink,
  18130. fireDismissalEventInstead: {},
  18131. markers: { toggledClass: detail.markers.overflowToggledClass },
  18132. parts: {
  18133. button: externals['overflow-button'](),
  18134. toolbar: externals.overflow()
  18135. }
  18136. }));
  18137. return {
  18138. uid: detail.uid,
  18139. dom: detail.dom,
  18140. components,
  18141. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  18142. others: {
  18143. overflowGroup: () => {
  18144. return ToolbarGroup.sketch({
  18145. ...externals['overflow-group'](),
  18146. items: [memFloatingToolbarButton.asSpec()]
  18147. });
  18148. }
  18149. }
  18150. })]),
  18151. apis: {
  18152. setGroups: (toolbar, groups) => {
  18153. detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
  18154. refresh$1(toolbar, memFloatingToolbarButton, detail);
  18155. },
  18156. refresh: toolbar => refresh$1(toolbar, memFloatingToolbarButton, detail),
  18157. toggle: toolbar => {
  18158. memFloatingToolbarButton.getOpt(toolbar).each(floatingToolbarButton => {
  18159. FloatingToolbarButton.toggle(floatingToolbarButton);
  18160. });
  18161. },
  18162. isOpen: toolbar => memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false),
  18163. reposition: toolbar => {
  18164. memFloatingToolbarButton.getOpt(toolbar).each(floatingToolbarButton => {
  18165. FloatingToolbarButton.reposition(floatingToolbarButton);
  18166. });
  18167. },
  18168. getOverflow: toolbar => memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar)
  18169. },
  18170. domModification: { attributes: { role: 'group' } }
  18171. };
  18172. };
  18173. const SplitFloatingToolbar = composite({
  18174. name: 'SplitFloatingToolbar',
  18175. configFields: schema$b(),
  18176. partFields: parts$7(),
  18177. factory: factory$8,
  18178. apis: {
  18179. setGroups: (apis, toolbar, groups) => {
  18180. apis.setGroups(toolbar, groups);
  18181. },
  18182. refresh: (apis, toolbar) => {
  18183. apis.refresh(toolbar);
  18184. },
  18185. reposition: (apis, toolbar) => {
  18186. apis.reposition(toolbar);
  18187. },
  18188. toggle: (apis, toolbar) => {
  18189. apis.toggle(toolbar);
  18190. },
  18191. isOpen: (apis, toolbar) => apis.isOpen(toolbar),
  18192. getOverflow: (apis, toolbar) => apis.getOverflow(toolbar)
  18193. }
  18194. });
  18195. const schema$8 = constant$1([
  18196. markers$1([
  18197. 'closedClass',
  18198. 'openClass',
  18199. 'shrinkingClass',
  18200. 'growingClass',
  18201. 'overflowToggledClass'
  18202. ]),
  18203. onHandler('onOpened'),
  18204. onHandler('onClosed')
  18205. ].concat(schema$c()));
  18206. const parts$4 = constant$1([
  18207. required({
  18208. factory: Toolbar,
  18209. schema: schema$e(),
  18210. name: 'primary'
  18211. }),
  18212. required({
  18213. factory: Toolbar,
  18214. schema: schema$e(),
  18215. name: 'overflow',
  18216. overrides: detail => {
  18217. return {
  18218. toolbarBehaviours: derive$1([
  18219. Sliding.config({
  18220. dimension: { property: 'height' },
  18221. closedClass: detail.markers.closedClass,
  18222. openClass: detail.markers.openClass,
  18223. shrinkingClass: detail.markers.shrinkingClass,
  18224. growingClass: detail.markers.growingClass,
  18225. onShrunk: comp => {
  18226. getPart(comp, detail, 'overflow-button').each(button => {
  18227. Toggling.off(button);
  18228. Focusing.focus(button);
  18229. });
  18230. detail.onClosed(comp);
  18231. },
  18232. onGrown: comp => {
  18233. Keying.focusIn(comp);
  18234. detail.onOpened(comp);
  18235. },
  18236. onStartGrow: comp => {
  18237. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  18238. }
  18239. }),
  18240. Keying.config({
  18241. mode: 'acyclic',
  18242. onEscape: comp => {
  18243. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  18244. return Optional.some(true);
  18245. }
  18246. })
  18247. ])
  18248. };
  18249. }
  18250. }),
  18251. external({
  18252. name: 'overflow-button',
  18253. overrides: detail => ({
  18254. buttonBehaviours: derive$1([Toggling.config({
  18255. toggleClass: detail.markers.overflowToggledClass,
  18256. aria: { mode: 'pressed' },
  18257. toggleOnExecute: false
  18258. })])
  18259. })
  18260. }),
  18261. external({ name: 'overflow-group' })
  18262. ]);
  18263. const isOpen = (toolbar, detail) => getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
  18264. const toggleToolbar = (toolbar, detail) => {
  18265. getPart(toolbar, detail, 'overflow-button').bind(() => getPart(toolbar, detail, 'overflow')).each(overf => {
  18266. refresh(toolbar, detail);
  18267. Sliding.toggleGrow(overf);
  18268. });
  18269. };
  18270. const refresh = (toolbar, detail) => {
  18271. getPart(toolbar, detail, 'overflow').each(overflow => {
  18272. refresh$2(toolbar, detail, groups => {
  18273. const builtGroups = map$2(groups, g => premade(g));
  18274. Toolbar.setGroups(overflow, builtGroups);
  18275. });
  18276. getPart(toolbar, detail, 'overflow-button').each(button => {
  18277. if (Sliding.hasGrown(overflow)) {
  18278. Toggling.on(button);
  18279. }
  18280. });
  18281. Sliding.refresh(overflow);
  18282. });
  18283. };
  18284. const factory$7 = (detail, components, spec, externals) => {
  18285. const toolbarToggleEvent = 'alloy.toolbar.toggle';
  18286. const doSetGroups = (toolbar, groups) => {
  18287. const built = map$2(groups, toolbar.getSystem().build);
  18288. detail.builtGroups.set(built);
  18289. };
  18290. return {
  18291. uid: detail.uid,
  18292. dom: detail.dom,
  18293. components,
  18294. behaviours: augment(detail.splitToolbarBehaviours, [
  18295. Coupling.config({
  18296. others: {
  18297. overflowGroup: toolbar => {
  18298. return ToolbarGroup.sketch({
  18299. ...externals['overflow-group'](),
  18300. items: [Button.sketch({
  18301. ...externals['overflow-button'](),
  18302. action: _button => {
  18303. emit(toolbar, toolbarToggleEvent);
  18304. }
  18305. })]
  18306. });
  18307. }
  18308. }
  18309. }),
  18310. config('toolbar-toggle-events', [run$1(toolbarToggleEvent, toolbar => {
  18311. toggleToolbar(toolbar, detail);
  18312. })])
  18313. ]),
  18314. apis: {
  18315. setGroups: (toolbar, groups) => {
  18316. doSetGroups(toolbar, groups);
  18317. refresh(toolbar, detail);
  18318. },
  18319. refresh: toolbar => refresh(toolbar, detail),
  18320. toggle: toolbar => toggleToolbar(toolbar, detail),
  18321. isOpen: toolbar => isOpen(toolbar, detail)
  18322. },
  18323. domModification: { attributes: { role: 'group' } }
  18324. };
  18325. };
  18326. const SplitSlidingToolbar = composite({
  18327. name: 'SplitSlidingToolbar',
  18328. configFields: schema$8(),
  18329. partFields: parts$4(),
  18330. factory: factory$7,
  18331. apis: {
  18332. setGroups: (apis, toolbar, groups) => {
  18333. apis.setGroups(toolbar, groups);
  18334. },
  18335. refresh: (apis, toolbar) => {
  18336. apis.refresh(toolbar);
  18337. },
  18338. toggle: (apis, toolbar) => {
  18339. apis.toggle(toolbar);
  18340. },
  18341. isOpen: (apis, toolbar) => apis.isOpen(toolbar)
  18342. }
  18343. });
  18344. const renderToolbarGroupCommon = toolbarGroup => {
  18345. const attributes = toolbarGroup.title.fold(() => ({}), title => ({ attributes: { title } }));
  18346. return {
  18347. dom: {
  18348. tag: 'div',
  18349. classes: ['tox-toolbar__group'],
  18350. ...attributes
  18351. },
  18352. components: [ToolbarGroup.parts.items({})],
  18353. items: toolbarGroup.items,
  18354. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  18355. tgroupBehaviours: derive$1([
  18356. Tabstopping.config({}),
  18357. Focusing.config({})
  18358. ])
  18359. };
  18360. };
  18361. const renderToolbarGroup = toolbarGroup => ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  18362. const getToolbarbehaviours = (toolbarSpec, modeName) => {
  18363. const onAttached = runOnAttached(component => {
  18364. const groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
  18365. Toolbar.setGroups(component, groups);
  18366. });
  18367. return derive$1([
  18368. DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
  18369. receivingConfig(),
  18370. Keying.config({
  18371. mode: modeName,
  18372. onEscape: toolbarSpec.onEscape,
  18373. selector: '.tox-toolbar__group'
  18374. }),
  18375. config('toolbar-events', [onAttached])
  18376. ]);
  18377. };
  18378. const renderMoreToolbarCommon = toolbarSpec => {
  18379. const modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  18380. return {
  18381. uid: toolbarSpec.uid,
  18382. dom: {
  18383. tag: 'div',
  18384. classes: ['tox-toolbar-overlord']
  18385. },
  18386. parts: {
  18387. 'overflow-group': renderToolbarGroupCommon({
  18388. title: Optional.none(),
  18389. items: []
  18390. }),
  18391. 'overflow-button': renderIconButtonSpec({
  18392. name: 'more',
  18393. icon: Optional.some('more-drawer'),
  18394. enabled: true,
  18395. tooltip: Optional.some('More...'),
  18396. primary: false,
  18397. buttonType: Optional.none(),
  18398. borderless: false
  18399. }, Optional.none(), toolbarSpec.providers)
  18400. },
  18401. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  18402. };
  18403. };
  18404. const renderFloatingMoreToolbar = toolbarSpec => {
  18405. const baseSpec = renderMoreToolbarCommon(toolbarSpec);
  18406. const overflowXOffset = 4;
  18407. const primary = SplitFloatingToolbar.parts.primary({
  18408. dom: {
  18409. tag: 'div',
  18410. classes: ['tox-toolbar__primary']
  18411. }
  18412. });
  18413. return SplitFloatingToolbar.sketch({
  18414. ...baseSpec,
  18415. lazySink: toolbarSpec.getSink,
  18416. getOverflowBounds: () => {
  18417. const headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
  18418. const headerBounds = absolute$2(headerElem);
  18419. const docElem = documentElement(headerElem);
  18420. const docBounds = absolute$2(docElem);
  18421. const height = Math.max(docElem.dom.scrollHeight, docBounds.height);
  18422. return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  18423. },
  18424. parts: {
  18425. ...baseSpec.parts,
  18426. overflow: {
  18427. dom: {
  18428. tag: 'div',
  18429. classes: ['tox-toolbar__overflow'],
  18430. attributes: toolbarSpec.attributes
  18431. }
  18432. }
  18433. },
  18434. components: [primary],
  18435. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  18436. });
  18437. };
  18438. const renderSlidingMoreToolbar = toolbarSpec => {
  18439. const primary = SplitSlidingToolbar.parts.primary({
  18440. dom: {
  18441. tag: 'div',
  18442. classes: ['tox-toolbar__primary']
  18443. }
  18444. });
  18445. const overflow = SplitSlidingToolbar.parts.overflow({
  18446. dom: {
  18447. tag: 'div',
  18448. classes: ['tox-toolbar__overflow']
  18449. }
  18450. });
  18451. const baseSpec = renderMoreToolbarCommon(toolbarSpec);
  18452. return SplitSlidingToolbar.sketch({
  18453. ...baseSpec,
  18454. components: [
  18455. primary,
  18456. overflow
  18457. ],
  18458. markers: {
  18459. openClass: 'tox-toolbar__overflow--open',
  18460. closedClass: 'tox-toolbar__overflow--closed',
  18461. growingClass: 'tox-toolbar__overflow--growing',
  18462. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  18463. overflowToggledClass: 'tox-tbtn--enabled'
  18464. },
  18465. onOpened: comp => {
  18466. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  18467. },
  18468. onClosed: comp => {
  18469. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  18470. }
  18471. });
  18472. };
  18473. const renderToolbar = toolbarSpec => {
  18474. const modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  18475. return Toolbar.sketch({
  18476. uid: toolbarSpec.uid,
  18477. dom: {
  18478. tag: 'div',
  18479. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode$1.scrolling ? ['tox-toolbar--scrolling'] : [])
  18480. },
  18481. components: [Toolbar.parts.groups({})],
  18482. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  18483. });
  18484. };
  18485. const factory$6 = (detail, components, _spec) => {
  18486. const apis = {
  18487. getSocket: comp => {
  18488. return parts$a.getPart(comp, detail, 'socket');
  18489. },
  18490. setSidebar: (comp, panelConfigs) => {
  18491. parts$a.getPart(comp, detail, 'sidebar').each(sidebar => setSidebar(sidebar, panelConfigs));
  18492. },
  18493. toggleSidebar: (comp, name) => {
  18494. parts$a.getPart(comp, detail, 'sidebar').each(sidebar => toggleSidebar(sidebar, name));
  18495. },
  18496. whichSidebar: comp => {
  18497. return parts$a.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  18498. },
  18499. getHeader: comp => {
  18500. return parts$a.getPart(comp, detail, 'header');
  18501. },
  18502. getToolbar: comp => {
  18503. return parts$a.getPart(comp, detail, 'toolbar');
  18504. },
  18505. setToolbar: (comp, groups) => {
  18506. parts$a.getPart(comp, detail, 'toolbar').each(toolbar => {
  18507. toolbar.getApis().setGroups(toolbar, groups);
  18508. });
  18509. },
  18510. setToolbars: (comp, toolbars) => {
  18511. parts$a.getPart(comp, detail, 'multiple-toolbar').each(mToolbar => {
  18512. CustomList.setItems(mToolbar, toolbars);
  18513. });
  18514. },
  18515. refreshToolbar: comp => {
  18516. const toolbar = parts$a.getPart(comp, detail, 'toolbar');
  18517. toolbar.each(toolbar => toolbar.getApis().refresh(toolbar));
  18518. },
  18519. toggleToolbarDrawer: comp => {
  18520. parts$a.getPart(comp, detail, 'toolbar').each(toolbar => {
  18521. mapFrom(toolbar.getApis().toggle, toggle => toggle(toolbar));
  18522. });
  18523. },
  18524. isToolbarDrawerToggled: comp => {
  18525. return parts$a.getPart(comp, detail, 'toolbar').bind(toolbar => Optional.from(toolbar.getApis().isOpen).map(isOpen => isOpen(toolbar))).getOr(false);
  18526. },
  18527. getThrobber: comp => {
  18528. return parts$a.getPart(comp, detail, 'throbber');
  18529. },
  18530. focusToolbar: comp => {
  18531. const optToolbar = parts$a.getPart(comp, detail, 'toolbar').orThunk(() => parts$a.getPart(comp, detail, 'multiple-toolbar'));
  18532. optToolbar.each(toolbar => {
  18533. Keying.focusIn(toolbar);
  18534. });
  18535. },
  18536. setMenubar: (comp, menus) => {
  18537. parts$a.getPart(comp, detail, 'menubar').each(menubar => {
  18538. SilverMenubar.setMenus(menubar, menus);
  18539. });
  18540. },
  18541. focusMenubar: comp => {
  18542. parts$a.getPart(comp, detail, 'menubar').each(menubar => {
  18543. SilverMenubar.focus(menubar);
  18544. });
  18545. }
  18546. };
  18547. return {
  18548. uid: detail.uid,
  18549. dom: detail.dom,
  18550. components,
  18551. apis,
  18552. behaviours: detail.behaviours
  18553. };
  18554. };
  18555. const partMenubar = partType.optional({
  18556. factory: SilverMenubar,
  18557. name: 'menubar',
  18558. schema: [required$1('backstage')]
  18559. });
  18560. const toolbarFactory = spec => {
  18561. if (spec.type === ToolbarMode$1.sliding) {
  18562. return renderSlidingMoreToolbar;
  18563. } else if (spec.type === ToolbarMode$1.floating) {
  18564. return renderFloatingMoreToolbar;
  18565. } else {
  18566. return renderToolbar;
  18567. }
  18568. };
  18569. const partMultipleToolbar = partType.optional({
  18570. factory: {
  18571. sketch: spec => CustomList.sketch({
  18572. uid: spec.uid,
  18573. dom: spec.dom,
  18574. listBehaviours: derive$1([Keying.config({
  18575. mode: 'acyclic',
  18576. selector: '.tox-toolbar'
  18577. })]),
  18578. makeItem: () => renderToolbar({
  18579. type: spec.type,
  18580. uid: generate$6('multiple-toolbar-item'),
  18581. cyclicKeying: false,
  18582. initGroups: [],
  18583. providers: spec.providers,
  18584. onEscape: () => {
  18585. spec.onEscape();
  18586. return Optional.some(true);
  18587. }
  18588. }),
  18589. setupItem: (_mToolbar, tc, data, _index) => {
  18590. Toolbar.setGroups(tc, data);
  18591. },
  18592. shell: true
  18593. })
  18594. },
  18595. name: 'multiple-toolbar',
  18596. schema: [
  18597. required$1('dom'),
  18598. required$1('onEscape')
  18599. ]
  18600. });
  18601. const partToolbar = partType.optional({
  18602. factory: {
  18603. sketch: spec => {
  18604. const renderer = toolbarFactory(spec);
  18605. const toolbarSpec = {
  18606. type: spec.type,
  18607. uid: spec.uid,
  18608. onEscape: () => {
  18609. spec.onEscape();
  18610. return Optional.some(true);
  18611. },
  18612. cyclicKeying: false,
  18613. initGroups: [],
  18614. getSink: spec.getSink,
  18615. providers: spec.providers,
  18616. moreDrawerData: {
  18617. lazyToolbar: spec.lazyToolbar,
  18618. lazyMoreButton: spec.lazyMoreButton,
  18619. lazyHeader: spec.lazyHeader
  18620. },
  18621. attributes: spec.attributes
  18622. };
  18623. return renderer(toolbarSpec);
  18624. }
  18625. },
  18626. name: 'toolbar',
  18627. schema: [
  18628. required$1('dom'),
  18629. required$1('onEscape'),
  18630. required$1('getSink')
  18631. ]
  18632. });
  18633. const partHeader = partType.optional({
  18634. factory: { sketch: renderHeader },
  18635. name: 'header',
  18636. schema: [required$1('dom')]
  18637. });
  18638. const partSocket = partType.optional({
  18639. name: 'socket',
  18640. schema: [required$1('dom')]
  18641. });
  18642. const partSidebar = partType.optional({
  18643. factory: { sketch: renderSidebar },
  18644. name: 'sidebar',
  18645. schema: [required$1('dom')]
  18646. });
  18647. const partThrobber = partType.optional({
  18648. factory: { sketch: renderThrobber },
  18649. name: 'throbber',
  18650. schema: [required$1('dom')]
  18651. });
  18652. var OuterContainer = composite({
  18653. name: 'OuterContainer',
  18654. factory: factory$6,
  18655. configFields: [
  18656. required$1('dom'),
  18657. required$1('behaviours')
  18658. ],
  18659. partFields: [
  18660. partHeader,
  18661. partMenubar,
  18662. partToolbar,
  18663. partMultipleToolbar,
  18664. partSocket,
  18665. partSidebar,
  18666. partThrobber
  18667. ],
  18668. apis: {
  18669. getSocket: (apis, comp) => {
  18670. return apis.getSocket(comp);
  18671. },
  18672. setSidebar: (apis, comp, panelConfigs) => {
  18673. apis.setSidebar(comp, panelConfigs);
  18674. },
  18675. toggleSidebar: (apis, comp, name) => {
  18676. apis.toggleSidebar(comp, name);
  18677. },
  18678. whichSidebar: (apis, comp) => {
  18679. return apis.whichSidebar(comp);
  18680. },
  18681. getHeader: (apis, comp) => {
  18682. return apis.getHeader(comp);
  18683. },
  18684. getToolbar: (apis, comp) => {
  18685. return apis.getToolbar(comp);
  18686. },
  18687. setToolbar: (apis, comp, grps) => {
  18688. const groups = map$2(grps, grp => {
  18689. return renderToolbarGroup(grp);
  18690. });
  18691. apis.setToolbar(comp, groups);
  18692. },
  18693. setToolbars: (apis, comp, ts) => {
  18694. const renderedToolbars = map$2(ts, g => map$2(g, renderToolbarGroup));
  18695. apis.setToolbars(comp, renderedToolbars);
  18696. },
  18697. refreshToolbar: (apis, comp) => {
  18698. return apis.refreshToolbar(comp);
  18699. },
  18700. toggleToolbarDrawer: (apis, comp) => {
  18701. apis.toggleToolbarDrawer(comp);
  18702. },
  18703. isToolbarDrawerToggled: (apis, comp) => {
  18704. return apis.isToolbarDrawerToggled(comp);
  18705. },
  18706. getThrobber: (apis, comp) => {
  18707. return apis.getThrobber(comp);
  18708. },
  18709. setMenubar: (apis, comp, menus) => {
  18710. apis.setMenubar(comp, menus);
  18711. },
  18712. focusMenubar: (apis, comp) => {
  18713. apis.focusMenubar(comp);
  18714. },
  18715. focusToolbar: (apis, comp) => {
  18716. apis.focusToolbar(comp);
  18717. }
  18718. }
  18719. });
  18720. const defaultMenubar = 'file edit view insert format tools table help';
  18721. const defaultMenus = {
  18722. file: {
  18723. title: 'File',
  18724. items: 'newdocument restoredraft | preview | export print | deleteallconversations'
  18725. },
  18726. edit: {
  18727. title: 'Edit',
  18728. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  18729. },
  18730. view: {
  18731. title: 'View',
  18732. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  18733. },
  18734. insert: {
  18735. title: 'Insert',
  18736. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime'
  18737. },
  18738. format: {
  18739. title: 'Format',
  18740. items: 'bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat'
  18741. },
  18742. tools: {
  18743. title: 'Tools',
  18744. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  18745. },
  18746. table: {
  18747. title: 'Table',
  18748. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  18749. },
  18750. help: {
  18751. title: 'Help',
  18752. items: 'help'
  18753. }
  18754. };
  18755. const make = (menu, registry, editor) => {
  18756. const removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  18757. return {
  18758. text: menu.title,
  18759. getItems: () => bind$3(menu.items, i => {
  18760. const itemName = i.toLowerCase();
  18761. if (itemName.trim().length === 0) {
  18762. return [];
  18763. } else if (exists(removedMenuItems, removedMenuItem => removedMenuItem === itemName)) {
  18764. return [];
  18765. } else if (itemName === 'separator' || itemName === '|') {
  18766. return [{ type: 'separator' }];
  18767. } else if (registry.menuItems[itemName]) {
  18768. return [registry.menuItems[itemName]];
  18769. } else {
  18770. return [];
  18771. }
  18772. })
  18773. };
  18774. };
  18775. const parseItemsString = items => {
  18776. if (typeof items === 'string') {
  18777. return items.split(' ');
  18778. }
  18779. return items;
  18780. };
  18781. const identifyMenus = (editor, registry) => {
  18782. const rawMenuData = {
  18783. ...defaultMenus,
  18784. ...registry.menus
  18785. };
  18786. const userDefinedMenus = keys(registry.menus).length > 0;
  18787. const menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  18788. const validMenus = filter$2(menubar, menuName => {
  18789. const isDefaultMenu = has$2(defaultMenus, menuName);
  18790. if (userDefinedMenus) {
  18791. return isDefaultMenu || get$g(registry.menus, menuName).exists(menu => has$2(menu, 'items'));
  18792. } else {
  18793. return isDefaultMenu;
  18794. }
  18795. });
  18796. const menus = map$2(validMenus, menuName => {
  18797. const menuData = rawMenuData[menuName];
  18798. return make({
  18799. title: menuData.title,
  18800. items: parseItemsString(menuData.items)
  18801. }, registry, editor);
  18802. });
  18803. return filter$2(menus, menu => {
  18804. const isNotSeparator = item => item.type !== 'separator';
  18805. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  18806. });
  18807. };
  18808. const fireSkinLoaded = editor => {
  18809. const done = () => {
  18810. editor._skinLoaded = true;
  18811. fireSkinLoaded$1(editor);
  18812. };
  18813. return () => {
  18814. if (editor.initialized) {
  18815. done();
  18816. } else {
  18817. editor.on('init', done);
  18818. }
  18819. };
  18820. };
  18821. const fireSkinLoadError = (editor, err) => () => fireSkinLoadError$1(editor, { message: err });
  18822. const loadStylesheet = (editor, stylesheetUrl, styleSheetLoader) => {
  18823. editor.on('remove', () => styleSheetLoader.unload(stylesheetUrl));
  18824. return styleSheetLoader.load(stylesheetUrl);
  18825. };
  18826. const loadUiSkins = (editor, skinUrl) => {
  18827. const skinUiCss = skinUrl + '/skin.min.css';
  18828. return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
  18829. };
  18830. const loadShadowDomUiSkins = (editor, skinUrl) => {
  18831. const isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
  18832. if (isInShadowRoot$1) {
  18833. const shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css';
  18834. return loadStylesheet(editor, shadowDomSkinCss, global$7.DOM.styleSheetLoader);
  18835. } else {
  18836. return Promise.resolve();
  18837. }
  18838. };
  18839. const loadSkin = (isInline, editor) => {
  18840. const skinUrl = getSkinUrl(editor);
  18841. if (skinUrl) {
  18842. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  18843. }
  18844. if (!isSkinDisabled(editor) && isString(skinUrl)) {
  18845. Promise.all([
  18846. loadUiSkins(editor, skinUrl),
  18847. loadShadowDomUiSkins(editor, skinUrl)
  18848. ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, 'Skin could not be loaded'));
  18849. } else {
  18850. fireSkinLoaded(editor)();
  18851. }
  18852. };
  18853. const iframe = curry(loadSkin, false);
  18854. const inline = curry(loadSkin, true);
  18855. const onSetupFormatToggle = (editor, name) => api => {
  18856. const boundCallback = unbindable();
  18857. const init = () => {
  18858. api.setActive(editor.formatter.match(name));
  18859. const binding = editor.formatter.formatChanged(name, api.setActive);
  18860. boundCallback.set(binding);
  18861. };
  18862. editor.initialized ? init() : editor.once('init', init);
  18863. return () => {
  18864. editor.off('init', init);
  18865. boundCallback.clear();
  18866. };
  18867. };
  18868. const onSetupEvent = (editor, event, f) => api => {
  18869. const handleEvent = () => f(api);
  18870. const init = () => {
  18871. f(api);
  18872. editor.on(event, handleEvent);
  18873. };
  18874. editor.initialized ? init() : editor.once('init', init);
  18875. return () => {
  18876. editor.off('init', init);
  18877. editor.off(event, handleEvent);
  18878. };
  18879. };
  18880. const onActionToggleFormat$1 = editor => rawItem => () => {
  18881. editor.undoManager.transact(() => {
  18882. editor.focus();
  18883. editor.execCommand('mceToggleFormat', false, rawItem.format);
  18884. });
  18885. };
  18886. const onActionExecCommand = (editor, command) => () => editor.execCommand(command);
  18887. const generateSelectItems = (_editor, backstage, spec) => {
  18888. const generateItem = (rawItem, response, invalid, value) => {
  18889. const translatedText = backstage.shared.providers.translate(rawItem.title);
  18890. if (rawItem.type === 'separator') {
  18891. return Optional.some({
  18892. type: 'separator',
  18893. text: translatedText
  18894. });
  18895. } else if (rawItem.type === 'submenu') {
  18896. const items = bind$3(rawItem.getStyleItems(), si => validate(si, response, value));
  18897. if (response === 0 && items.length <= 0) {
  18898. return Optional.none();
  18899. } else {
  18900. return Optional.some({
  18901. type: 'nestedmenuitem',
  18902. text: translatedText,
  18903. enabled: items.length > 0,
  18904. getSubmenuItems: () => bind$3(rawItem.getStyleItems(), si => validate(si, response, value))
  18905. });
  18906. }
  18907. } else {
  18908. return Optional.some({
  18909. type: 'togglemenuitem',
  18910. text: translatedText,
  18911. icon: rawItem.icon,
  18912. active: rawItem.isSelected(value),
  18913. enabled: !invalid,
  18914. onAction: spec.onAction(rawItem),
  18915. ...rawItem.getStylePreview().fold(() => ({}), preview => ({ meta: { style: preview } }))
  18916. });
  18917. }
  18918. };
  18919. const validate = (item, response, value) => {
  18920. const invalid = item.type === 'formatter' && spec.isInvalid(item);
  18921. if (response === 0) {
  18922. return invalid ? [] : generateItem(item, response, false, value).toArray();
  18923. } else {
  18924. return generateItem(item, response, invalid, value).toArray();
  18925. }
  18926. };
  18927. const validateItems = preItems => {
  18928. const value = spec.getCurrentValue();
  18929. const response = spec.shouldHide ? 0 : 1;
  18930. return bind$3(preItems, item => validate(item, response, value));
  18931. };
  18932. const getFetch = (backstage, getStyleItems) => (comp, callback) => {
  18933. const preItems = getStyleItems();
  18934. const items = validateItems(preItems);
  18935. const menu = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  18936. callback(menu);
  18937. };
  18938. return {
  18939. validateItems,
  18940. getFetch
  18941. };
  18942. };
  18943. const createMenuItems = (editor, backstage, spec) => {
  18944. const dataset = spec.dataset;
  18945. const getStyleItems = dataset.type === 'basic' ? () => map$2(dataset.data, d => processBasic(d, spec.isSelectedFor, spec.getPreviewFor)) : dataset.getData;
  18946. return {
  18947. items: generateSelectItems(editor, backstage, spec),
  18948. getStyleItems
  18949. };
  18950. };
  18951. const createSelectButton = (editor, backstage, spec) => {
  18952. const {items, getStyleItems} = createMenuItems(editor, backstage, spec);
  18953. const getApi = comp => ({ getComponent: constant$1(comp) });
  18954. const onSetup = onSetupEvent(editor, 'NodeChange', api => {
  18955. const comp = api.getComponent();
  18956. spec.updateText(comp);
  18957. });
  18958. return renderCommonDropdown({
  18959. text: spec.icon.isSome() ? Optional.none() : spec.text,
  18960. icon: spec.icon,
  18961. tooltip: Optional.from(spec.tooltip),
  18962. role: Optional.none(),
  18963. fetch: items.getFetch(backstage, getStyleItems),
  18964. onSetup,
  18965. getApi,
  18966. columns: 1,
  18967. presets: 'normal',
  18968. classes: spec.icon.isSome() ? [] : ['bespoke'],
  18969. dropdownBehaviours: []
  18970. }, 'tox-tbtn', backstage.shared);
  18971. };
  18972. const process = rawFormats => map$2(rawFormats, item => {
  18973. let title = item, format = item;
  18974. const values = item.split('=');
  18975. if (values.length > 1) {
  18976. title = values[0];
  18977. format = values[1];
  18978. }
  18979. return {
  18980. title,
  18981. format
  18982. };
  18983. });
  18984. const buildBasicStaticDataset = data => ({
  18985. type: 'basic',
  18986. data
  18987. });
  18988. var Delimiter;
  18989. (function (Delimiter) {
  18990. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  18991. Delimiter[Delimiter['Space'] = 1] = 'Space';
  18992. }(Delimiter || (Delimiter = {})));
  18993. const split = (rawFormats, delimiter) => {
  18994. if (delimiter === Delimiter.SemiColon) {
  18995. return rawFormats.replace(/;$/, '').split(';');
  18996. } else {
  18997. return rawFormats.split(' ');
  18998. }
  18999. };
  19000. const buildBasicSettingsDataset = (editor, settingName, delimiter) => {
  19001. const rawFormats = editor.options.get(settingName);
  19002. const data = process(split(rawFormats, delimiter));
  19003. return {
  19004. type: 'basic',
  19005. data
  19006. };
  19007. };
  19008. const alignMenuItems = [
  19009. {
  19010. title: 'Left',
  19011. icon: 'align-left',
  19012. format: 'alignleft',
  19013. command: 'JustifyLeft'
  19014. },
  19015. {
  19016. title: 'Center',
  19017. icon: 'align-center',
  19018. format: 'aligncenter',
  19019. command: 'JustifyCenter'
  19020. },
  19021. {
  19022. title: 'Right',
  19023. icon: 'align-right',
  19024. format: 'alignright',
  19025. command: 'JustifyRight'
  19026. },
  19027. {
  19028. title: 'Justify',
  19029. icon: 'align-justify',
  19030. format: 'alignjustify',
  19031. command: 'JustifyFull'
  19032. }
  19033. ];
  19034. const getSpec$4 = editor => {
  19035. const getMatchingValue = () => find$5(alignMenuItems, item => editor.formatter.match(item.format));
  19036. const isSelectedFor = format => () => editor.formatter.match(format);
  19037. const getPreviewFor = _format => Optional.none;
  19038. const updateSelectMenuIcon = comp => {
  19039. const match = getMatchingValue();
  19040. const alignment = match.fold(constant$1('left'), item => item.title.toLowerCase());
  19041. emitWith(comp, updateMenuIcon, { icon: `align-${ alignment }` });
  19042. };
  19043. const dataset = buildBasicStaticDataset(alignMenuItems);
  19044. const onAction = rawItem => () => find$5(alignMenuItems, item => item.format === rawItem.format).each(item => editor.execCommand(item.command));
  19045. return {
  19046. tooltip: 'Align',
  19047. text: Optional.none(),
  19048. icon: Optional.some('align-left'),
  19049. isSelectedFor,
  19050. getCurrentValue: Optional.none,
  19051. getPreviewFor,
  19052. onAction,
  19053. updateText: updateSelectMenuIcon,
  19054. dataset,
  19055. shouldHide: false,
  19056. isInvalid: item => !editor.formatter.canApply(item.format)
  19057. };
  19058. };
  19059. const createAlignButton = (editor, backstage) => createSelectButton(editor, backstage, getSpec$4(editor));
  19060. const createAlignMenu = (editor, backstage) => {
  19061. const menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
  19062. editor.ui.registry.addNestedMenuItem('align', {
  19063. text: backstage.shared.providers.translate('Align'),
  19064. getSubmenuItems: () => menuItems.items.validateItems(menuItems.getStyleItems())
  19065. });
  19066. };
  19067. const findNearest = (editor, getStyles) => {
  19068. const styles = getStyles();
  19069. const formats = map$2(styles, style => style.format);
  19070. return Optional.from(editor.formatter.closest(formats)).bind(fmt => find$5(styles, data => data.format === fmt)).orThunk(() => someIf(editor.formatter.match('p'), {
  19071. title: 'Paragraph',
  19072. format: 'p'
  19073. }));
  19074. };
  19075. const getSpec$3 = editor => {
  19076. const fallbackFormat = 'Paragraph';
  19077. const isSelectedFor = format => () => editor.formatter.match(format);
  19078. const getPreviewFor = format => () => {
  19079. const fmt = editor.formatter.get(format);
  19080. return Optional.some({
  19081. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  19082. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  19083. });
  19084. };
  19085. const updateSelectMenuText = comp => {
  19086. const detectedFormat = findNearest(editor, () => dataset.data);
  19087. const text = detectedFormat.fold(constant$1(fallbackFormat), fmt => fmt.title);
  19088. emitWith(comp, updateMenuText, { text });
  19089. };
  19090. const dataset = buildBasicSettingsDataset(editor, 'block_formats', Delimiter.SemiColon);
  19091. return {
  19092. tooltip: 'Blocks',
  19093. text: Optional.some(fallbackFormat),
  19094. icon: Optional.none(),
  19095. isSelectedFor,
  19096. getCurrentValue: Optional.none,
  19097. getPreviewFor,
  19098. onAction: onActionToggleFormat$1(editor),
  19099. updateText: updateSelectMenuText,
  19100. dataset,
  19101. shouldHide: false,
  19102. isInvalid: item => !editor.formatter.canApply(item.format)
  19103. };
  19104. };
  19105. const createBlocksButton = (editor, backstage) => createSelectButton(editor, backstage, getSpec$3(editor));
  19106. const createBlocksMenu = (editor, backstage) => {
  19107. const menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  19108. editor.ui.registry.addNestedMenuItem('blocks', {
  19109. text: 'Blocks',
  19110. getSubmenuItems: () => menuItems.items.validateItems(menuItems.getStyleItems())
  19111. });
  19112. };
  19113. const systemStackFonts = [
  19114. '-apple-system',
  19115. 'Segoe UI',
  19116. 'Roboto',
  19117. 'Helvetica Neue',
  19118. 'sans-serif'
  19119. ];
  19120. const splitFonts = fontFamily => {
  19121. const fonts = fontFamily.split(/\s*,\s*/);
  19122. return map$2(fonts, font => font.replace(/^['"]+|['"]+$/g, ''));
  19123. };
  19124. const isSystemFontStack = fontFamily => {
  19125. const matchesSystemStack = () => {
  19126. const fonts = splitFonts(fontFamily.toLowerCase());
  19127. return forall(systemStackFonts, font => fonts.indexOf(font.toLowerCase()) > -1);
  19128. };
  19129. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  19130. };
  19131. const getSpec$2 = editor => {
  19132. const systemFont = 'System Font';
  19133. const getMatchingValue = () => {
  19134. const getFirstFont = fontFamily => fontFamily ? splitFonts(fontFamily)[0] : '';
  19135. const fontFamily = editor.queryCommandValue('FontName');
  19136. const items = dataset.data;
  19137. const font = fontFamily ? fontFamily.toLowerCase() : '';
  19138. const matchOpt = find$5(items, item => {
  19139. const format = item.format;
  19140. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  19141. }).orThunk(() => {
  19142. return someIf(isSystemFontStack(font), {
  19143. title: systemFont,
  19144. format: font
  19145. });
  19146. });
  19147. return {
  19148. matchOpt,
  19149. font: fontFamily
  19150. };
  19151. };
  19152. const isSelectedFor = item => valueOpt => valueOpt.exists(value => value.format === item);
  19153. const getCurrentValue = () => {
  19154. const {matchOpt} = getMatchingValue();
  19155. return matchOpt;
  19156. };
  19157. const getPreviewFor = item => () => Optional.some({
  19158. tag: 'div',
  19159. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  19160. });
  19161. const onAction = rawItem => () => {
  19162. editor.undoManager.transact(() => {
  19163. editor.focus();
  19164. editor.execCommand('FontName', false, rawItem.format);
  19165. });
  19166. };
  19167. const updateSelectMenuText = comp => {
  19168. const {matchOpt, font} = getMatchingValue();
  19169. const text = matchOpt.fold(constant$1(font), item => item.title);
  19170. emitWith(comp, updateMenuText, { text });
  19171. };
  19172. const dataset = buildBasicSettingsDataset(editor, 'font_family_formats', Delimiter.SemiColon);
  19173. return {
  19174. tooltip: 'Fonts',
  19175. text: Optional.some(systemFont),
  19176. icon: Optional.none(),
  19177. isSelectedFor,
  19178. getCurrentValue,
  19179. getPreviewFor,
  19180. onAction,
  19181. updateText: updateSelectMenuText,
  19182. dataset,
  19183. shouldHide: false,
  19184. isInvalid: never
  19185. };
  19186. };
  19187. const createFontFamilyButton = (editor, backstage) => createSelectButton(editor, backstage, getSpec$2(editor));
  19188. const createFontFamilyMenu = (editor, backstage) => {
  19189. const menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  19190. editor.ui.registry.addNestedMenuItem('fontfamily', {
  19191. text: backstage.shared.providers.translate('Fonts'),
  19192. getSubmenuItems: () => menuItems.items.validateItems(menuItems.getStyleItems())
  19193. });
  19194. };
  19195. const legacyFontSizes = {
  19196. '8pt': '1',
  19197. '10pt': '2',
  19198. '12pt': '3',
  19199. '14pt': '4',
  19200. '18pt': '5',
  19201. '24pt': '6',
  19202. '36pt': '7'
  19203. };
  19204. const keywordFontSizes = {
  19205. 'xx-small': '7pt',
  19206. 'x-small': '8pt',
  19207. 'small': '10pt',
  19208. 'medium': '12pt',
  19209. 'large': '14pt',
  19210. 'x-large': '18pt',
  19211. 'xx-large': '24pt'
  19212. };
  19213. const round = (number, precision) => {
  19214. const factor = Math.pow(10, precision);
  19215. return Math.round(number * factor) / factor;
  19216. };
  19217. const toPt = (fontSize, precision) => {
  19218. if (/[0-9.]+px$/.test(fontSize)) {
  19219. return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  19220. } else {
  19221. return get$g(keywordFontSizes, fontSize).getOr(fontSize);
  19222. }
  19223. };
  19224. const toLegacy = fontSize => get$g(legacyFontSizes, fontSize).getOr('');
  19225. const getSpec$1 = editor => {
  19226. const getMatchingValue = () => {
  19227. let matchOpt = Optional.none();
  19228. const items = dataset.data;
  19229. const fontSize = editor.queryCommandValue('FontSize');
  19230. if (fontSize) {
  19231. for (let precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  19232. const pt = toPt(fontSize, precision);
  19233. const legacy = toLegacy(pt);
  19234. matchOpt = find$5(items, item => item.format === fontSize || item.format === pt || item.format === legacy);
  19235. }
  19236. }
  19237. return {
  19238. matchOpt,
  19239. size: fontSize
  19240. };
  19241. };
  19242. const isSelectedFor = item => valueOpt => valueOpt.exists(value => value.format === item);
  19243. const getCurrentValue = () => {
  19244. const {matchOpt} = getMatchingValue();
  19245. return matchOpt;
  19246. };
  19247. const getPreviewFor = constant$1(Optional.none);
  19248. const onAction = rawItem => () => {
  19249. editor.undoManager.transact(() => {
  19250. editor.focus();
  19251. editor.execCommand('FontSize', false, rawItem.format);
  19252. });
  19253. };
  19254. const updateSelectMenuText = comp => {
  19255. const {matchOpt, size} = getMatchingValue();
  19256. const text = matchOpt.fold(constant$1(size), match => match.title);
  19257. emitWith(comp, updateMenuText, { text });
  19258. };
  19259. const dataset = buildBasicSettingsDataset(editor, 'font_size_formats', Delimiter.Space);
  19260. return {
  19261. tooltip: 'Font sizes',
  19262. text: Optional.some('12pt'),
  19263. icon: Optional.none(),
  19264. isSelectedFor,
  19265. getPreviewFor,
  19266. getCurrentValue,
  19267. onAction,
  19268. updateText: updateSelectMenuText,
  19269. dataset,
  19270. shouldHide: false,
  19271. isInvalid: never
  19272. };
  19273. };
  19274. const createFontSizeButton = (editor, backstage) => createSelectButton(editor, backstage, getSpec$1(editor));
  19275. const createFontSizeMenu = (editor, backstage) => {
  19276. const menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  19277. editor.ui.registry.addNestedMenuItem('fontsize', {
  19278. text: 'Font sizes',
  19279. getSubmenuItems: () => menuItems.items.validateItems(menuItems.getStyleItems())
  19280. });
  19281. };
  19282. const getSpec = (editor, dataset) => {
  19283. const fallbackFormat = 'Paragraph';
  19284. const isSelectedFor = format => () => editor.formatter.match(format);
  19285. const getPreviewFor = format => () => {
  19286. const fmt = editor.formatter.get(format);
  19287. return fmt !== undefined ? Optional.some({
  19288. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  19289. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  19290. }) : Optional.none();
  19291. };
  19292. const updateSelectMenuText = comp => {
  19293. const getFormatItems = fmt => {
  19294. const subs = fmt.items;
  19295. return subs !== undefined && subs.length > 0 ? bind$3(subs, getFormatItems) : [{
  19296. title: fmt.title,
  19297. format: fmt.format
  19298. }];
  19299. };
  19300. const flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
  19301. const detectedFormat = findNearest(editor, constant$1(flattenedItems));
  19302. const text = detectedFormat.fold(constant$1(fallbackFormat), fmt => fmt.title);
  19303. emitWith(comp, updateMenuText, { text });
  19304. };
  19305. return {
  19306. tooltip: 'Formats',
  19307. text: Optional.some(fallbackFormat),
  19308. icon: Optional.none(),
  19309. isSelectedFor,
  19310. getCurrentValue: Optional.none,
  19311. getPreviewFor,
  19312. onAction: onActionToggleFormat$1(editor),
  19313. updateText: updateSelectMenuText,
  19314. shouldHide: shouldAutoHideStyleFormats(editor),
  19315. isInvalid: item => !editor.formatter.canApply(item.format),
  19316. dataset
  19317. };
  19318. };
  19319. const createStylesButton = (editor, backstage) => {
  19320. const dataset = {
  19321. type: 'advanced',
  19322. ...backstage.styles
  19323. };
  19324. return createSelectButton(editor, backstage, getSpec(editor, dataset));
  19325. };
  19326. const createStylesMenu = (editor, backstage) => {
  19327. const dataset = {
  19328. type: 'advanced',
  19329. ...backstage.styles
  19330. };
  19331. const menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset));
  19332. editor.ui.registry.addNestedMenuItem('styles', {
  19333. text: 'Formats',
  19334. getSubmenuItems: () => menuItems.items.validateItems(menuItems.getStyleItems())
  19335. });
  19336. };
  19337. const events$3 = (reflectingConfig, reflectingState) => {
  19338. const update = (component, data) => {
  19339. reflectingConfig.updateState.each(updateState => {
  19340. const newState = updateState(component, data);
  19341. reflectingState.set(newState);
  19342. });
  19343. reflectingConfig.renderComponents.each(renderComponents => {
  19344. const newComponents = renderComponents(data, reflectingState.get());
  19345. const replacer = reflectingConfig.reuseDom ? withReuse : withoutReuse;
  19346. replacer(component, newComponents);
  19347. });
  19348. };
  19349. return derive$2([
  19350. run$1(receive(), (component, message) => {
  19351. const receivingData = message;
  19352. if (!receivingData.universal) {
  19353. const channel = reflectingConfig.channel;
  19354. if (contains$2(receivingData.channels, channel)) {
  19355. update(component, receivingData.data);
  19356. }
  19357. }
  19358. }),
  19359. runOnAttached((comp, _se) => {
  19360. reflectingConfig.initialData.each(rawData => {
  19361. update(comp, rawData);
  19362. });
  19363. })
  19364. ]);
  19365. };
  19366. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  19367. __proto__: null,
  19368. events: events$3
  19369. });
  19370. const getState = (component, replaceConfig, reflectState) => reflectState;
  19371. var ReflectingApis = /*#__PURE__*/Object.freeze({
  19372. __proto__: null,
  19373. getState: getState
  19374. });
  19375. var ReflectingSchema = [
  19376. required$1('channel'),
  19377. option$3('renderComponents'),
  19378. option$3('updateState'),
  19379. option$3('initialData'),
  19380. defaultedBoolean('reuseDom', true)
  19381. ];
  19382. const init$3 = () => {
  19383. const cell = Cell(Optional.none());
  19384. const clear = () => cell.set(Optional.none());
  19385. const readState = () => cell.get().getOr('none');
  19386. return {
  19387. readState,
  19388. get: cell.get,
  19389. set: cell.set,
  19390. clear
  19391. };
  19392. };
  19393. var ReflectingState = /*#__PURE__*/Object.freeze({
  19394. __proto__: null,
  19395. init: init$3
  19396. });
  19397. const Reflecting = create$3({
  19398. fields: ReflectingSchema,
  19399. name: 'reflecting',
  19400. active: ActiveReflecting,
  19401. apis: ReflectingApis,
  19402. state: ReflectingState
  19403. });
  19404. const schema$7 = constant$1([
  19405. required$1('toggleClass'),
  19406. required$1('fetch'),
  19407. onStrictHandler('onExecute'),
  19408. defaulted('getHotspot', Optional.some),
  19409. defaulted('getAnchorOverrides', constant$1({})),
  19410. schema$y(),
  19411. onStrictHandler('onItemExecute'),
  19412. option$3('lazySink'),
  19413. required$1('dom'),
  19414. onHandler('onOpen'),
  19415. field('splitDropdownBehaviours', [
  19416. Coupling,
  19417. Keying,
  19418. Focusing
  19419. ]),
  19420. defaulted('matchWidth', false),
  19421. defaulted('useMinWidth', false),
  19422. defaulted('eventOrder', {}),
  19423. option$3('role')
  19424. ].concat(sandboxFields()));
  19425. const arrowPart = required({
  19426. factory: Button,
  19427. schema: [required$1('dom')],
  19428. name: 'arrow',
  19429. defaults: () => {
  19430. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  19431. },
  19432. overrides: detail => {
  19433. return {
  19434. dom: {
  19435. tag: 'span',
  19436. attributes: { role: 'presentation' }
  19437. },
  19438. action: arrow => {
  19439. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  19440. },
  19441. buttonBehaviours: derive$1([Toggling.config({
  19442. toggleOnExecute: false,
  19443. toggleClass: detail.toggleClass
  19444. })])
  19445. };
  19446. }
  19447. });
  19448. const buttonPart = required({
  19449. factory: Button,
  19450. schema: [required$1('dom')],
  19451. name: 'button',
  19452. defaults: () => {
  19453. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  19454. },
  19455. overrides: detail => {
  19456. return {
  19457. dom: {
  19458. tag: 'span',
  19459. attributes: { role: 'presentation' }
  19460. },
  19461. action: btn => {
  19462. btn.getSystem().getByUid(detail.uid).each(splitDropdown => {
  19463. detail.onExecute(splitDropdown, btn);
  19464. });
  19465. }
  19466. };
  19467. }
  19468. });
  19469. const parts$3 = constant$1([
  19470. arrowPart,
  19471. buttonPart,
  19472. optional({
  19473. factory: {
  19474. sketch: spec => {
  19475. return {
  19476. uid: spec.uid,
  19477. dom: {
  19478. tag: 'span',
  19479. styles: { display: 'none' },
  19480. attributes: { 'aria-hidden': 'true' },
  19481. innerHtml: spec.text
  19482. }
  19483. };
  19484. }
  19485. },
  19486. schema: [required$1('text')],
  19487. name: 'aria-descriptor'
  19488. }),
  19489. external({
  19490. schema: [tieredMenuMarkers()],
  19491. name: 'menu',
  19492. defaults: detail => {
  19493. return {
  19494. onExecute: (tmenu, item) => {
  19495. tmenu.getSystem().getByUid(detail.uid).each(splitDropdown => {
  19496. detail.onItemExecute(splitDropdown, tmenu, item);
  19497. });
  19498. }
  19499. };
  19500. }
  19501. }),
  19502. partType$1()
  19503. ]);
  19504. const factory$5 = (detail, components, spec, externals) => {
  19505. const switchToMenu = sandbox => {
  19506. Composing.getCurrent(sandbox).each(current => {
  19507. Highlighting.highlightFirst(current);
  19508. Keying.focusIn(current);
  19509. });
  19510. };
  19511. const action = component => {
  19512. const onOpenSync = switchToMenu;
  19513. togglePopup(detail, identity, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19514. };
  19515. const openMenu = comp => {
  19516. action(comp);
  19517. return Optional.some(true);
  19518. };
  19519. const executeOnButton = comp => {
  19520. const button = getPartOrDie(comp, detail, 'button');
  19521. emitExecute(button);
  19522. return Optional.some(true);
  19523. };
  19524. const buttonEvents = {
  19525. ...derive$2([runOnAttached((component, _simulatedEvent) => {
  19526. const ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  19527. ariaDescriptor.each(descriptor => {
  19528. const descriptorId = generate$6('aria');
  19529. set$9(descriptor.element, 'id', descriptorId);
  19530. set$9(component.element, 'aria-describedby', descriptorId);
  19531. });
  19532. })]),
  19533. ...events$a(Optional.some(action))
  19534. };
  19535. const apis = {
  19536. repositionMenus: comp => {
  19537. if (Toggling.isOn(comp)) {
  19538. repositionMenus(comp);
  19539. }
  19540. }
  19541. };
  19542. return {
  19543. uid: detail.uid,
  19544. dom: detail.dom,
  19545. components,
  19546. apis,
  19547. eventOrder: {
  19548. ...detail.eventOrder,
  19549. [execute$5()]: [
  19550. 'disabling',
  19551. 'toggling',
  19552. 'alloy.base.behaviour'
  19553. ]
  19554. },
  19555. events: buttonEvents,
  19556. behaviours: augment(detail.splitDropdownBehaviours, [
  19557. Coupling.config({
  19558. others: {
  19559. sandbox: hotspot => {
  19560. const arrow = getPartOrDie(hotspot, detail, 'arrow');
  19561. const extras = {
  19562. onOpen: () => {
  19563. Toggling.on(arrow);
  19564. Toggling.on(hotspot);
  19565. },
  19566. onClose: () => {
  19567. Toggling.off(arrow);
  19568. Toggling.off(hotspot);
  19569. }
  19570. };
  19571. return makeSandbox$1(detail, hotspot, extras);
  19572. }
  19573. }
  19574. }),
  19575. Keying.config({
  19576. mode: 'special',
  19577. onSpace: executeOnButton,
  19578. onEnter: executeOnButton,
  19579. onDown: openMenu
  19580. }),
  19581. Focusing.config({}),
  19582. Toggling.config({
  19583. toggleOnExecute: false,
  19584. aria: { mode: 'expanded' }
  19585. })
  19586. ]),
  19587. domModification: {
  19588. attributes: {
  19589. 'role': detail.role.getOr('button'),
  19590. 'aria-haspopup': true
  19591. }
  19592. }
  19593. };
  19594. };
  19595. const SplitDropdown = composite({
  19596. name: 'SplitDropdown',
  19597. configFields: schema$7(),
  19598. partFields: parts$3(),
  19599. factory: factory$5,
  19600. apis: { repositionMenus: (apis, comp) => apis.repositionMenus(comp) }
  19601. });
  19602. const getButtonApi = component => ({
  19603. isEnabled: () => !Disabling.isDisabled(component),
  19604. setEnabled: state => Disabling.set(component, !state)
  19605. });
  19606. const getToggleApi = component => ({
  19607. setActive: state => {
  19608. Toggling.set(component, state);
  19609. },
  19610. isActive: () => Toggling.isOn(component),
  19611. isEnabled: () => !Disabling.isDisabled(component),
  19612. setEnabled: state => Disabling.set(component, !state)
  19613. });
  19614. const getTooltipAttributes = (tooltip, providersBackstage) => tooltip.map(tooltip => ({
  19615. 'aria-label': providersBackstage.translate(tooltip),
  19616. 'title': providersBackstage.translate(tooltip)
  19617. })).getOr({});
  19618. const focusButtonEvent = generate$6('focus-button');
  19619. const renderCommonStructure = (icon, text, tooltip, receiver, behaviours, providersBackstage) => {
  19620. return {
  19621. dom: {
  19622. tag: 'button',
  19623. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []),
  19624. attributes: getTooltipAttributes(tooltip, providersBackstage)
  19625. },
  19626. components: componentRenderPipeline([
  19627. icon.map(iconName => renderIconFromPack(iconName, providersBackstage.icons)),
  19628. text.map(text => renderLabel(text, 'tox-tbtn', providersBackstage))
  19629. ]),
  19630. eventOrder: {
  19631. [mousedown()]: [
  19632. 'focusing',
  19633. 'alloy.base.behaviour',
  19634. 'common-button-display-events'
  19635. ]
  19636. },
  19637. buttonBehaviours: derive$1([
  19638. DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
  19639. receivingConfig(),
  19640. config('common-button-display-events', [run$1(mousedown(), (button, se) => {
  19641. se.event.prevent();
  19642. emit(button, focusButtonEvent);
  19643. })])
  19644. ].concat(receiver.map(r => Reflecting.config({
  19645. channel: r,
  19646. initialData: {
  19647. icon,
  19648. text
  19649. },
  19650. renderComponents: (data, _state) => componentRenderPipeline([
  19651. data.icon.map(iconName => renderIconFromPack(iconName, providersBackstage.icons)),
  19652. data.text.map(text => renderLabel(text, 'tox-tbtn', providersBackstage))
  19653. ])
  19654. })).toArray()).concat(behaviours.getOr([])))
  19655. };
  19656. };
  19657. const renderFloatingToolbarButton = (spec, backstage, identifyButtons, attributes) => {
  19658. const sharedBackstage = backstage.shared;
  19659. return FloatingToolbarButton.sketch({
  19660. lazySink: sharedBackstage.getSink,
  19661. fetch: () => Future.nu(resolve => {
  19662. resolve(map$2(identifyButtons(spec.items), renderToolbarGroup));
  19663. }),
  19664. markers: { toggledClass: 'tox-tbtn--enabled' },
  19665. parts: {
  19666. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
  19667. toolbar: {
  19668. dom: {
  19669. tag: 'div',
  19670. classes: ['tox-toolbar__overflow'],
  19671. attributes
  19672. }
  19673. }
  19674. }
  19675. });
  19676. };
  19677. const renderCommonToolbarButton = (spec, specialisation, providersBackstage) => {
  19678. const editorOffCell = Cell(noop);
  19679. const structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
  19680. return Button.sketch({
  19681. dom: structure.dom,
  19682. components: structure.components,
  19683. eventOrder: toolbarButtonEventOrder,
  19684. buttonBehaviours: derive$1([
  19685. config('toolbar-button-events', [
  19686. onToolbarButtonExecute({
  19687. onAction: spec.onAction,
  19688. getApi: specialisation.getApi
  19689. }),
  19690. onControlAttached(specialisation, editorOffCell),
  19691. onControlDetached(specialisation, editorOffCell)
  19692. ]),
  19693. DisablingConfigs.toolbarButton(() => !spec.enabled || providersBackstage.isDisabled()),
  19694. receivingConfig()
  19695. ].concat(specialisation.toolbarButtonBehaviours))
  19696. });
  19697. };
  19698. const renderToolbarButton = (spec, providersBackstage) => renderToolbarButtonWith(spec, providersBackstage, []);
  19699. const renderToolbarButtonWith = (spec, providersBackstage, bonusEvents) => renderCommonToolbarButton(spec, {
  19700. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  19701. getApi: getButtonApi,
  19702. onSetup: spec.onSetup
  19703. }, providersBackstage);
  19704. const renderToolbarToggleButton = (spec, providersBackstage) => renderToolbarToggleButtonWith(spec, providersBackstage, []);
  19705. const renderToolbarToggleButtonWith = (spec, providersBackstage, bonusEvents) => deepMerge(renderCommonToolbarButton(spec, {
  19706. toolbarButtonBehaviours: [
  19707. Replacing.config({}),
  19708. Toggling.config({
  19709. toggleClass: 'tox-tbtn--enabled',
  19710. aria: { mode: 'pressed' },
  19711. toggleOnExecute: false
  19712. })
  19713. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  19714. getApi: getToggleApi,
  19715. onSetup: spec.onSetup
  19716. }, providersBackstage));
  19717. const fetchChoices = (getApi, spec, providersBackstage) => comp => Future.nu(callback => spec.fetch(callback)).map(items => Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, value => {
  19718. spec.onItemAction(getApi(comp), value);
  19719. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
  19720. movement: deriveMenuMovement(spec.columns, spec.presets),
  19721. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached((comp, _se) => {
  19722. detectSize(comp, 4, classForPreset(spec.presets)).each(({numRows, numColumns}) => {
  19723. Keying.setGridSize(comp, numRows, numColumns);
  19724. });
  19725. })])
  19726. }))));
  19727. const renderSplitButton = (spec, sharedBackstage) => {
  19728. const displayChannel = generate$6('channel-update-split-dropdown-display');
  19729. const getApi = comp => ({
  19730. isEnabled: () => !Disabling.isDisabled(comp),
  19731. setEnabled: state => Disabling.set(comp, !state),
  19732. setIconFill: (id, value) => {
  19733. descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(underlinePath => {
  19734. set$9(underlinePath, 'fill', value);
  19735. });
  19736. },
  19737. setActive: state => {
  19738. set$9(comp.element, 'aria-pressed', state);
  19739. descendant(comp.element, 'span').each(button => {
  19740. comp.getSystem().getByDom(button).each(buttonComp => Toggling.set(buttonComp, state));
  19741. });
  19742. },
  19743. isActive: () => descendant(comp.element, 'span').exists(button => comp.getSystem().getByDom(button).exists(Toggling.isOn))
  19744. });
  19745. const editorOffCell = Cell(noop);
  19746. const specialisation = {
  19747. getApi,
  19748. onSetup: spec.onSetup
  19749. };
  19750. return SplitDropdown.sketch({
  19751. dom: {
  19752. tag: 'div',
  19753. classes: ['tox-split-button'],
  19754. attributes: {
  19755. 'aria-pressed': false,
  19756. ...getTooltipAttributes(spec.tooltip, sharedBackstage.providers)
  19757. }
  19758. },
  19759. onExecute: button => {
  19760. spec.onAction(getApi(button));
  19761. },
  19762. onItemExecute: (_a, _b, _c) => {
  19763. },
  19764. splitDropdownBehaviours: derive$1([
  19765. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  19766. receivingConfig(),
  19767. config('split-dropdown-events', [
  19768. run$1(focusButtonEvent, Focusing.focus),
  19769. onControlAttached(specialisation, editorOffCell),
  19770. onControlDetached(specialisation, editorOffCell)
  19771. ]),
  19772. Unselecting.config({})
  19773. ]),
  19774. eventOrder: {
  19775. [attachedToDom()]: [
  19776. 'alloy.base.behaviour',
  19777. 'split-dropdown-events'
  19778. ]
  19779. },
  19780. toggleClass: 'tox-tbtn--enabled',
  19781. lazySink: sharedBackstage.getSink,
  19782. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  19783. parts: { menu: part(false, spec.columns, spec.presets) },
  19784. components: [
  19785. SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
  19786. toggleClass: 'tox-tbtn--enabled',
  19787. toggleOnExecute: false
  19788. })]), sharedBackstage.providers)),
  19789. SplitDropdown.parts.arrow({
  19790. dom: {
  19791. tag: 'button',
  19792. classes: [
  19793. 'tox-tbtn',
  19794. 'tox-split-button__chevron'
  19795. ],
  19796. innerHtml: get$2('chevron-down', sharedBackstage.providers.icons)
  19797. },
  19798. buttonBehaviours: derive$1([
  19799. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  19800. receivingConfig(),
  19801. addFocusableBehaviour()
  19802. ])
  19803. }),
  19804. SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  19805. ]
  19806. });
  19807. };
  19808. const defaultToolbar = [
  19809. {
  19810. name: 'history',
  19811. items: [
  19812. 'undo',
  19813. 'redo'
  19814. ]
  19815. },
  19816. {
  19817. name: 'styles',
  19818. items: ['styles']
  19819. },
  19820. {
  19821. name: 'formatting',
  19822. items: [
  19823. 'bold',
  19824. 'italic'
  19825. ]
  19826. },
  19827. {
  19828. name: 'alignment',
  19829. items: [
  19830. 'alignleft',
  19831. 'aligncenter',
  19832. 'alignright',
  19833. 'alignjustify'
  19834. ]
  19835. },
  19836. {
  19837. name: 'indentation',
  19838. items: [
  19839. 'outdent',
  19840. 'indent'
  19841. ]
  19842. },
  19843. {
  19844. name: 'permanent pen',
  19845. items: ['permanentpen']
  19846. },
  19847. {
  19848. name: 'comments',
  19849. items: ['addcomment']
  19850. }
  19851. ];
  19852. const renderFromBridge = (bridgeBuilder, render) => (spec, extras, editor) => {
  19853. const internal = bridgeBuilder(spec).mapError(errInfo => formatError(errInfo)).getOrDie();
  19854. return render(internal, extras, editor);
  19855. };
  19856. const types = {
  19857. button: renderFromBridge(createToolbarButton, (s, extras) => renderToolbarButton(s, extras.backstage.shared.providers)),
  19858. togglebutton: renderFromBridge(createToggleButton, (s, extras) => renderToolbarToggleButton(s, extras.backstage.shared.providers)),
  19859. menubutton: renderFromBridge(createMenuButton, (s, extras) => renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none())),
  19860. splitbutton: renderFromBridge(createSplitButton, (s, extras) => renderSplitButton(s, extras.backstage.shared)),
  19861. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, (s, extras, editor) => {
  19862. const buttons = editor.ui.registry.getAll().buttons;
  19863. const identify = toolbar => identifyButtons(editor, {
  19864. buttons,
  19865. toolbar,
  19866. allowToolbarGroups: false
  19867. }, extras, Optional.none());
  19868. const attributes = { [Attribute]: extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop };
  19869. switch (getToolbarMode(editor)) {
  19870. case ToolbarMode$1.floating:
  19871. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  19872. default:
  19873. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  19874. }
  19875. }),
  19876. styleSelectButton: (editor, extras) => createStylesButton(editor, extras.backstage),
  19877. fontsizeSelectButton: (editor, extras) => createFontSizeButton(editor, extras.backstage),
  19878. fontSelectButton: (editor, extras) => createFontFamilyButton(editor, extras.backstage),
  19879. formatButton: (editor, extras) => createBlocksButton(editor, extras.backstage),
  19880. alignMenuButton: (editor, extras) => createAlignButton(editor, extras.backstage)
  19881. };
  19882. const extractFrom = (spec, extras, editor) => get$g(types, spec.type).fold(() => {
  19883. console.error('skipping button defined by', spec);
  19884. return Optional.none();
  19885. }, render => Optional.some(render(spec, extras, editor)));
  19886. const bespokeButtons = {
  19887. styles: types.styleSelectButton,
  19888. fontsize: types.fontsizeSelectButton,
  19889. fontfamily: types.fontSelectButton,
  19890. blocks: types.formatButton,
  19891. align: types.alignMenuButton
  19892. };
  19893. const removeUnusedDefaults = buttons => {
  19894. const filteredItemGroups = map$2(defaultToolbar, group => {
  19895. const items = filter$2(group.items, subItem => has$2(buttons, subItem) || has$2(bespokeButtons, subItem));
  19896. return {
  19897. name: group.name,
  19898. items
  19899. };
  19900. });
  19901. return filter$2(filteredItemGroups, group => group.items.length > 0);
  19902. };
  19903. const convertStringToolbar = strToolbar => {
  19904. const groupsStrings = strToolbar.split('|');
  19905. return map$2(groupsStrings, g => ({ items: g.trim().split(' ') }));
  19906. };
  19907. const isToolbarGroupSettingArray = toolbar => isArrayOf(toolbar, t => has$2(t, 'name') && has$2(t, 'items'));
  19908. const createToolbar = toolbarConfig => {
  19909. const toolbar = toolbarConfig.toolbar;
  19910. const buttons = toolbarConfig.buttons;
  19911. if (toolbar === false) {
  19912. return [];
  19913. } else if (toolbar === undefined || toolbar === true) {
  19914. return removeUnusedDefaults(buttons);
  19915. } else if (isString(toolbar)) {
  19916. return convertStringToolbar(toolbar);
  19917. } else if (isToolbarGroupSettingArray(toolbar)) {
  19918. return toolbar;
  19919. } else {
  19920. console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  19921. return [];
  19922. }
  19923. };
  19924. const lookupButton = (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) => get$g(buttons, toolbarItem.toLowerCase()).orThunk(() => prefixes.bind(ps => findMap(ps, prefix => get$g(buttons, prefix + toolbarItem.toLowerCase())))).fold(() => get$g(bespokeButtons, toolbarItem.toLowerCase()).map(r => r(editor, extras)).orThunk(() => Optional.none()), spec => {
  19925. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  19926. console.warn(`Ignoring the '${ toolbarItem }' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.`);
  19927. return Optional.none();
  19928. } else {
  19929. return extractFrom(spec, extras, editor);
  19930. }
  19931. });
  19932. const identifyButtons = (editor, toolbarConfig, extras, prefixes) => {
  19933. const toolbarGroups = createToolbar(toolbarConfig);
  19934. const groups = map$2(toolbarGroups, group => {
  19935. const items = bind$3(group.items, toolbarItem => toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray());
  19936. return {
  19937. title: Optional.from(editor.translate(group.name)),
  19938. items
  19939. };
  19940. });
  19941. return filter$2(groups, group => group.items.length > 0);
  19942. };
  19943. const setToolbar = (editor, uiComponents, rawUiConfig, backstage) => {
  19944. const comp = uiComponents.outerContainer;
  19945. const toolbarConfig = rawUiConfig.toolbar;
  19946. const toolbarButtonsConfig = rawUiConfig.buttons;
  19947. if (isArrayOf(toolbarConfig, isString)) {
  19948. const toolbars = toolbarConfig.map(t => {
  19949. const config = {
  19950. toolbar: t,
  19951. buttons: toolbarButtonsConfig,
  19952. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  19953. };
  19954. return identifyButtons(editor, config, { backstage }, Optional.none());
  19955. });
  19956. OuterContainer.setToolbars(comp, toolbars);
  19957. } else {
  19958. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage }, Optional.none()));
  19959. }
  19960. };
  19961. const detection = detect$1();
  19962. const isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  19963. const setupEvents$1 = (editor, uiComponents) => {
  19964. const dom = editor.dom;
  19965. let contentWindow = editor.getWin();
  19966. const initialDocEle = editor.getDoc().documentElement;
  19967. const lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  19968. const lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  19969. const resizeWindow = () => {
  19970. const outer = lastWindowDimensions.get();
  19971. if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
  19972. lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  19973. fireResizeContent(editor);
  19974. }
  19975. };
  19976. const resizeDocument = () => {
  19977. const docEle = editor.getDoc().documentElement;
  19978. const inner = lastDocumentDimensions.get();
  19979. if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
  19980. lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
  19981. fireResizeContent(editor);
  19982. }
  19983. };
  19984. const scroll = e => fireScrollContent(editor, e);
  19985. dom.bind(contentWindow, 'resize', resizeWindow);
  19986. dom.bind(contentWindow, 'scroll', scroll);
  19987. const elementLoad = capture(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
  19988. const mothership = uiComponents.uiMothership.element;
  19989. editor.on('hide', () => {
  19990. set$8(mothership, 'display', 'none');
  19991. });
  19992. editor.on('show', () => {
  19993. remove$6(mothership, 'display');
  19994. });
  19995. editor.on('NodeChange', resizeDocument);
  19996. editor.on('remove', () => {
  19997. elementLoad.unbind();
  19998. dom.unbind(contentWindow, 'resize', resizeWindow);
  19999. dom.unbind(contentWindow, 'scroll', scroll);
  20000. contentWindow = null;
  20001. });
  20002. };
  20003. const render$1 = (editor, uiComponents, rawUiConfig, backstage, args) => {
  20004. const lastToolbarWidth = Cell(0);
  20005. const outerContainer = uiComponents.outerContainer;
  20006. iframe(editor);
  20007. const eTargetNode = SugarElement.fromDom(args.targetNode);
  20008. const uiRoot = getContentContainer(getRootNode(eTargetNode));
  20009. attachSystemAfter(eTargetNode, uiComponents.mothership);
  20010. attachSystem(uiRoot, uiComponents.uiMothership);
  20011. editor.on('PostRender', () => {
  20012. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  20013. lastToolbarWidth.set(editor.getWin().innerWidth);
  20014. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  20015. OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
  20016. setupEvents$1(editor, uiComponents);
  20017. });
  20018. const socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
  20019. if (isiOS12) {
  20020. setAll(socket.element, {
  20021. 'overflow': 'scroll',
  20022. '-webkit-overflow-scrolling': 'touch'
  20023. });
  20024. const limit = first(() => {
  20025. editor.dispatch('ScrollContent');
  20026. }, 20);
  20027. const unbinder = bind(socket.element, 'scroll', limit.throttle);
  20028. editor.on('remove', unbinder.unbind);
  20029. }
  20030. setupReadonlyModeSwitch(editor, uiComponents);
  20031. editor.addCommand('ToggleSidebar', (_ui, value) => {
  20032. OuterContainer.toggleSidebar(outerContainer, value);
  20033. editor.dispatch('ToggleSidebar');
  20034. });
  20035. editor.addQueryValueHandler('ToggleSidebar', () => OuterContainer.whichSidebar(outerContainer));
  20036. const toolbarMode = getToolbarMode(editor);
  20037. const refreshDrawer = () => {
  20038. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  20039. };
  20040. if (toolbarMode === ToolbarMode$1.sliding || toolbarMode === ToolbarMode$1.floating) {
  20041. editor.on('ResizeWindow ResizeEditor ResizeContent', () => {
  20042. const width = editor.getWin().innerWidth;
  20043. if (width !== lastToolbarWidth.get()) {
  20044. refreshDrawer();
  20045. lastToolbarWidth.set(width);
  20046. }
  20047. });
  20048. }
  20049. const api = {
  20050. setEnabled: state => {
  20051. broadcastReadonly(uiComponents, !state);
  20052. },
  20053. isEnabled: () => !Disabling.isDisabled(outerContainer)
  20054. };
  20055. return {
  20056. iframeContainer: socket.element.dom,
  20057. editorContainer: outerContainer.element.dom,
  20058. api
  20059. };
  20060. };
  20061. var Iframe = /*#__PURE__*/Object.freeze({
  20062. __proto__: null,
  20063. render: render$1
  20064. });
  20065. const parseToInt = val => {
  20066. const re = /^[0-9\.]+(|px)$/i;
  20067. if (re.test('' + val)) {
  20068. return Optional.some(parseInt('' + val, 10));
  20069. }
  20070. return Optional.none();
  20071. };
  20072. const numToPx = val => isNumber(val) ? val + 'px' : val;
  20073. const calcCappedSize = (size, minSize, maxSize) => {
  20074. const minOverride = minSize.filter(min => size < min);
  20075. const maxOverride = maxSize.filter(max => size > max);
  20076. return minOverride.or(maxOverride).getOr(size);
  20077. };
  20078. const getHeight = editor => {
  20079. const baseHeight = getHeightOption(editor);
  20080. const minHeight = getMinHeightOption(editor);
  20081. const maxHeight = getMaxHeightOption(editor);
  20082. return parseToInt(baseHeight).map(height => calcCappedSize(height, minHeight, maxHeight));
  20083. };
  20084. const getHeightWithFallback = editor => {
  20085. const height = getHeight(editor);
  20086. return height.getOr(getHeightOption(editor));
  20087. };
  20088. const getWidth = editor => {
  20089. const baseWidth = getWidthOption(editor);
  20090. const minWidth = getMinWidthOption(editor);
  20091. const maxWidth = getMaxWidthOption(editor);
  20092. return parseToInt(baseWidth).map(width => calcCappedSize(width, minWidth, maxWidth));
  20093. };
  20094. const getWidthWithFallback = editor => {
  20095. const width = getWidth(editor);
  20096. return width.getOr(getWidthOption(editor));
  20097. };
  20098. const {ToolbarLocation, ToolbarMode} = Options;
  20099. const InlineHeader = (editor, targetElm, uiComponents, backstage, floatContainer) => {
  20100. const {uiMothership, outerContainer} = uiComponents;
  20101. const DOM = global$7.DOM;
  20102. const useFixedToolbarContainer = useFixedContainer(editor);
  20103. const isSticky = isStickyToolbar(editor);
  20104. const editorMaxWidthOpt = getMaxWidthOption(editor).or(getWidth(editor));
  20105. const headerBackstage = backstage.shared.header;
  20106. const isPositionedAtTop = headerBackstage.isPositionedAtTop;
  20107. const toolbarMode = getToolbarMode(editor);
  20108. const isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  20109. const visible = Cell(false);
  20110. const isVisible = () => visible.get() && !editor.removed;
  20111. const calcToolbarOffset = toolbar => isSplitToolbar ? toolbar.fold(constant$1(0), tbar => tbar.components().length > 1 ? get$d(tbar.components()[1].element) : 0) : 0;
  20112. const calcMode = container => {
  20113. switch (getToolbarLocation(editor)) {
  20114. case ToolbarLocation.auto:
  20115. const toolbar = OuterContainer.getToolbar(outerContainer);
  20116. const offset = calcToolbarOffset(toolbar);
  20117. const toolbarHeight = get$d(container.element) - offset;
  20118. const targetBounds = box$1(targetElm);
  20119. const roomAtTop = targetBounds.y > toolbarHeight;
  20120. if (roomAtTop) {
  20121. return 'top';
  20122. } else {
  20123. const doc = documentElement(targetElm);
  20124. const docHeight = Math.max(doc.dom.scrollHeight, get$d(doc));
  20125. const roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  20126. if (roomAtBottom) {
  20127. return 'bottom';
  20128. } else {
  20129. const winBounds = win();
  20130. const isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  20131. return isRoomAtBottomViewport ? 'bottom' : 'top';
  20132. }
  20133. }
  20134. case ToolbarLocation.bottom:
  20135. return 'bottom';
  20136. case ToolbarLocation.top:
  20137. default:
  20138. return 'top';
  20139. }
  20140. };
  20141. const setupMode = mode => {
  20142. const container = floatContainer.get();
  20143. Docking.setModes(container, [mode]);
  20144. headerBackstage.setDockingMode(mode);
  20145. const verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  20146. set$9(container.element, Attribute, verticalDir);
  20147. };
  20148. const updateChromeWidth = () => {
  20149. const maxWidth = editorMaxWidthOpt.getOrThunk(() => {
  20150. const bodyMargin = parseToInt(get$e(body(), 'margin-left')).getOr(0);
  20151. return get$c(body()) - absolute$3(targetElm).left + bodyMargin;
  20152. });
  20153. set$8(floatContainer.get().element, 'max-width', maxWidth + 'px');
  20154. };
  20155. const updateChromePosition = () => {
  20156. const toolbar = OuterContainer.getToolbar(outerContainer);
  20157. const offset = calcToolbarOffset(toolbar);
  20158. const targetBounds = box$1(targetElm);
  20159. const top = isPositionedAtTop() ? Math.max(targetBounds.y - get$d(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
  20160. setAll(outerContainer.element, {
  20161. position: 'absolute',
  20162. top: Math.round(top) + 'px',
  20163. left: Math.round(targetBounds.x) + 'px'
  20164. });
  20165. };
  20166. const repositionPopups$1 = () => {
  20167. uiMothership.broadcastOn([repositionPopups()], {});
  20168. };
  20169. const updateChromeUi = (resetDocking = false) => {
  20170. if (!isVisible()) {
  20171. return;
  20172. }
  20173. if (!useFixedToolbarContainer) {
  20174. updateChromeWidth();
  20175. }
  20176. if (isSplitToolbar) {
  20177. OuterContainer.refreshToolbar(outerContainer);
  20178. }
  20179. if (!useFixedToolbarContainer) {
  20180. updateChromePosition();
  20181. }
  20182. if (isSticky) {
  20183. const floatContainerComp = floatContainer.get();
  20184. resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  20185. }
  20186. repositionPopups$1();
  20187. };
  20188. const updateMode = (updateUi = true) => {
  20189. if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  20190. return;
  20191. }
  20192. const currentMode = headerBackstage.getDockingMode();
  20193. const newMode = calcMode(floatContainer.get());
  20194. if (newMode !== currentMode) {
  20195. setupMode(newMode);
  20196. if (updateUi) {
  20197. updateChromeUi(true);
  20198. }
  20199. }
  20200. };
  20201. const show = () => {
  20202. visible.set(true);
  20203. set$8(outerContainer.element, 'display', 'flex');
  20204. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  20205. remove$6(uiMothership.element, 'display');
  20206. updateMode(false);
  20207. updateChromeUi();
  20208. };
  20209. const hide = () => {
  20210. visible.set(false);
  20211. if (uiComponents.outerContainer) {
  20212. set$8(outerContainer.element, 'display', 'none');
  20213. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  20214. }
  20215. set$8(uiMothership.element, 'display', 'none');
  20216. };
  20217. return {
  20218. isVisible,
  20219. isPositionedAtTop,
  20220. show,
  20221. hide,
  20222. update: updateChromeUi,
  20223. updateMode,
  20224. repositionPopups: repositionPopups$1
  20225. };
  20226. };
  20227. const getTargetPosAndBounds = (targetElm, isToolbarTop) => {
  20228. const bounds = box$1(targetElm);
  20229. return {
  20230. pos: isToolbarTop ? bounds.y : bounds.bottom,
  20231. bounds
  20232. };
  20233. };
  20234. const setupEvents = (editor, targetElm, ui, toolbarPersist) => {
  20235. const prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  20236. const resizeContent = e => {
  20237. const {pos, bounds} = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop());
  20238. const {
  20239. pos: prevPos,
  20240. bounds: prevBounds
  20241. } = prevPosAndBounds.get();
  20242. const hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  20243. prevPosAndBounds.set({
  20244. pos,
  20245. bounds
  20246. });
  20247. if (hasResized) {
  20248. fireResizeContent(editor, e);
  20249. }
  20250. if (ui.isVisible()) {
  20251. if (prevPos !== pos) {
  20252. ui.update(true);
  20253. } else if (hasResized) {
  20254. ui.updateMode();
  20255. ui.repositionPopups();
  20256. }
  20257. }
  20258. };
  20259. if (!toolbarPersist) {
  20260. editor.on('activate', ui.show);
  20261. editor.on('deactivate', ui.hide);
  20262. }
  20263. editor.on('SkinLoaded ResizeWindow', () => ui.update(true));
  20264. editor.on('NodeChange keydown', e => {
  20265. requestAnimationFrame(() => resizeContent(e));
  20266. });
  20267. editor.on('ScrollWindow', () => ui.updateMode());
  20268. const elementLoad = unbindable();
  20269. elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
  20270. editor.on('remove', () => {
  20271. elementLoad.clear();
  20272. });
  20273. };
  20274. const render = (editor, uiComponents, rawUiConfig, backstage, args) => {
  20275. const {mothership, uiMothership, outerContainer} = uiComponents;
  20276. const floatContainer = Cell(null);
  20277. const targetElm = SugarElement.fromDom(args.targetNode);
  20278. const ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  20279. const toolbarPersist = isToolbarPersist(editor);
  20280. inline(editor);
  20281. const render = () => {
  20282. if (floatContainer.get()) {
  20283. ui.show();
  20284. return;
  20285. }
  20286. floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  20287. const uiContainer = getUiContainer(editor);
  20288. attachSystem(uiContainer, mothership);
  20289. attachSystem(uiContainer, uiMothership);
  20290. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  20291. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  20292. ui.show();
  20293. setupEvents(editor, targetElm, ui, toolbarPersist);
  20294. editor.nodeChanged();
  20295. };
  20296. editor.on('show', render);
  20297. editor.on('hide', ui.hide);
  20298. if (!toolbarPersist) {
  20299. editor.on('focus', render);
  20300. editor.on('blur', ui.hide);
  20301. }
  20302. editor.on('init', () => {
  20303. if (editor.hasFocus() || toolbarPersist) {
  20304. render();
  20305. }
  20306. });
  20307. setupReadonlyModeSwitch(editor, uiComponents);
  20308. const api = {
  20309. show: () => {
  20310. render();
  20311. },
  20312. hide: () => {
  20313. ui.hide();
  20314. },
  20315. setEnabled: state => {
  20316. broadcastReadonly(uiComponents, !state);
  20317. },
  20318. isEnabled: () => !Disabling.isDisabled(outerContainer)
  20319. };
  20320. return {
  20321. editorContainer: outerContainer.element.dom,
  20322. api
  20323. };
  20324. };
  20325. var Inline = /*#__PURE__*/Object.freeze({
  20326. __proto__: null,
  20327. render: render
  20328. });
  20329. const showContextToolbarEvent = 'contexttoolbar-show';
  20330. const hideContextToolbarEvent = 'contexttoolbar-hide';
  20331. const getFormApi = input => ({
  20332. hide: () => emit(input, sandboxClose()),
  20333. getValue: () => Representing.getValue(input)
  20334. });
  20335. const runOnExecute = (memInput, original) => run$1(internalToolbarButtonExecute, (comp, se) => {
  20336. const input = memInput.get(comp);
  20337. const formApi = getFormApi(input);
  20338. original.onAction(formApi, se.event.buttonApi);
  20339. });
  20340. const renderContextButton = (memInput, button, extras) => {
  20341. const {primary, ...rest} = button.original;
  20342. const bridged = getOrDie(createToolbarButton({
  20343. ...rest,
  20344. type: 'button',
  20345. onAction: noop
  20346. }));
  20347. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  20348. };
  20349. const renderContextToggleButton = (memInput, button, extras) => {
  20350. const {primary, ...rest} = button.original;
  20351. const bridged = getOrDie(createToggleButton({
  20352. ...rest,
  20353. type: 'togglebutton',
  20354. onAction: noop
  20355. }));
  20356. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  20357. };
  20358. const generateOne = (memInput, button, providersBackstage) => {
  20359. const extras = { backstage: { shared: { providers: providersBackstage } } };
  20360. if (button.type === 'contextformtogglebutton') {
  20361. return renderContextToggleButton(memInput, button, extras);
  20362. } else {
  20363. return renderContextButton(memInput, button, extras);
  20364. }
  20365. };
  20366. const generate = (memInput, buttons, providersBackstage) => {
  20367. const mementos = map$2(buttons, button => record(generateOne(memInput, button, providersBackstage)));
  20368. const asSpecs = () => map$2(mementos, mem => mem.asSpec());
  20369. const findPrimary = compInSystem => findMap(buttons, (button, i) => {
  20370. if (button.primary) {
  20371. return Optional.from(mementos[i]).bind(mem => mem.getOpt(compInSystem)).filter(not(Disabling.isDisabled));
  20372. } else {
  20373. return Optional.none();
  20374. }
  20375. });
  20376. return {
  20377. asSpecs,
  20378. findPrimary
  20379. };
  20380. };
  20381. const buildInitGroups = (ctx, providers) => {
  20382. const inputAttributes = ctx.label.fold(() => ({}), label => ({ 'aria-label': label }));
  20383. const memInput = record(Input.sketch({
  20384. inputClasses: [
  20385. 'tox-toolbar-textfield',
  20386. 'tox-toolbar-nav-js'
  20387. ],
  20388. data: ctx.initValue(),
  20389. inputAttributes,
  20390. selectOnFocus: true,
  20391. inputBehaviours: derive$1([Keying.config({
  20392. mode: 'special',
  20393. onEnter: input => commands.findPrimary(input).map(primary => {
  20394. emitExecute(primary);
  20395. return true;
  20396. }),
  20397. onLeft: (comp, se) => {
  20398. se.cut();
  20399. return Optional.none();
  20400. },
  20401. onRight: (comp, se) => {
  20402. se.cut();
  20403. return Optional.none();
  20404. }
  20405. })])
  20406. }));
  20407. const commands = generate(memInput, ctx.commands, providers);
  20408. return [
  20409. {
  20410. title: Optional.none(),
  20411. items: [memInput.asSpec()]
  20412. },
  20413. {
  20414. title: Optional.none(),
  20415. items: commands.asSpecs()
  20416. }
  20417. ];
  20418. };
  20419. const renderContextForm = (toolbarType, ctx, providers) => renderToolbar({
  20420. type: toolbarType,
  20421. uid: generate$6('context-toolbar'),
  20422. initGroups: buildInitGroups(ctx, providers),
  20423. onEscape: Optional.none,
  20424. cyclicKeying: true,
  20425. providers
  20426. });
  20427. const ContextForm = {
  20428. renderContextForm,
  20429. buildInitGroups
  20430. };
  20431. const isVerticalOverlap = (a, b, threshold = 0.01) => b.bottom - a.y >= threshold && a.bottom - b.y >= threshold;
  20432. const getRangeRect = rng => {
  20433. const rect = rng.getBoundingClientRect();
  20434. if (rect.height <= 0 && rect.width <= 0) {
  20435. const leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
  20436. const elm = isText(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
  20437. return elm.filter(isElement$1).map(e => e.dom.getBoundingClientRect()).getOr(rect);
  20438. } else {
  20439. return rect;
  20440. }
  20441. };
  20442. const getSelectionBounds = editor => {
  20443. const rng = editor.selection.getRng();
  20444. const rect = getRangeRect(rng);
  20445. if (editor.inline) {
  20446. const scroll = get$b();
  20447. return bounds(scroll.left + rect.left, scroll.top + rect.top, rect.width, rect.height);
  20448. } else {
  20449. const bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
  20450. return bounds(bodyPos.x + rect.left, bodyPos.y + rect.top, rect.width, rect.height);
  20451. }
  20452. };
  20453. const getAnchorElementBounds = (editor, lastElement) => lastElement.filter(inBody).map(absolute$2).getOrThunk(() => getSelectionBounds(editor));
  20454. const getHorizontalBounds = (contentAreaBox, viewportBounds, margin) => {
  20455. const x = Math.max(contentAreaBox.x + margin, viewportBounds.x);
  20456. const right = Math.min(contentAreaBox.right - margin, viewportBounds.right);
  20457. return {
  20458. x,
  20459. width: right - x
  20460. };
  20461. };
  20462. const getVerticalBounds = (editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) => {
  20463. const container = SugarElement.fromDom(editor.getContainer());
  20464. const header = descendant(container, '.tox-editor-header').getOr(container);
  20465. const headerBox = box$1(header);
  20466. const isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  20467. const isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  20468. if (editor.inline && isToolbarAbove) {
  20469. return {
  20470. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  20471. bottom: viewportBounds.bottom
  20472. };
  20473. }
  20474. if (editor.inline && !isToolbarAbove) {
  20475. return {
  20476. y: viewportBounds.y,
  20477. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  20478. };
  20479. }
  20480. const containerBounds = toolbarType === 'line' ? box$1(container) : contentAreaBox;
  20481. if (isToolbarAbove) {
  20482. return {
  20483. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  20484. bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
  20485. };
  20486. }
  20487. return {
  20488. y: Math.max(containerBounds.y + margin, viewportBounds.y),
  20489. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  20490. };
  20491. };
  20492. const getContextToolbarBounds = (editor, sharedBackstage, toolbarType, margin = 0) => {
  20493. const viewportBounds = getBounds$3(window);
  20494. const contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  20495. const toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  20496. const {x, width} = getHorizontalBounds(contentAreaBox, viewportBounds, margin);
  20497. if (editor.inline && !toolbarOrMenubarEnabled) {
  20498. return bounds(x, viewportBounds.y, width, viewportBounds.height);
  20499. } else {
  20500. const isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  20501. const {y, bottom} = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin);
  20502. return bounds(x, y, width, bottom - y);
  20503. }
  20504. };
  20505. const bubbleSize$1 = 12;
  20506. const bubbleAlignments$1 = {
  20507. valignCentre: [],
  20508. alignCentre: [],
  20509. alignLeft: ['tox-pop--align-left'],
  20510. alignRight: ['tox-pop--align-right'],
  20511. right: ['tox-pop--right'],
  20512. left: ['tox-pop--left'],
  20513. bottom: ['tox-pop--bottom'],
  20514. top: ['tox-pop--top'],
  20515. inset: ['tox-pop--inset']
  20516. };
  20517. const anchorOverrides = {
  20518. maxHeightFunction: expandable$1(),
  20519. maxWidthFunction: expandable()
  20520. };
  20521. const isEntireElementSelected = (editor, elem) => {
  20522. const rng = editor.selection.getRng();
  20523. const leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  20524. return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem);
  20525. };
  20526. const preservePosition = (elem, position, f) => {
  20527. const currentPosition = getRaw(elem, 'position');
  20528. set$8(elem, 'position', position);
  20529. const result = f(elem);
  20530. currentPosition.each(pos => set$8(elem, 'position', pos));
  20531. return result;
  20532. };
  20533. const shouldUseInsetLayouts = position => position === 'node';
  20534. const determineInsetLayout = (editor, contextbar, elem, data, bounds) => {
  20535. const selectionBounds = getSelectionBounds(editor);
  20536. const isSameAnchorElement = data.lastElement().exists(prev => eq(elem, prev));
  20537. if (isEntireElementSelected(editor, elem)) {
  20538. return isSameAnchorElement ? preserve : north;
  20539. } else if (isSameAnchorElement) {
  20540. return preservePosition(contextbar, data.getMode(), () => {
  20541. const isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
  20542. return isOverlapping && !data.isReposition() ? flip : preserve;
  20543. });
  20544. } else {
  20545. const yBounds = data.getMode() === 'fixed' ? bounds.y + get$b().top : bounds.y;
  20546. const contextbarHeight = get$d(contextbar) + bubbleSize$1;
  20547. return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
  20548. }
  20549. };
  20550. const getAnchorSpec$2 = (editor, mobile, data, position) => {
  20551. const smartInsetLayout = elem => (anchor, element, bubbles, placee, bounds) => {
  20552. const layout = determineInsetLayout(editor, placee, elem, data, bounds);
  20553. const newAnchor = {
  20554. ...anchor,
  20555. y: bounds.y,
  20556. height: bounds.height
  20557. };
  20558. return {
  20559. ...layout(newAnchor, element, bubbles, placee, bounds),
  20560. alwaysFit: true
  20561. };
  20562. };
  20563. const getInsetLayouts = elem => shouldUseInsetLayouts(position) ? [smartInsetLayout(elem)] : [];
  20564. const desktopAnchorSpecLayouts = {
  20565. onLtr: elem => [
  20566. north$2,
  20567. south$2,
  20568. northeast$2,
  20569. southeast$2,
  20570. northwest$2,
  20571. southwest$2
  20572. ].concat(getInsetLayouts(elem)),
  20573. onRtl: elem => [
  20574. north$2,
  20575. south$2,
  20576. northwest$2,
  20577. southwest$2,
  20578. northeast$2,
  20579. southeast$2
  20580. ].concat(getInsetLayouts(elem))
  20581. };
  20582. const mobileAnchorSpecLayouts = {
  20583. onLtr: elem => [
  20584. south$2,
  20585. southeast$2,
  20586. southwest$2,
  20587. northeast$2,
  20588. northwest$2,
  20589. north$2
  20590. ].concat(getInsetLayouts(elem)),
  20591. onRtl: elem => [
  20592. south$2,
  20593. southwest$2,
  20594. southeast$2,
  20595. northwest$2,
  20596. northeast$2,
  20597. north$2
  20598. ].concat(getInsetLayouts(elem))
  20599. };
  20600. return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
  20601. };
  20602. const getAnchorLayout = (editor, position, isTouch, data) => {
  20603. if (position === 'line') {
  20604. return {
  20605. bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
  20606. layouts: {
  20607. onLtr: () => [east$2],
  20608. onRtl: () => [west$2]
  20609. },
  20610. overrides: anchorOverrides
  20611. };
  20612. } else {
  20613. return {
  20614. bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
  20615. layouts: getAnchorSpec$2(editor, isTouch, data, position),
  20616. overrides: anchorOverrides
  20617. };
  20618. }
  20619. };
  20620. const matchTargetWith = (elem, candidates) => {
  20621. const ctxs = filter$2(candidates, toolbarApi => toolbarApi.predicate(elem.dom));
  20622. const {pass, fail} = partition$3(ctxs, t => t.type === 'contexttoolbar');
  20623. return {
  20624. contextToolbars: pass,
  20625. contextForms: fail
  20626. };
  20627. };
  20628. const filterByPositionForStartNode = toolbars => {
  20629. if (toolbars.length <= 1) {
  20630. return toolbars;
  20631. } else {
  20632. const doesPositionExist = value => exists(toolbars, t => t.position === value);
  20633. const filterToolbarsByPosition = value => filter$2(toolbars, t => t.position === value);
  20634. const hasSelectionToolbars = doesPositionExist('selection');
  20635. const hasNodeToolbars = doesPositionExist('node');
  20636. if (hasSelectionToolbars || hasNodeToolbars) {
  20637. if (hasNodeToolbars && hasSelectionToolbars) {
  20638. const nodeToolbars = filterToolbarsByPosition('node');
  20639. const selectionToolbars = map$2(filterToolbarsByPosition('selection'), t => ({
  20640. ...t,
  20641. position: 'node'
  20642. }));
  20643. return nodeToolbars.concat(selectionToolbars);
  20644. } else {
  20645. return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  20646. }
  20647. } else {
  20648. return filterToolbarsByPosition('line');
  20649. }
  20650. }
  20651. };
  20652. const filterByPositionForAncestorNode = toolbars => {
  20653. if (toolbars.length <= 1) {
  20654. return toolbars;
  20655. } else {
  20656. const findPosition = value => find$5(toolbars, t => t.position === value);
  20657. const basePosition = findPosition('selection').orThunk(() => findPosition('node')).orThunk(() => findPosition('line')).map(t => t.position);
  20658. return basePosition.fold(() => [], pos => filter$2(toolbars, t => t.position === pos));
  20659. }
  20660. };
  20661. const matchStartNode = (elem, nodeCandidates, editorCandidates) => {
  20662. const nodeMatches = matchTargetWith(elem, nodeCandidates);
  20663. if (nodeMatches.contextForms.length > 0) {
  20664. return Optional.some({
  20665. elem,
  20666. toolbars: [nodeMatches.contextForms[0]]
  20667. });
  20668. } else {
  20669. const editorMatches = matchTargetWith(elem, editorCandidates);
  20670. if (editorMatches.contextForms.length > 0) {
  20671. return Optional.some({
  20672. elem,
  20673. toolbars: [editorMatches.contextForms[0]]
  20674. });
  20675. } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  20676. const toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  20677. return Optional.some({
  20678. elem,
  20679. toolbars
  20680. });
  20681. } else {
  20682. return Optional.none();
  20683. }
  20684. }
  20685. };
  20686. const matchAncestor = (isRoot, startNode, scopes) => {
  20687. if (isRoot(startNode)) {
  20688. return Optional.none();
  20689. } else {
  20690. return ancestor$2(startNode, ancestorElem => {
  20691. if (isElement$1(ancestorElem)) {
  20692. const {contextToolbars, contextForms} = matchTargetWith(ancestorElem, scopes.inNodeScope);
  20693. const toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  20694. return toolbars.length > 0 ? Optional.some({
  20695. elem: ancestorElem,
  20696. toolbars
  20697. }) : Optional.none();
  20698. } else {
  20699. return Optional.none();
  20700. }
  20701. }, isRoot);
  20702. }
  20703. };
  20704. const lookup$1 = (scopes, editor) => {
  20705. const rootElem = SugarElement.fromDom(editor.getBody());
  20706. const isRoot = elem => eq(elem, rootElem);
  20707. const isOutsideRoot = startNode => !isRoot(startNode) && !contains(rootElem, startNode);
  20708. const startNode = SugarElement.fromDom(editor.selection.getNode());
  20709. if (isOutsideRoot(startNode)) {
  20710. return Optional.none();
  20711. }
  20712. return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(() => matchAncestor(isRoot, startNode, scopes));
  20713. };
  20714. const categorise = (contextToolbars, navigate) => {
  20715. const forms = {};
  20716. const inNodeScope = [];
  20717. const inEditorScope = [];
  20718. const formNavigators = {};
  20719. const lookupTable = {};
  20720. const registerForm = (key, toolbarSpec) => {
  20721. const contextForm = getOrDie(createContextForm(toolbarSpec));
  20722. forms[key] = contextForm;
  20723. contextForm.launch.map(launch => {
  20724. formNavigators['form:' + key + ''] = {
  20725. ...toolbarSpec.launch,
  20726. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  20727. onAction: () => {
  20728. navigate(contextForm);
  20729. }
  20730. };
  20731. });
  20732. if (contextForm.scope === 'editor') {
  20733. inEditorScope.push(contextForm);
  20734. } else {
  20735. inNodeScope.push(contextForm);
  20736. }
  20737. lookupTable[key] = contextForm;
  20738. };
  20739. const registerToolbar = (key, toolbarSpec) => {
  20740. createContextToolbar(toolbarSpec).each(contextToolbar => {
  20741. if (toolbarSpec.scope === 'editor') {
  20742. inEditorScope.push(contextToolbar);
  20743. } else {
  20744. inNodeScope.push(contextToolbar);
  20745. }
  20746. lookupTable[key] = contextToolbar;
  20747. });
  20748. };
  20749. const keys$1 = keys(contextToolbars);
  20750. each$1(keys$1, key => {
  20751. const toolbarApi = contextToolbars[key];
  20752. if (toolbarApi.type === 'contextform') {
  20753. registerForm(key, toolbarApi);
  20754. } else if (toolbarApi.type === 'contexttoolbar') {
  20755. registerToolbar(key, toolbarApi);
  20756. }
  20757. });
  20758. return {
  20759. forms,
  20760. inNodeScope,
  20761. inEditorScope,
  20762. lookupTable,
  20763. formNavigators
  20764. };
  20765. };
  20766. const forwardSlideEvent = generate$6('forward-slide');
  20767. const backSlideEvent = generate$6('backward-slide');
  20768. const changeSlideEvent = generate$6('change-slide-event');
  20769. const resizingClass = 'tox-pop--resizing';
  20770. const renderContextToolbar = spec => {
  20771. const stack = Cell([]);
  20772. return InlineView.sketch({
  20773. dom: {
  20774. tag: 'div',
  20775. classes: ['tox-pop']
  20776. },
  20777. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  20778. onShow: comp => {
  20779. stack.set([]);
  20780. InlineView.getContent(comp).each(c => {
  20781. remove$6(c.element, 'visibility');
  20782. });
  20783. remove$2(comp.element, resizingClass);
  20784. remove$6(comp.element, 'width');
  20785. },
  20786. inlineBehaviours: derive$1([
  20787. config('context-toolbar-events', [
  20788. runOnSource(transitionend(), (comp, se) => {
  20789. if (se.event.raw.propertyName === 'width') {
  20790. remove$2(comp.element, resizingClass);
  20791. remove$6(comp.element, 'width');
  20792. }
  20793. }),
  20794. run$1(changeSlideEvent, (comp, se) => {
  20795. const elem = comp.element;
  20796. remove$6(elem, 'width');
  20797. const currentWidth = get$c(elem);
  20798. InlineView.setContent(comp, se.event.contents);
  20799. add$2(elem, resizingClass);
  20800. const newWidth = get$c(elem);
  20801. set$8(elem, 'width', currentWidth + 'px');
  20802. InlineView.getContent(comp).each(newContents => {
  20803. se.event.focus.bind(f => {
  20804. focus$3(f);
  20805. return search(elem);
  20806. }).orThunk(() => {
  20807. Keying.focusIn(newContents);
  20808. return active$1(getRootNode(elem));
  20809. });
  20810. });
  20811. setTimeout(() => {
  20812. set$8(comp.element, 'width', newWidth + 'px');
  20813. }, 0);
  20814. }),
  20815. run$1(forwardSlideEvent, (comp, se) => {
  20816. InlineView.getContent(comp).each(oldContents => {
  20817. stack.set(stack.get().concat([{
  20818. bar: oldContents,
  20819. focus: active$1(getRootNode(comp.element))
  20820. }]));
  20821. });
  20822. emitWith(comp, changeSlideEvent, {
  20823. contents: se.event.forwardContents,
  20824. focus: Optional.none()
  20825. });
  20826. }),
  20827. run$1(backSlideEvent, (comp, _se) => {
  20828. last$1(stack.get()).each(last => {
  20829. stack.set(stack.get().slice(0, stack.get().length - 1));
  20830. emitWith(comp, changeSlideEvent, {
  20831. contents: premade(last.bar),
  20832. focus: last.focus
  20833. });
  20834. });
  20835. })
  20836. ]),
  20837. Keying.config({
  20838. mode: 'special',
  20839. onEscape: comp => last$1(stack.get()).fold(() => spec.onEscape(), _ => {
  20840. emit(comp, backSlideEvent);
  20841. return Optional.some(true);
  20842. })
  20843. })
  20844. ]),
  20845. lazySink: () => Result.value(spec.sink)
  20846. });
  20847. };
  20848. const transitionClass = 'tox-pop--transition';
  20849. const register$9 = (editor, registryContextToolbars, sink, extras) => {
  20850. const backstage = extras.backstage;
  20851. const sharedBackstage = backstage.shared;
  20852. const isTouch = detect$1().deviceType.isTouch;
  20853. const lastElement = value$2();
  20854. const lastTrigger = value$2();
  20855. const lastContextPosition = value$2();
  20856. const contextbar = build$1(renderContextToolbar({
  20857. sink,
  20858. onEscape: () => {
  20859. editor.focus();
  20860. return Optional.some(true);
  20861. }
  20862. }));
  20863. const getBounds = () => {
  20864. const position = lastContextPosition.get().getOr('node');
  20865. const margin = shouldUseInsetLayouts(position) ? 1 : 0;
  20866. return getContextToolbarBounds(editor, sharedBackstage, position, margin);
  20867. };
  20868. const canLaunchToolbar = () => {
  20869. return !editor.removed && !(isTouch() && backstage.isContextMenuOpen());
  20870. };
  20871. const isSameLaunchElement = elem => is$1(lift2(elem, lastElement.get(), eq), true);
  20872. const shouldContextToolbarHide = () => {
  20873. if (!canLaunchToolbar()) {
  20874. return true;
  20875. } else {
  20876. const contextToolbarBounds = getBounds();
  20877. const anchorBounds = is$1(lastContextPosition.get(), 'node') ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
  20878. return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
  20879. }
  20880. };
  20881. const close = () => {
  20882. lastElement.clear();
  20883. lastTrigger.clear();
  20884. lastContextPosition.clear();
  20885. InlineView.hide(contextbar);
  20886. };
  20887. const hideOrRepositionIfNecessary = () => {
  20888. if (InlineView.isOpen(contextbar)) {
  20889. const contextBarEle = contextbar.element;
  20890. remove$6(contextBarEle, 'display');
  20891. if (shouldContextToolbarHide()) {
  20892. set$8(contextBarEle, 'display', 'none');
  20893. } else {
  20894. lastTrigger.set(0);
  20895. InlineView.reposition(contextbar);
  20896. }
  20897. }
  20898. };
  20899. const wrapInPopDialog = toolbarSpec => ({
  20900. dom: {
  20901. tag: 'div',
  20902. classes: ['tox-pop__dialog']
  20903. },
  20904. components: [toolbarSpec],
  20905. behaviours: derive$1([
  20906. Keying.config({ mode: 'acyclic' }),
  20907. config('pop-dialog-wrap-events', [
  20908. runOnAttached(comp => {
  20909. editor.shortcuts.add('ctrl+F9', 'focus statusbar', () => Keying.focusIn(comp));
  20910. }),
  20911. runOnDetached(_comp => {
  20912. editor.shortcuts.remove('ctrl+F9');
  20913. })
  20914. ])
  20915. ])
  20916. });
  20917. const getScopes = cached(() => categorise(registryContextToolbars, toolbarApi => {
  20918. const alloySpec = buildToolbar([toolbarApi]);
  20919. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  20920. }));
  20921. const buildContextToolbarGroups = (allButtons, ctx) => identifyButtons(editor, {
  20922. buttons: allButtons,
  20923. toolbar: ctx.items,
  20924. allowToolbarGroups: false
  20925. }, extras, Optional.some(['form:']));
  20926. const buildContextFormGroups = (ctx, providers) => ContextForm.buildInitGroups(ctx, providers);
  20927. const buildToolbar = toolbars => {
  20928. const {buttons} = editor.ui.registry.getAll();
  20929. const scopes = getScopes();
  20930. const allButtons = {
  20931. ...buttons,
  20932. ...scopes.formNavigators
  20933. };
  20934. const toolbarType = getToolbarMode(editor) === ToolbarMode$1.scrolling ? ToolbarMode$1.scrolling : ToolbarMode$1.default;
  20935. const initGroups = flatten(map$2(toolbars, ctx => ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers)));
  20936. return renderToolbar({
  20937. type: toolbarType,
  20938. uid: generate$6('context-toolbar'),
  20939. initGroups,
  20940. onEscape: Optional.none,
  20941. cyclicKeying: true,
  20942. providers: sharedBackstage.providers
  20943. });
  20944. };
  20945. const getAnchor = (position, element) => {
  20946. const anchorage = position === 'node' ? sharedBackstage.anchors.node(element) : sharedBackstage.anchors.cursor();
  20947. const anchorLayout = getAnchorLayout(editor, position, isTouch(), {
  20948. lastElement: lastElement.get,
  20949. isReposition: () => is$1(lastTrigger.get(), 0),
  20950. getMode: () => Positioning.getMode(sink)
  20951. });
  20952. return deepMerge(anchorage, anchorLayout);
  20953. };
  20954. const launchContext = (toolbarApi, elem) => {
  20955. launchContextToolbar.cancel();
  20956. if (!canLaunchToolbar()) {
  20957. return;
  20958. }
  20959. const toolbarSpec = buildToolbar(toolbarApi);
  20960. const position = toolbarApi[0].position;
  20961. const anchor = getAnchor(position, elem);
  20962. lastContextPosition.set(position);
  20963. lastTrigger.set(1);
  20964. const contextBarEle = contextbar.element;
  20965. remove$6(contextBarEle, 'display');
  20966. if (!isSameLaunchElement(elem)) {
  20967. remove$2(contextBarEle, transitionClass);
  20968. Positioning.reset(sink, contextbar);
  20969. }
  20970. InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
  20971. anchor,
  20972. transition: {
  20973. classes: [transitionClass],
  20974. mode: 'placement'
  20975. }
  20976. }, () => Optional.some(getBounds()));
  20977. elem.fold(lastElement.clear, lastElement.set);
  20978. if (shouldContextToolbarHide()) {
  20979. set$8(contextBarEle, 'display', 'none');
  20980. }
  20981. };
  20982. const launchContextToolbar = last(() => {
  20983. if (!editor.hasFocus() || editor.removed) {
  20984. return;
  20985. }
  20986. if (has(contextbar.element, transitionClass)) {
  20987. launchContextToolbar.throttle();
  20988. } else {
  20989. const scopes = getScopes();
  20990. lookup$1(scopes, editor).fold(close, info => {
  20991. launchContext(info.toolbars, Optional.some(info.elem));
  20992. });
  20993. }
  20994. }, 17);
  20995. editor.on('init', () => {
  20996. editor.on('remove', close);
  20997. editor.on('ScrollContent ScrollWindow ObjectResized ResizeEditor longpress', hideOrRepositionIfNecessary);
  20998. editor.on('click keyup focus SetContent', launchContextToolbar.throttle);
  20999. editor.on(hideContextToolbarEvent, close);
  21000. editor.on(showContextToolbarEvent, e => {
  21001. const scopes = getScopes();
  21002. get$g(scopes.lookupTable, e.toolbarKey).each(ctx => {
  21003. launchContext([ctx], someIf(e.target !== editor, e.target));
  21004. InlineView.getContent(contextbar).each(Keying.focusIn);
  21005. });
  21006. });
  21007. editor.on('focusout', _e => {
  21008. global$9.setEditorTimeout(editor, () => {
  21009. if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
  21010. close();
  21011. }
  21012. }, 0);
  21013. });
  21014. editor.on('SwitchMode', () => {
  21015. if (editor.mode.isReadOnly()) {
  21016. close();
  21017. }
  21018. });
  21019. editor.on('AfterProgressState', event => {
  21020. if (event.state) {
  21021. close();
  21022. } else if (editor.hasFocus()) {
  21023. launchContextToolbar.throttle();
  21024. }
  21025. });
  21026. editor.on('NodeChange', _e => {
  21027. search(contextbar.element).fold(launchContextToolbar.throttle, noop);
  21028. });
  21029. });
  21030. };
  21031. const register$8 = editor => {
  21032. const alignToolbarButtons = [
  21033. {
  21034. name: 'alignleft',
  21035. text: 'Align left',
  21036. cmd: 'JustifyLeft',
  21037. icon: 'align-left'
  21038. },
  21039. {
  21040. name: 'aligncenter',
  21041. text: 'Align center',
  21042. cmd: 'JustifyCenter',
  21043. icon: 'align-center'
  21044. },
  21045. {
  21046. name: 'alignright',
  21047. text: 'Align right',
  21048. cmd: 'JustifyRight',
  21049. icon: 'align-right'
  21050. },
  21051. {
  21052. name: 'alignjustify',
  21053. text: 'Justify',
  21054. cmd: 'JustifyFull',
  21055. icon: 'align-justify'
  21056. }
  21057. ];
  21058. each$1(alignToolbarButtons, item => {
  21059. editor.ui.registry.addToggleButton(item.name, {
  21060. tooltip: item.text,
  21061. icon: item.icon,
  21062. onAction: onActionExecCommand(editor, item.cmd),
  21063. onSetup: onSetupFormatToggle(editor, item.name)
  21064. });
  21065. });
  21066. editor.ui.registry.addButton('alignnone', {
  21067. tooltip: 'No alignment',
  21068. icon: 'align-none',
  21069. onAction: onActionExecCommand(editor, 'JustifyNone')
  21070. });
  21071. };
  21072. const units = {
  21073. unsupportedLength: [
  21074. 'em',
  21075. 'ex',
  21076. 'cap',
  21077. 'ch',
  21078. 'ic',
  21079. 'rem',
  21080. 'lh',
  21081. 'rlh',
  21082. 'vw',
  21083. 'vh',
  21084. 'vi',
  21085. 'vb',
  21086. 'vmin',
  21087. 'vmax',
  21088. 'cm',
  21089. 'mm',
  21090. 'Q',
  21091. 'in',
  21092. 'pc',
  21093. 'pt',
  21094. 'px'
  21095. ],
  21096. fixed: [
  21097. 'px',
  21098. 'pt'
  21099. ],
  21100. relative: ['%'],
  21101. empty: ['']
  21102. };
  21103. const pattern = (() => {
  21104. const decimalDigits = '[0-9]+';
  21105. const signedInteger = '[+-]?' + decimalDigits;
  21106. const exponentPart = '[eE]' + signedInteger;
  21107. const dot = '\\.';
  21108. const opt = input => `(?:${ input })?`;
  21109. const unsignedDecimalLiteral = [
  21110. 'Infinity',
  21111. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  21112. dot + decimalDigits + opt(exponentPart),
  21113. decimalDigits + opt(exponentPart)
  21114. ].join('|');
  21115. const float = `[+-]?(?:${ unsignedDecimalLiteral })`;
  21116. return new RegExp(`^(${ float })(.*)$`);
  21117. })();
  21118. const isUnit = (unit, accepted) => exists(accepted, acc => exists(units[acc], check => unit === check));
  21119. const parse = (input, accepted) => {
  21120. const match = Optional.from(pattern.exec(input));
  21121. return match.bind(array => {
  21122. const value = Number(array[1]);
  21123. const unitRaw = array[2];
  21124. if (isUnit(unitRaw, accepted)) {
  21125. return Optional.some({
  21126. value,
  21127. unit: unitRaw
  21128. });
  21129. } else {
  21130. return Optional.none();
  21131. }
  21132. });
  21133. };
  21134. const normalise = (input, accepted) => parse(input, accepted).map(({value, unit}) => value + unit);
  21135. const registerController = (editor, spec) => {
  21136. const getMenuItems = () => {
  21137. const options = spec.getOptions(editor);
  21138. const initial = spec.getCurrent(editor).map(spec.hash);
  21139. const current = value$2();
  21140. return map$2(options, value => ({
  21141. type: 'togglemenuitem',
  21142. text: spec.display(value),
  21143. onSetup: api => {
  21144. const setActive = active => {
  21145. if (active) {
  21146. current.on(oldApi => oldApi.setActive(false));
  21147. current.set(api);
  21148. }
  21149. api.setActive(active);
  21150. };
  21151. setActive(is$1(initial, spec.hash(value)));
  21152. const unbindWatcher = spec.watcher(editor, value, setActive);
  21153. return () => {
  21154. current.clear();
  21155. unbindWatcher();
  21156. };
  21157. },
  21158. onAction: () => spec.setCurrent(editor, value)
  21159. }));
  21160. };
  21161. editor.ui.registry.addMenuButton(spec.name, {
  21162. tooltip: spec.text,
  21163. icon: spec.icon,
  21164. fetch: callback => callback(getMenuItems()),
  21165. onSetup: spec.onToolbarSetup
  21166. });
  21167. editor.ui.registry.addNestedMenuItem(spec.name, {
  21168. type: 'nestedmenuitem',
  21169. text: spec.text,
  21170. getSubmenuItems: getMenuItems,
  21171. onSetup: spec.onMenuSetup
  21172. });
  21173. };
  21174. const lineHeightSpec = {
  21175. name: 'lineheight',
  21176. text: 'Line height',
  21177. icon: 'line-height',
  21178. getOptions: getLineHeightFormats,
  21179. hash: input => normalise(input, [
  21180. 'fixed',
  21181. 'relative',
  21182. 'empty'
  21183. ]).getOr(input),
  21184. display: identity,
  21185. watcher: (editor, value, callback) => editor.formatter.formatChanged('lineheight', callback, false, { value }).unbind,
  21186. getCurrent: editor => Optional.from(editor.queryCommandValue('LineHeight')),
  21187. setCurrent: (editor, value) => editor.execCommand('LineHeight', false, value)
  21188. };
  21189. const languageSpec = editor => {
  21190. const settingsOpt = Optional.from(getContentLanguages(editor));
  21191. return settingsOpt.map(settings => ({
  21192. name: 'language',
  21193. text: 'Language',
  21194. icon: 'language',
  21195. getOptions: constant$1(settings),
  21196. hash: input => isUndefined(input.customCode) ? input.code : `${ input.code }/${ input.customCode }`,
  21197. display: input => input.title,
  21198. watcher: (editor, value, callback) => editor.formatter.formatChanged('lang', callback, false, {
  21199. value: value.code,
  21200. customValue: value.customCode
  21201. }).unbind,
  21202. getCurrent: editor => {
  21203. const node = SugarElement.fromDom(editor.selection.getNode());
  21204. return closest$4(node, n => Optional.some(n).filter(isElement$1).bind(ele => {
  21205. const codeOpt = getOpt(ele, 'lang');
  21206. return codeOpt.map(code => {
  21207. const customCode = getOpt(ele, 'data-mce-lang').getOrUndefined();
  21208. return {
  21209. code,
  21210. customCode,
  21211. title: ''
  21212. };
  21213. });
  21214. }));
  21215. },
  21216. setCurrent: (editor, lang) => editor.execCommand('Lang', false, lang),
  21217. onToolbarSetup: api => {
  21218. const unbinder = unbindable();
  21219. api.setActive(editor.formatter.match('lang', {}, undefined, true));
  21220. unbinder.set(editor.formatter.formatChanged('lang', api.setActive, true));
  21221. return unbinder.clear;
  21222. }
  21223. }));
  21224. };
  21225. const register$7 = editor => {
  21226. registerController(editor, lineHeightSpec);
  21227. languageSpec(editor).each(spec => registerController(editor, spec));
  21228. };
  21229. const register$6 = (editor, backstage) => {
  21230. createAlignMenu(editor, backstage);
  21231. createFontFamilyMenu(editor, backstage);
  21232. createStylesMenu(editor, backstage);
  21233. createBlocksMenu(editor, backstage);
  21234. createFontSizeMenu(editor, backstage);
  21235. };
  21236. const onSetupOutdentState = editor => onSetupEvent(editor, 'NodeChange', api => {
  21237. api.setEnabled(editor.queryCommandState('outdent'));
  21238. });
  21239. const registerButtons$2 = editor => {
  21240. editor.ui.registry.addButton('outdent', {
  21241. tooltip: 'Decrease indent',
  21242. icon: 'outdent',
  21243. onSetup: onSetupOutdentState(editor),
  21244. onAction: onActionExecCommand(editor, 'outdent')
  21245. });
  21246. editor.ui.registry.addButton('indent', {
  21247. tooltip: 'Increase indent',
  21248. icon: 'indent',
  21249. onAction: onActionExecCommand(editor, 'indent')
  21250. });
  21251. };
  21252. const register$5 = editor => {
  21253. registerButtons$2(editor);
  21254. };
  21255. const makeSetupHandler = (editor, pasteAsText) => api => {
  21256. api.setActive(pasteAsText.get());
  21257. const pastePlainTextToggleHandler = e => {
  21258. pasteAsText.set(e.state);
  21259. api.setActive(e.state);
  21260. };
  21261. editor.on('PastePlainTextToggle', pastePlainTextToggleHandler);
  21262. return () => editor.off('PastePlainTextToggle', pastePlainTextToggleHandler);
  21263. };
  21264. const register$4 = editor => {
  21265. const pasteAsText = Cell(getPasteAsText(editor));
  21266. const onAction = () => editor.execCommand('mceTogglePlainTextPaste');
  21267. editor.ui.registry.addToggleButton('pastetext', {
  21268. active: false,
  21269. icon: 'paste-text',
  21270. tooltip: 'Paste as text',
  21271. onAction,
  21272. onSetup: makeSetupHandler(editor, pasteAsText)
  21273. });
  21274. editor.ui.registry.addToggleMenuItem('pastetext', {
  21275. text: 'Paste as text',
  21276. icon: 'paste-text',
  21277. onAction,
  21278. onSetup: makeSetupHandler(editor, pasteAsText)
  21279. });
  21280. };
  21281. const onActionToggleFormat = (editor, fmt) => () => {
  21282. editor.execCommand('mceToggleFormat', false, fmt);
  21283. };
  21284. const registerFormatButtons = editor => {
  21285. global$1.each([
  21286. {
  21287. name: 'bold',
  21288. text: 'Bold',
  21289. icon: 'bold'
  21290. },
  21291. {
  21292. name: 'italic',
  21293. text: 'Italic',
  21294. icon: 'italic'
  21295. },
  21296. {
  21297. name: 'underline',
  21298. text: 'Underline',
  21299. icon: 'underline'
  21300. },
  21301. {
  21302. name: 'strikethrough',
  21303. text: 'Strikethrough',
  21304. icon: 'strike-through'
  21305. },
  21306. {
  21307. name: 'subscript',
  21308. text: 'Subscript',
  21309. icon: 'subscript'
  21310. },
  21311. {
  21312. name: 'superscript',
  21313. text: 'Superscript',
  21314. icon: 'superscript'
  21315. }
  21316. ], (btn, _idx) => {
  21317. editor.ui.registry.addToggleButton(btn.name, {
  21318. tooltip: btn.text,
  21319. icon: btn.icon,
  21320. onSetup: onSetupFormatToggle(editor, btn.name),
  21321. onAction: onActionToggleFormat(editor, btn.name)
  21322. });
  21323. });
  21324. for (let i = 1; i <= 6; i++) {
  21325. const name = 'h' + i;
  21326. editor.ui.registry.addToggleButton(name, {
  21327. text: name.toUpperCase(),
  21328. tooltip: 'Heading ' + i,
  21329. onSetup: onSetupFormatToggle(editor, name),
  21330. onAction: onActionToggleFormat(editor, name)
  21331. });
  21332. }
  21333. };
  21334. const registerCommandButtons = editor => {
  21335. global$1.each([
  21336. {
  21337. name: 'cut',
  21338. text: 'Cut',
  21339. action: 'Cut',
  21340. icon: 'cut'
  21341. },
  21342. {
  21343. name: 'copy',
  21344. text: 'Copy',
  21345. action: 'Copy',
  21346. icon: 'copy'
  21347. },
  21348. {
  21349. name: 'paste',
  21350. text: 'Paste',
  21351. action: 'Paste',
  21352. icon: 'paste'
  21353. },
  21354. {
  21355. name: 'help',
  21356. text: 'Help',
  21357. action: 'mceHelp',
  21358. icon: 'help'
  21359. },
  21360. {
  21361. name: 'selectall',
  21362. text: 'Select all',
  21363. action: 'SelectAll',
  21364. icon: 'select-all'
  21365. },
  21366. {
  21367. name: 'newdocument',
  21368. text: 'New document',
  21369. action: 'mceNewDocument',
  21370. icon: 'new-document'
  21371. },
  21372. {
  21373. name: 'removeformat',
  21374. text: 'Clear formatting',
  21375. action: 'RemoveFormat',
  21376. icon: 'remove-formatting'
  21377. },
  21378. {
  21379. name: 'remove',
  21380. text: 'Remove',
  21381. action: 'Delete',
  21382. icon: 'remove'
  21383. },
  21384. {
  21385. name: 'print',
  21386. text: 'Print',
  21387. action: 'mcePrint',
  21388. icon: 'print'
  21389. },
  21390. {
  21391. name: 'hr',
  21392. text: 'Horizontal line',
  21393. action: 'InsertHorizontalRule',
  21394. icon: 'horizontal-rule'
  21395. }
  21396. ], btn => {
  21397. editor.ui.registry.addButton(btn.name, {
  21398. tooltip: btn.text,
  21399. icon: btn.icon,
  21400. onAction: onActionExecCommand(editor, btn.action)
  21401. });
  21402. });
  21403. };
  21404. const registerCommandToggleButtons = editor => {
  21405. global$1.each([{
  21406. name: 'blockquote',
  21407. text: 'Blockquote',
  21408. action: 'mceBlockQuote',
  21409. icon: 'quote'
  21410. }], btn => {
  21411. editor.ui.registry.addToggleButton(btn.name, {
  21412. tooltip: btn.text,
  21413. icon: btn.icon,
  21414. onAction: onActionExecCommand(editor, btn.action),
  21415. onSetup: onSetupFormatToggle(editor, btn.name)
  21416. });
  21417. });
  21418. };
  21419. const registerButtons$1 = editor => {
  21420. registerFormatButtons(editor);
  21421. registerCommandButtons(editor);
  21422. registerCommandToggleButtons(editor);
  21423. };
  21424. const registerMenuItems$2 = editor => {
  21425. global$1.each([
  21426. {
  21427. name: 'bold',
  21428. text: 'Bold',
  21429. action: 'Bold',
  21430. icon: 'bold',
  21431. shortcut: 'Meta+B'
  21432. },
  21433. {
  21434. name: 'italic',
  21435. text: 'Italic',
  21436. action: 'Italic',
  21437. icon: 'italic',
  21438. shortcut: 'Meta+I'
  21439. },
  21440. {
  21441. name: 'underline',
  21442. text: 'Underline',
  21443. action: 'Underline',
  21444. icon: 'underline',
  21445. shortcut: 'Meta+U'
  21446. },
  21447. {
  21448. name: 'strikethrough',
  21449. text: 'Strikethrough',
  21450. action: 'Strikethrough',
  21451. icon: 'strike-through'
  21452. },
  21453. {
  21454. name: 'subscript',
  21455. text: 'Subscript',
  21456. action: 'Subscript',
  21457. icon: 'subscript'
  21458. },
  21459. {
  21460. name: 'superscript',
  21461. text: 'Superscript',
  21462. action: 'Superscript',
  21463. icon: 'superscript'
  21464. },
  21465. {
  21466. name: 'removeformat',
  21467. text: 'Clear formatting',
  21468. action: 'RemoveFormat',
  21469. icon: 'remove-formatting'
  21470. },
  21471. {
  21472. name: 'newdocument',
  21473. text: 'New document',
  21474. action: 'mceNewDocument',
  21475. icon: 'new-document'
  21476. },
  21477. {
  21478. name: 'cut',
  21479. text: 'Cut',
  21480. action: 'Cut',
  21481. icon: 'cut',
  21482. shortcut: 'Meta+X'
  21483. },
  21484. {
  21485. name: 'copy',
  21486. text: 'Copy',
  21487. action: 'Copy',
  21488. icon: 'copy',
  21489. shortcut: 'Meta+C'
  21490. },
  21491. {
  21492. name: 'paste',
  21493. text: 'Paste',
  21494. action: 'Paste',
  21495. icon: 'paste',
  21496. shortcut: 'Meta+V'
  21497. },
  21498. {
  21499. name: 'selectall',
  21500. text: 'Select all',
  21501. action: 'SelectAll',
  21502. icon: 'select-all',
  21503. shortcut: 'Meta+A'
  21504. },
  21505. {
  21506. name: 'print',
  21507. text: 'Print...',
  21508. action: 'mcePrint',
  21509. icon: 'print',
  21510. shortcut: 'Meta+P'
  21511. },
  21512. {
  21513. name: 'hr',
  21514. text: 'Horizontal line',
  21515. action: 'InsertHorizontalRule',
  21516. icon: 'horizontal-rule'
  21517. }
  21518. ], menuitem => {
  21519. editor.ui.registry.addMenuItem(menuitem.name, {
  21520. text: menuitem.text,
  21521. icon: menuitem.icon,
  21522. shortcut: menuitem.shortcut,
  21523. onAction: onActionExecCommand(editor, menuitem.action)
  21524. });
  21525. });
  21526. editor.ui.registry.addMenuItem('codeformat', {
  21527. text: 'Code',
  21528. icon: 'sourcecode',
  21529. onAction: onActionToggleFormat(editor, 'code')
  21530. });
  21531. };
  21532. const register$3 = editor => {
  21533. registerButtons$1(editor);
  21534. registerMenuItems$2(editor);
  21535. };
  21536. const onSetupUndoRedoState = (editor, type) => onSetupEvent(editor, 'Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', api => {
  21537. api.setEnabled(!editor.mode.isReadOnly() && editor.undoManager[type]());
  21538. });
  21539. const registerMenuItems$1 = editor => {
  21540. editor.ui.registry.addMenuItem('undo', {
  21541. text: 'Undo',
  21542. icon: 'undo',
  21543. shortcut: 'Meta+Z',
  21544. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  21545. onAction: onActionExecCommand(editor, 'undo')
  21546. });
  21547. editor.ui.registry.addMenuItem('redo', {
  21548. text: 'Redo',
  21549. icon: 'redo',
  21550. shortcut: 'Meta+Y',
  21551. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  21552. onAction: onActionExecCommand(editor, 'redo')
  21553. });
  21554. };
  21555. const registerButtons = editor => {
  21556. editor.ui.registry.addButton('undo', {
  21557. tooltip: 'Undo',
  21558. icon: 'undo',
  21559. enabled: false,
  21560. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  21561. onAction: onActionExecCommand(editor, 'undo')
  21562. });
  21563. editor.ui.registry.addButton('redo', {
  21564. tooltip: 'Redo',
  21565. icon: 'redo',
  21566. enabled: false,
  21567. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  21568. onAction: onActionExecCommand(editor, 'redo')
  21569. });
  21570. };
  21571. const register$2 = editor => {
  21572. registerMenuItems$1(editor);
  21573. registerButtons(editor);
  21574. };
  21575. const onSetupVisualAidState = editor => onSetupEvent(editor, 'VisualAid', api => {
  21576. api.setActive(editor.hasVisual);
  21577. });
  21578. const registerMenuItems = editor => {
  21579. editor.ui.registry.addToggleMenuItem('visualaid', {
  21580. text: 'Visual aids',
  21581. onSetup: onSetupVisualAidState(editor),
  21582. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  21583. });
  21584. };
  21585. const registerToolbarButton = editor => {
  21586. editor.ui.registry.addButton('visualaid', {
  21587. tooltip: 'Visual aids',
  21588. text: 'Visual aids',
  21589. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  21590. });
  21591. };
  21592. const register$1 = editor => {
  21593. registerToolbarButton(editor);
  21594. registerMenuItems(editor);
  21595. };
  21596. const setup$6 = (editor, backstage) => {
  21597. register$8(editor);
  21598. register$3(editor);
  21599. register$6(editor, backstage);
  21600. register$2(editor);
  21601. register$c(editor);
  21602. register$1(editor);
  21603. register$5(editor);
  21604. register$7(editor);
  21605. register$4(editor);
  21606. };
  21607. const patchPipeConfig = config => isString(config) ? config.split(/[ ,]/) : config;
  21608. const option = name => editor => editor.options.get(name);
  21609. const register = editor => {
  21610. const registerOption = editor.options.register;
  21611. registerOption('contextmenu_avoid_overlap', {
  21612. processor: 'string',
  21613. default: ''
  21614. });
  21615. registerOption('contextmenu_never_use_native', {
  21616. processor: 'boolean',
  21617. default: false
  21618. });
  21619. registerOption('contextmenu', {
  21620. processor: value => {
  21621. if (value === false) {
  21622. return {
  21623. value: [],
  21624. valid: true
  21625. };
  21626. } else if (isString(value) || isArrayOf(value, isString)) {
  21627. return {
  21628. value: patchPipeConfig(value),
  21629. valid: true
  21630. };
  21631. } else {
  21632. return {
  21633. valid: false,
  21634. message: 'Must be false or a string.'
  21635. };
  21636. }
  21637. },
  21638. default: 'link linkchecker image editimage table spellchecker configurepermanentpen'
  21639. });
  21640. };
  21641. const shouldNeverUseNative = option('contextmenu_never_use_native');
  21642. const getAvoidOverlapSelector = option('contextmenu_avoid_overlap');
  21643. const isContextMenuDisabled = editor => getContextMenu(editor).length === 0;
  21644. const getContextMenu = editor => {
  21645. const contextMenus = editor.ui.registry.getAll().contextMenus;
  21646. const contextMenu = editor.options.get('contextmenu');
  21647. if (editor.options.isSet('contextmenu')) {
  21648. return contextMenu;
  21649. } else {
  21650. return filter$2(contextMenu, item => has$2(contextMenus, item));
  21651. }
  21652. };
  21653. const nu = (x, y) => ({
  21654. type: 'makeshift',
  21655. x,
  21656. y
  21657. });
  21658. const transpose = (pos, dx, dy) => {
  21659. return nu(pos.x + dx, pos.y + dy);
  21660. };
  21661. const isTouchEvent = e => e.type === 'longpress' || e.type.indexOf('touch') === 0;
  21662. const fromPageXY = e => {
  21663. if (isTouchEvent(e)) {
  21664. const touch = e.touches[0];
  21665. return nu(touch.pageX, touch.pageY);
  21666. } else {
  21667. return nu(e.pageX, e.pageY);
  21668. }
  21669. };
  21670. const fromClientXY = e => {
  21671. if (isTouchEvent(e)) {
  21672. const touch = e.touches[0];
  21673. return nu(touch.clientX, touch.clientY);
  21674. } else {
  21675. return nu(e.clientX, e.clientY);
  21676. }
  21677. };
  21678. const transposeContentAreaContainer = (element, pos) => {
  21679. const containerPos = global$7.DOM.getPos(element);
  21680. return transpose(pos, containerPos.x, containerPos.y);
  21681. };
  21682. const getPointAnchor = (editor, e) => {
  21683. if (e.type === 'contextmenu' || e.type === 'longpress') {
  21684. if (editor.inline) {
  21685. return fromPageXY(e);
  21686. } else {
  21687. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  21688. }
  21689. } else {
  21690. return getSelectionAnchor(editor);
  21691. }
  21692. };
  21693. const getSelectionAnchor = editor => {
  21694. return {
  21695. type: 'selection',
  21696. root: SugarElement.fromDom(editor.selection.getNode())
  21697. };
  21698. };
  21699. const getNodeAnchor = editor => ({
  21700. type: 'node',
  21701. node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
  21702. root: SugarElement.fromDom(editor.getBody())
  21703. });
  21704. const getAnchorSpec$1 = (editor, e, anchorType) => {
  21705. switch (anchorType) {
  21706. case 'node':
  21707. return getNodeAnchor(editor);
  21708. case 'point':
  21709. return getPointAnchor(editor, e);
  21710. case 'selection':
  21711. return getSelectionAnchor(editor);
  21712. }
  21713. };
  21714. const initAndShow$1 = (editor, e, buildMenu, backstage, contextmenu, anchorType) => {
  21715. const items = buildMenu();
  21716. const anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  21717. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(menuData => {
  21718. e.preventDefault();
  21719. InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
  21720. menu: { markers: markers('normal') },
  21721. data: menuData
  21722. });
  21723. });
  21724. };
  21725. const layouts = {
  21726. onLtr: () => [
  21727. south$2,
  21728. southeast$2,
  21729. southwest$2,
  21730. northeast$2,
  21731. northwest$2,
  21732. north$2,
  21733. north,
  21734. south,
  21735. northeast,
  21736. southeast,
  21737. northwest,
  21738. southwest
  21739. ],
  21740. onRtl: () => [
  21741. south$2,
  21742. southwest$2,
  21743. southeast$2,
  21744. northwest$2,
  21745. northeast$2,
  21746. north$2,
  21747. north,
  21748. south,
  21749. northwest,
  21750. southwest,
  21751. northeast,
  21752. southeast
  21753. ]
  21754. };
  21755. const bubbleSize = 12;
  21756. const bubbleAlignments = {
  21757. valignCentre: [],
  21758. alignCentre: [],
  21759. alignLeft: ['tox-pop--align-left'],
  21760. alignRight: ['tox-pop--align-right'],
  21761. right: ['tox-pop--right'],
  21762. left: ['tox-pop--left'],
  21763. bottom: ['tox-pop--bottom'],
  21764. top: ['tox-pop--top']
  21765. };
  21766. const isTouchWithinSelection = (editor, e) => {
  21767. const selection = editor.selection;
  21768. if (selection.isCollapsed() || e.touches.length < 1) {
  21769. return false;
  21770. } else {
  21771. const touch = e.touches[0];
  21772. const rng = selection.getRng();
  21773. const rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
  21774. return rngRectOpt.exists(rngRect => rngRect.left <= touch.clientX && rngRect.right >= touch.clientX && rngRect.top <= touch.clientY && rngRect.bottom >= touch.clientY);
  21775. }
  21776. };
  21777. const setupiOSOverrides = editor => {
  21778. const originalSelection = editor.selection.getRng();
  21779. const selectionReset = () => {
  21780. global$9.setEditorTimeout(editor, () => {
  21781. editor.selection.setRng(originalSelection);
  21782. }, 10);
  21783. unbindEventListeners();
  21784. };
  21785. editor.once('touchend', selectionReset);
  21786. const preventMousedown = e => {
  21787. e.preventDefault();
  21788. e.stopImmediatePropagation();
  21789. };
  21790. editor.on('mousedown', preventMousedown, true);
  21791. const clearSelectionReset = () => unbindEventListeners();
  21792. editor.once('longpresscancel', clearSelectionReset);
  21793. const unbindEventListeners = () => {
  21794. editor.off('touchend', selectionReset);
  21795. editor.off('longpresscancel', clearSelectionReset);
  21796. editor.off('mousedown', preventMousedown);
  21797. };
  21798. };
  21799. const getAnchorSpec = (editor, e, anchorType) => {
  21800. const anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  21801. const bubbleYOffset = anchorType === 'point' ? bubbleSize : 0;
  21802. return {
  21803. bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
  21804. layouts,
  21805. overrides: {
  21806. maxWidthFunction: expandable(),
  21807. maxHeightFunction: expandable$1()
  21808. },
  21809. ...anchorSpec
  21810. };
  21811. };
  21812. const show = (editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) => {
  21813. const anchorSpec = getAnchorSpec(editor, e, anchorType);
  21814. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(menuData => {
  21815. e.preventDefault();
  21816. InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
  21817. menu: {
  21818. markers: markers('normal'),
  21819. highlightImmediately
  21820. },
  21821. data: menuData,
  21822. type: 'horizontal'
  21823. }, () => Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === 'node' ? 'node' : 'selection')));
  21824. editor.dispatch(hideContextToolbarEvent);
  21825. });
  21826. };
  21827. const initAndShow = (editor, e, buildMenu, backstage, contextmenu, anchorType) => {
  21828. const detection = detect$1();
  21829. const isiOS = detection.os.isiOS();
  21830. const isMacOS = detection.os.isMacOS();
  21831. const isAndroid = detection.os.isAndroid();
  21832. const isTouch = detection.deviceType.isTouch();
  21833. const shouldHighlightImmediately = () => !(isAndroid || isiOS || isMacOS && isTouch);
  21834. const open = () => {
  21835. const items = buildMenu();
  21836. show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
  21837. };
  21838. if ((isMacOS || isiOS) && anchorType !== 'node') {
  21839. const openiOS = () => {
  21840. setupiOSOverrides(editor);
  21841. open();
  21842. };
  21843. if (isTouchWithinSelection(editor, e)) {
  21844. openiOS();
  21845. } else {
  21846. editor.once('selectionchange', openiOS);
  21847. editor.once('touchend', () => editor.off('selectionchange', openiOS));
  21848. }
  21849. } else {
  21850. open();
  21851. }
  21852. };
  21853. const isSeparator = item => isString(item) ? item === '|' : item.type === 'separator';
  21854. const separator = { type: 'separator' };
  21855. const makeContextItem = item => {
  21856. const commonMenuItem = item => ({
  21857. text: item.text,
  21858. icon: item.icon,
  21859. enabled: item.enabled,
  21860. shortcut: item.shortcut
  21861. });
  21862. if (isString(item)) {
  21863. return item;
  21864. } else {
  21865. switch (item.type) {
  21866. case 'separator':
  21867. return separator;
  21868. case 'submenu':
  21869. return {
  21870. type: 'nestedmenuitem',
  21871. ...commonMenuItem(item),
  21872. getSubmenuItems: () => {
  21873. const items = item.getSubmenuItems();
  21874. if (isString(items)) {
  21875. return items;
  21876. } else {
  21877. return map$2(items, makeContextItem);
  21878. }
  21879. }
  21880. };
  21881. default:
  21882. return {
  21883. type: 'menuitem',
  21884. ...commonMenuItem(item),
  21885. onAction: noarg(item.onAction)
  21886. };
  21887. }
  21888. }
  21889. };
  21890. const addContextMenuGroup = (xs, groupItems) => {
  21891. if (groupItems.length === 0) {
  21892. return xs;
  21893. }
  21894. const lastMenuItem = last$1(xs).filter(item => !isSeparator(item));
  21895. const before = lastMenuItem.fold(() => [], _ => [separator]);
  21896. return xs.concat(before).concat(groupItems).concat([separator]);
  21897. };
  21898. const generateContextMenu = (contextMenus, menuConfig, selectedElement) => {
  21899. const sections = foldl(menuConfig, (acc, name) => {
  21900. return get$g(contextMenus, name.toLowerCase()).map(menu => {
  21901. const items = menu.update(selectedElement);
  21902. if (isString(items)) {
  21903. return addContextMenuGroup(acc, items.split(' '));
  21904. } else if (items.length > 0) {
  21905. const allItems = map$2(items, makeContextItem);
  21906. return addContextMenuGroup(acc, allItems);
  21907. } else {
  21908. return acc;
  21909. }
  21910. }).getOrThunk(() => acc.concat([name]));
  21911. }, []);
  21912. if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
  21913. sections.pop();
  21914. }
  21915. return sections;
  21916. };
  21917. const isNativeOverrideKeyEvent = (editor, e) => e.ctrlKey && !shouldNeverUseNative(editor);
  21918. const isTriggeredByKeyboard = (editor, e) => e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  21919. const getSelectedElement = (editor, e) => isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
  21920. const getAnchorType = (editor, e) => {
  21921. const selector = getAvoidOverlapSelector(editor);
  21922. const anchorType = isTriggeredByKeyboard(editor, e) ? 'selection' : 'point';
  21923. if (isNotEmpty(selector)) {
  21924. const target = getSelectedElement(editor, e);
  21925. const selectorExists = closest(SugarElement.fromDom(target), selector);
  21926. return selectorExists ? 'node' : anchorType;
  21927. } else {
  21928. return anchorType;
  21929. }
  21930. };
  21931. const setup$5 = (editor, lazySink, backstage) => {
  21932. const detection = detect$1();
  21933. const isTouch = detection.deviceType.isTouch;
  21934. const contextmenu = build$1(InlineView.sketch({
  21935. dom: { tag: 'div' },
  21936. lazySink,
  21937. onEscape: () => editor.focus(),
  21938. onShow: () => backstage.setContextMenuState(true),
  21939. onHide: () => backstage.setContextMenuState(false),
  21940. fireDismissalEventInstead: {},
  21941. inlineBehaviours: derive$1([config('dismissContextMenu', [run$1(dismissRequested(), (comp, _se) => {
  21942. Sandboxing.close(comp);
  21943. editor.focus();
  21944. })])])
  21945. }));
  21946. const hideContextMenu = _e => InlineView.hide(contextmenu);
  21947. const showContextMenu = e => {
  21948. if (shouldNeverUseNative(editor)) {
  21949. e.preventDefault();
  21950. }
  21951. if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  21952. return;
  21953. }
  21954. const anchorType = getAnchorType(editor, e);
  21955. const buildMenu = () => {
  21956. const selectedElement = getSelectedElement(editor, e);
  21957. const registry = editor.ui.registry.getAll();
  21958. const menuConfig = getContextMenu(editor);
  21959. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  21960. };
  21961. const initAndShow$2 = isTouch() ? initAndShow : initAndShow$1;
  21962. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType);
  21963. };
  21964. editor.on('init', () => {
  21965. const hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  21966. editor.on(hideEvents, hideContextMenu);
  21967. editor.on('longpress contextmenu', showContextMenu);
  21968. });
  21969. };
  21970. const adt = Adt.generate([
  21971. {
  21972. offset: [
  21973. 'x',
  21974. 'y'
  21975. ]
  21976. },
  21977. {
  21978. absolute: [
  21979. 'x',
  21980. 'y'
  21981. ]
  21982. },
  21983. {
  21984. fixed: [
  21985. 'x',
  21986. 'y'
  21987. ]
  21988. }
  21989. ]);
  21990. const subtract = change => point => point.translate(-change.left, -change.top);
  21991. const add = change => point => point.translate(change.left, change.top);
  21992. const transform = changes => (x, y) => foldl(changes, (rest, f) => f(rest), SugarPosition(x, y));
  21993. const asFixed = (coord, scroll, origin) => coord.fold(transform([
  21994. add(origin),
  21995. subtract(scroll)
  21996. ]), transform([subtract(scroll)]), transform([]));
  21997. const asAbsolute = (coord, scroll, origin) => coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)]));
  21998. const asOffset = (coord, scroll, origin) => coord.fold(transform([]), transform([subtract(origin)]), transform([
  21999. add(scroll),
  22000. subtract(origin)
  22001. ]));
  22002. const withinRange = (coord1, coord2, xRange, yRange, scroll, origin) => {
  22003. const a1 = asAbsolute(coord1, scroll, origin);
  22004. const a2 = asAbsolute(coord2, scroll, origin);
  22005. return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
  22006. };
  22007. const getDeltas = (coord1, coord2, xRange, yRange, scroll, origin) => {
  22008. const a1 = asAbsolute(coord1, scroll, origin);
  22009. const a2 = asAbsolute(coord2, scroll, origin);
  22010. const left = Math.abs(a1.left - a2.left);
  22011. const top = Math.abs(a1.top - a2.top);
  22012. return SugarPosition(left, top);
  22013. };
  22014. const toStyles = (coord, scroll, origin) => {
  22015. const stylesOpt = coord.fold((x, y) => ({
  22016. position: Optional.some('absolute'),
  22017. left: Optional.some(x + 'px'),
  22018. top: Optional.some(y + 'px')
  22019. }), (x, y) => ({
  22020. position: Optional.some('absolute'),
  22021. left: Optional.some(x - origin.left + 'px'),
  22022. top: Optional.some(y - origin.top + 'px')
  22023. }), (x, y) => ({
  22024. position: Optional.some('fixed'),
  22025. left: Optional.some(x + 'px'),
  22026. top: Optional.some(y + 'px')
  22027. }));
  22028. return {
  22029. right: Optional.none(),
  22030. bottom: Optional.none(),
  22031. ...stylesOpt
  22032. };
  22033. };
  22034. const translate = (coord, deltaX, deltaY) => coord.fold((x, y) => offset(x + deltaX, y + deltaY), (x, y) => absolute(x + deltaX, y + deltaY), (x, y) => fixed(x + deltaX, y + deltaY));
  22035. const absorb = (partialCoord, originalCoord, scroll, origin) => {
  22036. const absorbOne = (stencil, nu) => (optX, optY) => {
  22037. const original = stencil(originalCoord, scroll, origin);
  22038. return nu(optX.getOr(original.left), optY.getOr(original.top));
  22039. };
  22040. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
  22041. };
  22042. const offset = adt.offset;
  22043. const absolute = adt.absolute;
  22044. const fixed = adt.fixed;
  22045. const parseAttrToInt = (element, name) => {
  22046. const value = get$f(element, name);
  22047. return isUndefined(value) ? NaN : parseInt(value, 10);
  22048. };
  22049. const get = (component, snapsInfo) => {
  22050. const element = component.element;
  22051. const x = parseAttrToInt(element, snapsInfo.leftAttr);
  22052. const y = parseAttrToInt(element, snapsInfo.topAttr);
  22053. return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
  22054. };
  22055. const set = (component, snapsInfo, pt) => {
  22056. const element = component.element;
  22057. set$9(element, snapsInfo.leftAttr, pt.left + 'px');
  22058. set$9(element, snapsInfo.topAttr, pt.top + 'px');
  22059. };
  22060. const clear = (component, snapsInfo) => {
  22061. const element = component.element;
  22062. remove$7(element, snapsInfo.leftAttr);
  22063. remove$7(element, snapsInfo.topAttr);
  22064. };
  22065. const getCoords = (component, snapInfo, coord, delta) => get(component, snapInfo).fold(() => coord, fixed$1 => fixed(fixed$1.left + delta.left, fixed$1.top + delta.top));
  22066. const moveOrSnap = (component, snapInfo, coord, delta, scroll, origin) => {
  22067. const newCoord = getCoords(component, snapInfo, coord, delta);
  22068. const snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  22069. const fixedCoord = asFixed(newCoord, scroll, origin);
  22070. set(component, snapInfo, fixedCoord);
  22071. return snap.fold(() => ({
  22072. coord: fixed(fixedCoord.left, fixedCoord.top),
  22073. extra: Optional.none()
  22074. }), spanned => ({
  22075. coord: spanned.output,
  22076. extra: spanned.extra
  22077. }));
  22078. };
  22079. const stopDrag = (component, snapInfo) => {
  22080. clear(component, snapInfo);
  22081. };
  22082. const findMatchingSnap = (snaps, newCoord, scroll, origin) => findMap(snaps, snap => {
  22083. const sensor = snap.sensor;
  22084. const inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  22085. return inRange ? Optional.some({
  22086. output: absorb(snap.output, newCoord, scroll, origin),
  22087. extra: snap.extra
  22088. }) : Optional.none();
  22089. });
  22090. const findClosestSnap = (component, snapInfo, newCoord, scroll, origin) => {
  22091. const snaps = snapInfo.getSnapPoints(component);
  22092. const matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  22093. return matchSnap.orThunk(() => {
  22094. const bestSnap = foldl(snaps, (acc, snap) => {
  22095. const sensor = snap.sensor;
  22096. const deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  22097. return acc.deltas.fold(() => ({
  22098. deltas: Optional.some(deltas),
  22099. snap: Optional.some(snap)
  22100. }), bestDeltas => {
  22101. const currAvg = (deltas.left + deltas.top) / 2;
  22102. const bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
  22103. if (currAvg <= bestAvg) {
  22104. return {
  22105. deltas: Optional.some(deltas),
  22106. snap: Optional.some(snap)
  22107. };
  22108. } else {
  22109. return acc;
  22110. }
  22111. });
  22112. }, {
  22113. deltas: Optional.none(),
  22114. snap: Optional.none()
  22115. });
  22116. return bestSnap.snap.map(snap => ({
  22117. output: absorb(snap.output, newCoord, scroll, origin),
  22118. extra: snap.extra
  22119. }));
  22120. });
  22121. };
  22122. const findSnap = (component, snapInfo, newCoord, scroll, origin) => {
  22123. const snaps = snapInfo.getSnapPoints(component);
  22124. return findMatchingSnap(snaps, newCoord, scroll, origin);
  22125. };
  22126. const snapTo$1 = (snap, scroll, origin) => ({
  22127. coord: absorb(snap.output, snap.output, scroll, origin),
  22128. extra: snap.extra
  22129. });
  22130. const snapTo = (component, dragConfig, _state, snap) => {
  22131. const target = dragConfig.getTarget(component.element);
  22132. if (dragConfig.repositionTarget) {
  22133. const doc = owner$4(component.element);
  22134. const scroll = get$b(doc);
  22135. const origin = getOrigin(target);
  22136. const snapPin = snapTo$1(snap, scroll, origin);
  22137. const styles = toStyles(snapPin.coord, scroll, origin);
  22138. setOptions(target, styles);
  22139. }
  22140. };
  22141. var DraggingApis = /*#__PURE__*/Object.freeze({
  22142. __proto__: null,
  22143. snapTo: snapTo
  22144. });
  22145. const initialAttribute = 'data-initial-z-index';
  22146. const resetZIndex = blocker => {
  22147. parent(blocker.element).filter(isElement$1).each(root => {
  22148. getOpt(root, initialAttribute).fold(() => remove$6(root, 'z-index'), zIndex => set$8(root, 'z-index', zIndex));
  22149. remove$7(root, initialAttribute);
  22150. });
  22151. };
  22152. const changeZIndex = blocker => {
  22153. parent(blocker.element).filter(isElement$1).each(root => {
  22154. getRaw(root, 'z-index').each(zindex => {
  22155. set$9(root, initialAttribute, zindex);
  22156. });
  22157. set$8(root, 'z-index', get$e(blocker.element, 'z-index'));
  22158. });
  22159. };
  22160. const instigate = (anyComponent, blocker) => {
  22161. anyComponent.getSystem().addToGui(blocker);
  22162. changeZIndex(blocker);
  22163. };
  22164. const discard = blocker => {
  22165. resetZIndex(blocker);
  22166. blocker.getSystem().removeFromGui(blocker);
  22167. };
  22168. const createComponent = (component, blockerClass, blockerEvents) => component.getSystem().build(Container.sketch({
  22169. dom: {
  22170. styles: {
  22171. 'left': '0px',
  22172. 'top': '0px',
  22173. 'width': '100%',
  22174. 'height': '100%',
  22175. 'position': 'fixed',
  22176. 'z-index': '1000000000000000'
  22177. },
  22178. classes: [blockerClass]
  22179. },
  22180. events: blockerEvents
  22181. }));
  22182. var SnapSchema = optionObjOf('snaps', [
  22183. required$1('getSnapPoints'),
  22184. onHandler('onSensor'),
  22185. required$1('leftAttr'),
  22186. required$1('topAttr'),
  22187. defaulted('lazyViewport', win),
  22188. defaulted('mustSnap', false)
  22189. ]);
  22190. const schema$6 = [
  22191. defaulted('useFixed', never),
  22192. required$1('blockerClass'),
  22193. defaulted('getTarget', identity),
  22194. defaulted('onDrag', noop),
  22195. defaulted('repositionTarget', true),
  22196. defaulted('onDrop', noop),
  22197. defaultedFunction('getBounds', win),
  22198. SnapSchema
  22199. ];
  22200. const getCurrentCoord = target => lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), (left, top, position) => {
  22201. const nu = position === 'fixed' ? fixed : offset;
  22202. return nu(parseInt(left, 10), parseInt(top, 10));
  22203. }).getOrThunk(() => {
  22204. const location = absolute$3(target);
  22205. return absolute(location.left, location.top);
  22206. });
  22207. const clampCoords = (component, coords, scroll, origin, startData) => {
  22208. const bounds = startData.bounds;
  22209. const absoluteCoord = asAbsolute(coords, scroll, origin);
  22210. const newX = clamp(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
  22211. const newY = clamp(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
  22212. const newCoords = absolute(newX, newY);
  22213. return coords.fold(() => {
  22214. const offset$1 = asOffset(newCoords, scroll, origin);
  22215. return offset(offset$1.left, offset$1.top);
  22216. }, constant$1(newCoords), () => {
  22217. const fixed$1 = asFixed(newCoords, scroll, origin);
  22218. return fixed(fixed$1.left, fixed$1.top);
  22219. });
  22220. };
  22221. const calcNewCoord = (component, optSnaps, currentCoord, scroll, origin, delta, startData) => {
  22222. const newCoord = optSnaps.fold(() => {
  22223. const translated = translate(currentCoord, delta.left, delta.top);
  22224. const fixedCoord = asFixed(translated, scroll, origin);
  22225. return fixed(fixedCoord.left, fixedCoord.top);
  22226. }, snapInfo => {
  22227. const snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  22228. snapping.extra.each(extra => {
  22229. snapInfo.onSensor(component, extra);
  22230. });
  22231. return snapping.coord;
  22232. });
  22233. return clampCoords(component, newCoord, scroll, origin, startData);
  22234. };
  22235. const dragBy = (component, dragConfig, startData, delta) => {
  22236. const target = dragConfig.getTarget(component.element);
  22237. if (dragConfig.repositionTarget) {
  22238. const doc = owner$4(component.element);
  22239. const scroll = get$b(doc);
  22240. const origin = getOrigin(target);
  22241. const currentCoord = getCurrentCoord(target);
  22242. const newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll, origin, delta, startData);
  22243. const styles = toStyles(newCoord, scroll, origin);
  22244. setOptions(target, styles);
  22245. }
  22246. dragConfig.onDrag(component, target, delta);
  22247. };
  22248. const calcStartData = (dragConfig, comp) => ({
  22249. bounds: dragConfig.getBounds(),
  22250. height: getOuter$2(comp.element),
  22251. width: getOuter$1(comp.element)
  22252. });
  22253. const move = (component, dragConfig, dragState, dragMode, event) => {
  22254. const delta = dragState.update(dragMode, event);
  22255. const dragStartData = dragState.getStartData().getOrThunk(() => calcStartData(dragConfig, component));
  22256. delta.each(dlt => {
  22257. dragBy(component, dragConfig, dragStartData, dlt);
  22258. });
  22259. };
  22260. const stop = (component, blocker, dragConfig, dragState) => {
  22261. blocker.each(discard);
  22262. dragConfig.snaps.each(snapInfo => {
  22263. stopDrag(component, snapInfo);
  22264. });
  22265. const target = dragConfig.getTarget(component.element);
  22266. dragState.reset();
  22267. dragConfig.onDrop(component, target);
  22268. };
  22269. const handlers = events => (dragConfig, dragState) => {
  22270. const updateStartState = comp => {
  22271. dragState.setStartData(calcStartData(dragConfig, comp));
  22272. };
  22273. return derive$2([
  22274. run$1(windowScroll(), comp => {
  22275. dragState.getStartData().each(() => updateStartState(comp));
  22276. }),
  22277. ...events(dragConfig, dragState, updateStartState)
  22278. ]);
  22279. };
  22280. const init$2 = dragApi => derive$2([
  22281. run$1(mousedown(), dragApi.forceDrop),
  22282. run$1(mouseup(), dragApi.drop),
  22283. run$1(mousemove(), (comp, simulatedEvent) => {
  22284. dragApi.move(simulatedEvent.event);
  22285. }),
  22286. run$1(mouseout(), dragApi.delayDrop)
  22287. ]);
  22288. const getData$1 = event => Optional.from(SugarPosition(event.x, event.y));
  22289. const getDelta$1 = (old, nu) => SugarPosition(nu.left - old.left, nu.top - old.top);
  22290. var MouseData = /*#__PURE__*/Object.freeze({
  22291. __proto__: null,
  22292. getData: getData$1,
  22293. getDelta: getDelta$1
  22294. });
  22295. const events$2 = (dragConfig, dragState, updateStartState) => [run$1(mousedown(), (component, simulatedEvent) => {
  22296. const raw = simulatedEvent.event.raw;
  22297. if (raw.button !== 0) {
  22298. return;
  22299. }
  22300. simulatedEvent.stop();
  22301. const stop$1 = () => stop(component, Optional.some(blocker), dragConfig, dragState);
  22302. const delayDrop = DelayedFunction(stop$1, 200);
  22303. const dragApi = {
  22304. drop: stop$1,
  22305. delayDrop: delayDrop.schedule,
  22306. forceDrop: stop$1,
  22307. move: event => {
  22308. delayDrop.cancel();
  22309. move(component, dragConfig, dragState, MouseData, event);
  22310. }
  22311. };
  22312. const blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
  22313. const start = () => {
  22314. updateStartState(component);
  22315. instigate(component, blocker);
  22316. };
  22317. start();
  22318. })];
  22319. const schema$5 = [
  22320. ...schema$6,
  22321. output$1('dragger', { handlers: handlers(events$2) })
  22322. ];
  22323. const init$1 = dragApi => derive$2([
  22324. run$1(touchstart(), dragApi.forceDrop),
  22325. run$1(touchend(), dragApi.drop),
  22326. run$1(touchcancel(), dragApi.drop),
  22327. run$1(touchmove(), (comp, simulatedEvent) => {
  22328. dragApi.move(simulatedEvent.event);
  22329. })
  22330. ]);
  22331. const getDataFrom = touches => {
  22332. const touch = touches[0];
  22333. return Optional.some(SugarPosition(touch.clientX, touch.clientY));
  22334. };
  22335. const getData = event => {
  22336. const raw = event.raw;
  22337. const touches = raw.touches;
  22338. return touches.length === 1 ? getDataFrom(touches) : Optional.none();
  22339. };
  22340. const getDelta = (old, nu) => SugarPosition(nu.left - old.left, nu.top - old.top);
  22341. var TouchData = /*#__PURE__*/Object.freeze({
  22342. __proto__: null,
  22343. getData: getData,
  22344. getDelta: getDelta
  22345. });
  22346. const events$1 = (dragConfig, dragState, updateStartState) => {
  22347. const blockerSingleton = value$2();
  22348. const stopBlocking = component => {
  22349. stop(component, blockerSingleton.get(), dragConfig, dragState);
  22350. blockerSingleton.clear();
  22351. };
  22352. return [
  22353. run$1(touchstart(), (component, simulatedEvent) => {
  22354. simulatedEvent.stop();
  22355. const stop = () => stopBlocking(component);
  22356. const dragApi = {
  22357. drop: stop,
  22358. delayDrop: noop,
  22359. forceDrop: stop,
  22360. move: event => {
  22361. move(component, dragConfig, dragState, TouchData, event);
  22362. }
  22363. };
  22364. const blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
  22365. blockerSingleton.set(blocker);
  22366. const start = () => {
  22367. updateStartState(component);
  22368. instigate(component, blocker);
  22369. };
  22370. start();
  22371. }),
  22372. run$1(touchmove(), (component, simulatedEvent) => {
  22373. simulatedEvent.stop();
  22374. move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
  22375. }),
  22376. run$1(touchend(), (component, simulatedEvent) => {
  22377. simulatedEvent.stop();
  22378. stopBlocking(component);
  22379. }),
  22380. run$1(touchcancel(), stopBlocking)
  22381. ];
  22382. };
  22383. const schema$4 = [
  22384. ...schema$6,
  22385. output$1('dragger', { handlers: handlers(events$1) })
  22386. ];
  22387. const events = (dragConfig, dragState, updateStartState) => [
  22388. ...events$2(dragConfig, dragState, updateStartState),
  22389. ...events$1(dragConfig, dragState, updateStartState)
  22390. ];
  22391. const schema$3 = [
  22392. ...schema$6,
  22393. output$1('dragger', { handlers: handlers(events) })
  22394. ];
  22395. const mouse = schema$5;
  22396. const touch = schema$4;
  22397. const mouseOrTouch = schema$3;
  22398. var DraggingBranches = /*#__PURE__*/Object.freeze({
  22399. __proto__: null,
  22400. mouse: mouse,
  22401. touch: touch,
  22402. mouseOrTouch: mouseOrTouch
  22403. });
  22404. const init = () => {
  22405. let previous = Optional.none();
  22406. let startData = Optional.none();
  22407. const reset = () => {
  22408. previous = Optional.none();
  22409. startData = Optional.none();
  22410. };
  22411. const calculateDelta = (mode, nu) => {
  22412. const result = previous.map(old => mode.getDelta(old, nu));
  22413. previous = Optional.some(nu);
  22414. return result;
  22415. };
  22416. const update = (mode, dragEvent) => mode.getData(dragEvent).bind(nuData => calculateDelta(mode, nuData));
  22417. const setStartData = data => {
  22418. startData = Optional.some(data);
  22419. };
  22420. const getStartData = () => startData;
  22421. const readState = constant$1({});
  22422. return nu$8({
  22423. readState,
  22424. reset,
  22425. update,
  22426. getStartData,
  22427. setStartData
  22428. });
  22429. };
  22430. var DragState = /*#__PURE__*/Object.freeze({
  22431. __proto__: null,
  22432. init: init
  22433. });
  22434. const Dragging = createModes({
  22435. branchKey: 'mode',
  22436. branches: DraggingBranches,
  22437. name: 'dragging',
  22438. active: {
  22439. events: (dragConfig, dragState) => {
  22440. const dragger = dragConfig.dragger;
  22441. return dragger.handlers(dragConfig, dragState);
  22442. }
  22443. },
  22444. extra: {
  22445. snap: sConfig => ({
  22446. sensor: sConfig.sensor,
  22447. range: sConfig.range,
  22448. output: sConfig.output,
  22449. extra: Optional.from(sConfig.extra)
  22450. })
  22451. },
  22452. state: DragState,
  22453. apis: DraggingApis
  22454. });
  22455. const snapWidth = 40;
  22456. const snapOffset = snapWidth / 2;
  22457. const calcSnap = (selectorOpt, td, x, y, width, height) => selectorOpt.fold(() => Dragging.snap({
  22458. sensor: absolute(x - snapOffset, y - snapOffset),
  22459. range: SugarPosition(width, height),
  22460. output: absolute(Optional.some(x), Optional.some(y)),
  22461. extra: { td }
  22462. }), selectorHandle => {
  22463. const sensorLeft = x - snapOffset;
  22464. const sensorTop = y - snapOffset;
  22465. const sensorWidth = snapWidth;
  22466. const sensorHeight = snapWidth;
  22467. const rect = selectorHandle.element.dom.getBoundingClientRect();
  22468. return Dragging.snap({
  22469. sensor: absolute(sensorLeft, sensorTop),
  22470. range: SugarPosition(sensorWidth, sensorHeight),
  22471. output: absolute(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
  22472. extra: { td }
  22473. });
  22474. });
  22475. const getSnapsConfig = (getSnapPoints, cell, onChange) => {
  22476. const isSameCell = (cellOpt, td) => cellOpt.exists(currentTd => eq(currentTd, td));
  22477. return {
  22478. getSnapPoints,
  22479. leftAttr: 'data-drag-left',
  22480. topAttr: 'data-drag-top',
  22481. onSensor: (component, extra) => {
  22482. const td = extra.td;
  22483. if (!isSameCell(cell.get(), td)) {
  22484. cell.set(td);
  22485. onChange(td);
  22486. }
  22487. },
  22488. mustSnap: true
  22489. };
  22490. };
  22491. const createSelector = snaps => record(Button.sketch({
  22492. dom: {
  22493. tag: 'div',
  22494. classes: ['tox-selector']
  22495. },
  22496. buttonBehaviours: derive$1([
  22497. Dragging.config({
  22498. mode: 'mouseOrTouch',
  22499. blockerClass: 'blocker',
  22500. snaps
  22501. }),
  22502. Unselecting.config({})
  22503. ]),
  22504. eventOrder: {
  22505. mousedown: [
  22506. 'dragging',
  22507. 'alloy.base.behaviour'
  22508. ],
  22509. touchstart: [
  22510. 'dragging',
  22511. 'alloy.base.behaviour'
  22512. ]
  22513. }
  22514. }));
  22515. const setup$4 = (editor, sink) => {
  22516. const tlTds = Cell([]);
  22517. const brTds = Cell([]);
  22518. const isVisible = Cell(false);
  22519. const startCell = value$2();
  22520. const finishCell = value$2();
  22521. const getTopLeftSnap = td => {
  22522. const box = absolute$2(td);
  22523. return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  22524. };
  22525. const getTopLeftSnaps = () => map$2(tlTds.get(), td => getTopLeftSnap(td));
  22526. const getBottomRightSnap = td => {
  22527. const box = absolute$2(td);
  22528. return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  22529. };
  22530. const getBottomRightSnaps = () => map$2(brTds.get(), td => getBottomRightSnap(td));
  22531. const topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, start => {
  22532. finishCell.get().each(finish => {
  22533. editor.dispatch('TableSelectorChange', {
  22534. start,
  22535. finish
  22536. });
  22537. });
  22538. });
  22539. const bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, finish => {
  22540. startCell.get().each(start => {
  22541. editor.dispatch('TableSelectorChange', {
  22542. start,
  22543. finish
  22544. });
  22545. });
  22546. });
  22547. const memTopLeft = createSelector(topLeftSnaps);
  22548. const memBottomRight = createSelector(bottomRightSnaps);
  22549. const topLeft = build$1(memTopLeft.asSpec());
  22550. const bottomRight = build$1(memBottomRight.asSpec());
  22551. const showOrHideHandle = (selector, cell, isAbove, isBelow) => {
  22552. const cellRect = cell.dom.getBoundingClientRect();
  22553. remove$6(selector.element, 'display');
  22554. const viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
  22555. const aboveViewport = isAbove(cellRect);
  22556. const belowViewport = isBelow(cellRect, viewportHeight);
  22557. if (aboveViewport || belowViewport) {
  22558. set$8(selector.element, 'display', 'none');
  22559. }
  22560. };
  22561. const snapTo = (selector, cell, getSnapConfig, pos) => {
  22562. const snap = getSnapConfig(cell);
  22563. Dragging.snapTo(selector, snap);
  22564. const isAbove = rect => rect[pos] < 0;
  22565. const isBelow = (rect, viewportHeight) => rect[pos] > viewportHeight;
  22566. showOrHideHandle(selector, cell, isAbove, isBelow);
  22567. };
  22568. const snapTopLeft = cell => snapTo(topLeft, cell, getTopLeftSnap, 'top');
  22569. const snapLastTopLeft = () => startCell.get().each(snapTopLeft);
  22570. const snapBottomRight = cell => snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  22571. const snapLastBottomRight = () => finishCell.get().each(snapBottomRight);
  22572. if (detect$1().deviceType.isTouch()) {
  22573. editor.on('TableSelectionChange', e => {
  22574. if (!isVisible.get()) {
  22575. attach(sink, topLeft);
  22576. attach(sink, bottomRight);
  22577. isVisible.set(true);
  22578. }
  22579. startCell.set(e.start);
  22580. finishCell.set(e.finish);
  22581. e.otherCells.each(otherCells => {
  22582. tlTds.set(otherCells.upOrLeftCells);
  22583. brTds.set(otherCells.downOrRightCells);
  22584. snapTopLeft(e.start);
  22585. snapBottomRight(e.finish);
  22586. });
  22587. });
  22588. editor.on('ResizeEditor ResizeWindow ScrollContent', () => {
  22589. snapLastTopLeft();
  22590. snapLastBottomRight();
  22591. });
  22592. editor.on('TableSelectionClear', () => {
  22593. if (isVisible.get()) {
  22594. detach(topLeft);
  22595. detach(bottomRight);
  22596. isVisible.set(false);
  22597. }
  22598. startCell.clear();
  22599. finishCell.clear();
  22600. });
  22601. }
  22602. };
  22603. var Logo = "<svg width=\"50px\" height=\"16px\" viewBox=\"0 0 50 16\" xmlns=\"http://www.w3.org/2000/svg\">\n <path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M10.143 0c2.608.015 5.186 2.178 5.186 5.331 0 0 .077 3.812-.084 4.87-.361 2.41-2.164 4.074-4.65 4.496-1.453.284-2.523.49-3.212.623-.373.071-.634.122-.785.152-.184.038-.997.145-1.35.145-2.732 0-5.21-2.04-5.248-5.33 0 0 0-3.514.03-4.442.093-2.4 1.758-4.342 4.926-4.963 0 0 3.875-.752 4.036-.782.368-.07.775-.1 1.15-.1Zm1.826 2.8L5.83 3.989v2.393l-2.455.475v5.968l6.137-1.189V9.243l2.456-.476V2.8ZM5.83 6.382l3.682-.713v3.574l-3.682.713V6.382Zm27.173-1.64-.084-1.066h-2.226v9.132h2.456V7.743c-.008-1.151.998-2.064 2.149-2.072 1.15-.008 1.987.92 1.995 2.072v5.065h2.455V7.359c-.015-2.18-1.657-3.929-3.837-3.913a3.993 3.993 0 0 0-2.908 1.296Zm-6.3-4.266L29.16 0v2.387l-2.456.475V.476Zm0 3.2v9.132h2.456V3.676h-2.456Zm18.179 11.787L49.11 3.676H46.58l-1.612 4.527-.46 1.382-.384-1.382-1.611-4.527H39.98l3.3 9.132L42.15 16l2.732-.537ZM22.867 9.738c0 .752.568 1.075.921 1.075.353 0 .668-.047.998-.154l.537 1.765c-.23.154-.92.537-2.225.537-1.305 0-2.655-.997-2.686-2.686a136.877 136.877 0 0 1 0-4.374H18.8V3.676h1.612v-1.98l2.455-.476v2.456h2.302V5.9h-2.302v3.837Z\"/>\n</svg>\n";
  22604. const isHidden = elm => elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus') || elm.getAttribute('data-mce-type') === 'bookmark';
  22605. const renderElementPath = (editor, settings, providersBackstage) => {
  22606. var _a;
  22607. const delimiter = (_a = settings.delimiter) !== null && _a !== void 0 ? _a : '\u203A';
  22608. const renderElement = (name, element, index) => Button.sketch({
  22609. dom: {
  22610. tag: 'div',
  22611. classes: ['tox-statusbar__path-item'],
  22612. attributes: {
  22613. 'data-index': index,
  22614. 'aria-level': index + 1
  22615. }
  22616. },
  22617. components: [text$1(name)],
  22618. action: _btn => {
  22619. editor.focus();
  22620. editor.selection.select(element);
  22621. editor.nodeChanged();
  22622. },
  22623. buttonBehaviours: derive$1([
  22624. DisablingConfigs.button(providersBackstage.isDisabled),
  22625. receivingConfig()
  22626. ])
  22627. });
  22628. const renderDivider = () => ({
  22629. dom: {
  22630. tag: 'div',
  22631. classes: ['tox-statusbar__path-divider'],
  22632. attributes: { 'aria-hidden': true }
  22633. },
  22634. components: [text$1(` ${ delimiter } `)]
  22635. });
  22636. const renderPathData = data => foldl(data, (acc, path, index) => {
  22637. const element = renderElement(path.name, path.element, index);
  22638. if (index === 0) {
  22639. return acc.concat([element]);
  22640. } else {
  22641. return acc.concat([
  22642. renderDivider(),
  22643. element
  22644. ]);
  22645. }
  22646. }, []);
  22647. const updatePath = parents => {
  22648. const newPath = [];
  22649. let i = parents.length;
  22650. while (i-- > 0) {
  22651. const parent = parents[i];
  22652. if (parent.nodeType === 1 && !isHidden(parent)) {
  22653. const args = editor.dispatch('ResolveName', {
  22654. name: parent.nodeName.toLowerCase(),
  22655. target: parent
  22656. });
  22657. if (!args.isDefaultPrevented()) {
  22658. newPath.push({
  22659. name: args.name,
  22660. element: parent
  22661. });
  22662. }
  22663. if (args.isPropagationStopped()) {
  22664. break;
  22665. }
  22666. }
  22667. }
  22668. return newPath;
  22669. };
  22670. return {
  22671. dom: {
  22672. tag: 'div',
  22673. classes: ['tox-statusbar__path'],
  22674. attributes: { role: 'navigation' }
  22675. },
  22676. behaviours: derive$1([
  22677. Keying.config({
  22678. mode: 'flow',
  22679. selector: 'div[role=button]'
  22680. }),
  22681. Disabling.config({ disabled: providersBackstage.isDisabled }),
  22682. receivingConfig(),
  22683. Tabstopping.config({}),
  22684. Replacing.config({}),
  22685. config('elementPathEvents', [runOnAttached((comp, _e) => {
  22686. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', () => Keying.focusIn(comp));
  22687. editor.on('NodeChange', e => {
  22688. const newPath = updatePath(e.parents);
  22689. const newChildren = newPath.length > 0 ? renderPathData(newPath) : [];
  22690. Replacing.set(comp, newChildren);
  22691. });
  22692. })])
  22693. ]),
  22694. components: []
  22695. };
  22696. };
  22697. var ResizeTypes;
  22698. (function (ResizeTypes) {
  22699. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  22700. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  22701. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  22702. }(ResizeTypes || (ResizeTypes = {})));
  22703. const getDimensions = (editor, deltas, resizeType, originalHeight, originalWidth) => {
  22704. const dimensions = {};
  22705. dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightOption(editor), getMaxHeightOption(editor));
  22706. if (resizeType === ResizeTypes.Both) {
  22707. dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthOption(editor), getMaxWidthOption(editor));
  22708. }
  22709. return dimensions;
  22710. };
  22711. const resize = (editor, deltas, resizeType) => {
  22712. const container = SugarElement.fromDom(editor.getContainer());
  22713. const dimensions = getDimensions(editor, deltas, resizeType, get$d(container), get$c(container));
  22714. each(dimensions, (val, dim) => set$8(container, dim, numToPx(val)));
  22715. fireResizeEditor(editor);
  22716. };
  22717. const getResizeType = editor => {
  22718. const resize = getResize(editor);
  22719. if (resize === false) {
  22720. return ResizeTypes.None;
  22721. } else if (resize === 'both') {
  22722. return ResizeTypes.Both;
  22723. } else {
  22724. return ResizeTypes.Vertical;
  22725. }
  22726. };
  22727. const keyboardHandler = (editor, resizeType, x, y) => {
  22728. const scale = 20;
  22729. const delta = SugarPosition(x * scale, y * scale);
  22730. resize(editor, delta, resizeType);
  22731. return Optional.some(true);
  22732. };
  22733. const renderResizeHandler = (editor, providersBackstage) => {
  22734. const resizeType = getResizeType(editor);
  22735. if (resizeType === ResizeTypes.None) {
  22736. return Optional.none();
  22737. }
  22738. return Optional.some(render$3('resize-handle', {
  22739. tag: 'div',
  22740. classes: ['tox-statusbar__resize-handle'],
  22741. attributes: { title: providersBackstage.translate('Resize') },
  22742. behaviours: [
  22743. Dragging.config({
  22744. mode: 'mouse',
  22745. repositionTarget: false,
  22746. onDrag: (_comp, _target, delta) => resize(editor, delta, resizeType),
  22747. blockerClass: 'tox-blocker'
  22748. }),
  22749. Keying.config({
  22750. mode: 'special',
  22751. onLeft: () => keyboardHandler(editor, resizeType, -1, 0),
  22752. onRight: () => keyboardHandler(editor, resizeType, 1, 0),
  22753. onUp: () => keyboardHandler(editor, resizeType, 0, -1),
  22754. onDown: () => keyboardHandler(editor, resizeType, 0, 1)
  22755. }),
  22756. Tabstopping.config({}),
  22757. Focusing.config({})
  22758. ]
  22759. }, providersBackstage.icons));
  22760. };
  22761. const renderWordCount = (editor, providersBackstage) => {
  22762. const replaceCountText = (comp, count, mode) => Replacing.set(comp, [text$1(providersBackstage.translate([
  22763. '{0} ' + mode,
  22764. count[mode]
  22765. ]))]);
  22766. return Button.sketch({
  22767. dom: {
  22768. tag: 'button',
  22769. classes: ['tox-statusbar__wordcount']
  22770. },
  22771. components: [],
  22772. buttonBehaviours: derive$1([
  22773. DisablingConfigs.button(providersBackstage.isDisabled),
  22774. receivingConfig(),
  22775. Tabstopping.config({}),
  22776. Replacing.config({}),
  22777. Representing.config({
  22778. store: {
  22779. mode: 'memory',
  22780. initialValue: {
  22781. mode: 'words',
  22782. count: {
  22783. words: 0,
  22784. characters: 0
  22785. }
  22786. }
  22787. }
  22788. }),
  22789. config('wordcount-events', [
  22790. runOnExecute$1(comp => {
  22791. const currentVal = Representing.getValue(comp);
  22792. const newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  22793. Representing.setValue(comp, {
  22794. mode: newMode,
  22795. count: currentVal.count
  22796. });
  22797. replaceCountText(comp, currentVal.count, newMode);
  22798. }),
  22799. runOnAttached(comp => {
  22800. editor.on('wordCountUpdate', e => {
  22801. const {mode} = Representing.getValue(comp);
  22802. Representing.setValue(comp, {
  22803. mode,
  22804. count: e.wordCount
  22805. });
  22806. replaceCountText(comp, e.wordCount, mode);
  22807. });
  22808. })
  22809. ])
  22810. ]),
  22811. eventOrder: {
  22812. [execute$5()]: [
  22813. 'disabling',
  22814. 'alloy.base.behaviour',
  22815. 'wordcount-events'
  22816. ]
  22817. }
  22818. });
  22819. };
  22820. const renderStatusbar = (editor, providersBackstage) => {
  22821. const renderBranding = () => {
  22822. return {
  22823. dom: {
  22824. tag: 'span',
  22825. classes: ['tox-statusbar__branding']
  22826. },
  22827. components: [{
  22828. dom: {
  22829. tag: 'a',
  22830. attributes: {
  22831. 'href': 'https://www.tiny.cloud/powered-by-tiny?utm_campaign=editor_referral&utm_medium=poweredby&utm_source=tinymce&utm_content=v6',
  22832. 'rel': 'noopener',
  22833. 'target': '_blank',
  22834. 'aria-label': global$8.translate([
  22835. 'Powered by {0}',
  22836. 'Tiny'
  22837. ])
  22838. },
  22839. innerHtml: Logo.trim()
  22840. },
  22841. behaviours: derive$1([Focusing.config({})])
  22842. }]
  22843. };
  22844. };
  22845. const getTextComponents = () => {
  22846. const components = [];
  22847. if (useElementPath(editor)) {
  22848. components.push(renderElementPath(editor, {}, providersBackstage));
  22849. }
  22850. if (editor.hasPlugin('wordcount')) {
  22851. components.push(renderWordCount(editor, providersBackstage));
  22852. }
  22853. if (useBranding(editor)) {
  22854. components.push(renderBranding());
  22855. }
  22856. if (components.length > 0) {
  22857. return [{
  22858. dom: {
  22859. tag: 'div',
  22860. classes: ['tox-statusbar__text-container']
  22861. },
  22862. components
  22863. }];
  22864. }
  22865. return [];
  22866. };
  22867. const getComponents = () => {
  22868. const components = getTextComponents();
  22869. const resizeHandler = renderResizeHandler(editor, providersBackstage);
  22870. return components.concat(resizeHandler.toArray());
  22871. };
  22872. return {
  22873. dom: {
  22874. tag: 'div',
  22875. classes: ['tox-statusbar']
  22876. },
  22877. components: getComponents()
  22878. };
  22879. };
  22880. const getLazyMothership = singleton => singleton.get().getOrDie('UI has not been rendered');
  22881. const setup$3 = editor => {
  22882. const isInline = editor.inline;
  22883. const mode = isInline ? Inline : Iframe;
  22884. const header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  22885. const lazySink = value$2();
  22886. const lazyOuterContainer = value$2();
  22887. const lazyMothership = value$2();
  22888. const lazyUiMothership = value$2();
  22889. const platform = detect$1();
  22890. const isTouch = platform.deviceType.isTouch();
  22891. const touchPlatformClass = 'tox-platform-touch';
  22892. const deviceClasses = isTouch ? [touchPlatformClass] : [];
  22893. const isToolbarBottom = isToolbarLocationBottom(editor);
  22894. const toolbarMode = getToolbarMode(editor);
  22895. const memAnchorBar = record({
  22896. dom: {
  22897. tag: 'div',
  22898. classes: ['tox-anchorbar']
  22899. }
  22900. });
  22901. const lazyHeader = () => lazyOuterContainer.get().bind(OuterContainer.getHeader);
  22902. const lazySinkResult = () => Result.fromOption(lazySink.get(), 'UI has not been rendered');
  22903. const lazyAnchorBar = () => lazyOuterContainer.get().bind(container => memAnchorBar.getOpt(container)).getOrDie('Could not find a anchor bar element');
  22904. const lazyToolbar = () => lazyOuterContainer.get().bind(container => OuterContainer.getToolbar(container)).getOrDie('Could not find more toolbar element');
  22905. const lazyThrobber = () => lazyOuterContainer.get().bind(container => OuterContainer.getThrobber(container)).getOrDie('Could not find throbber element');
  22906. const backstage = init$7(lazySinkResult, editor, lazyAnchorBar);
  22907. const makeHeaderPart = () => {
  22908. const verticalDirAttributes = { attributes: { [Attribute]: isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom } };
  22909. const partMenubar = OuterContainer.parts.menubar({
  22910. dom: {
  22911. tag: 'div',
  22912. classes: ['tox-menubar']
  22913. },
  22914. backstage,
  22915. onEscape: () => {
  22916. editor.focus();
  22917. }
  22918. });
  22919. const partToolbar = OuterContainer.parts.toolbar({
  22920. dom: {
  22921. tag: 'div',
  22922. classes: ['tox-toolbar']
  22923. },
  22924. getSink: lazySinkResult,
  22925. providers: backstage.shared.providers,
  22926. onEscape: () => {
  22927. editor.focus();
  22928. },
  22929. type: toolbarMode,
  22930. lazyToolbar,
  22931. lazyHeader: () => lazyHeader().getOrDie('Could not find header element'),
  22932. ...verticalDirAttributes
  22933. });
  22934. const partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
  22935. dom: {
  22936. tag: 'div',
  22937. classes: ['tox-toolbar-overlord']
  22938. },
  22939. providers: backstage.shared.providers,
  22940. onEscape: () => {
  22941. editor.focus();
  22942. },
  22943. type: toolbarMode
  22944. });
  22945. const hasMultipleToolbar = isMultipleToolbars(editor);
  22946. const hasToolbar = isToolbarEnabled(editor);
  22947. const hasMenubar = isMenubarEnabled(editor);
  22948. const getPartToolbar = () => {
  22949. if (hasMultipleToolbar) {
  22950. return [partMultipleToolbar];
  22951. } else if (hasToolbar) {
  22952. return [partToolbar];
  22953. } else {
  22954. return [];
  22955. }
  22956. };
  22957. return OuterContainer.parts.header({
  22958. dom: {
  22959. tag: 'div',
  22960. classes: ['tox-editor-header'],
  22961. ...verticalDirAttributes
  22962. },
  22963. components: flatten([
  22964. hasMenubar ? [partMenubar] : [],
  22965. getPartToolbar(),
  22966. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  22967. ]),
  22968. sticky: isStickyToolbar(editor),
  22969. editor,
  22970. sharedBackstage: backstage.shared
  22971. });
  22972. };
  22973. const makeSidebarDefinition = () => {
  22974. const partSocket = OuterContainer.parts.socket({
  22975. dom: {
  22976. tag: 'div',
  22977. classes: ['tox-edit-area']
  22978. }
  22979. });
  22980. const partSidebar = OuterContainer.parts.sidebar({
  22981. dom: {
  22982. tag: 'div',
  22983. classes: ['tox-sidebar']
  22984. }
  22985. });
  22986. return {
  22987. dom: {
  22988. tag: 'div',
  22989. classes: ['tox-sidebar-wrap']
  22990. },
  22991. components: [
  22992. partSocket,
  22993. partSidebar
  22994. ]
  22995. };
  22996. };
  22997. const renderSink = () => {
  22998. const uiContainer = getUiContainer(editor);
  22999. const isGridUiContainer = eq(body(), uiContainer) && get$e(uiContainer, 'display') === 'grid';
  23000. const sinkSpec = {
  23001. dom: {
  23002. tag: 'div',
  23003. classes: [
  23004. 'tox',
  23005. 'tox-silver-sink',
  23006. 'tox-tinymce-aux'
  23007. ].concat(deviceClasses),
  23008. attributes: { ...global$8.isRtl() ? { dir: 'rtl' } : {} }
  23009. },
  23010. behaviours: derive$1([Positioning.config({ useFixed: () => header.isDocked(lazyHeader) })])
  23011. };
  23012. const reactiveWidthSpec = {
  23013. dom: { styles: { width: document.body.clientWidth + 'px' } },
  23014. events: derive$2([run$1(windowResize(), comp => {
  23015. set$8(comp.element, 'width', document.body.clientWidth + 'px');
  23016. })])
  23017. };
  23018. const sink = build$1(deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {}));
  23019. const uiMothership = takeover(sink);
  23020. lazySink.set(sink);
  23021. lazyUiMothership.set(uiMothership);
  23022. return {
  23023. sink,
  23024. uiMothership
  23025. };
  23026. };
  23027. const renderContainer = () => {
  23028. const partHeader = makeHeaderPart();
  23029. const sidebarContainer = makeSidebarDefinition();
  23030. const partThrobber = OuterContainer.parts.throbber({
  23031. dom: {
  23032. tag: 'div',
  23033. classes: ['tox-throbber']
  23034. },
  23035. backstage
  23036. });
  23037. const statusbar = useStatusBar(editor) && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
  23038. const editorComponents = flatten([
  23039. isToolbarBottom ? [] : [partHeader],
  23040. isInline ? [] : [sidebarContainer],
  23041. isToolbarBottom ? [partHeader] : []
  23042. ]);
  23043. const editorContainer = {
  23044. dom: {
  23045. tag: 'div',
  23046. classes: ['tox-editor-container']
  23047. },
  23048. components: editorComponents
  23049. };
  23050. const containerComponents = flatten([
  23051. [editorContainer],
  23052. isInline ? [] : statusbar.toArray(),
  23053. [partThrobber]
  23054. ]);
  23055. const isHidden = isDistractionFree(editor);
  23056. const attributes = {
  23057. role: 'application',
  23058. ...global$8.isRtl() ? { dir: 'rtl' } : {},
  23059. ...isHidden ? { 'aria-hidden': 'true' } : {}
  23060. };
  23061. const outerContainer = build$1(OuterContainer.sketch({
  23062. dom: {
  23063. tag: 'div',
  23064. classes: [
  23065. 'tox',
  23066. 'tox-tinymce'
  23067. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses),
  23068. styles: {
  23069. visibility: 'hidden',
  23070. ...isHidden ? {
  23071. opacity: '0',
  23072. border: '0'
  23073. } : {}
  23074. },
  23075. attributes
  23076. },
  23077. components: containerComponents,
  23078. behaviours: derive$1([
  23079. receivingConfig(),
  23080. Disabling.config({ disableClass: 'tox-tinymce--disabled' }),
  23081. Keying.config({
  23082. mode: 'cyclic',
  23083. 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, .tox-statusbar__resize-handle'
  23084. })
  23085. ])
  23086. }));
  23087. const mothership = takeover(outerContainer);
  23088. lazyOuterContainer.set(outerContainer);
  23089. lazyMothership.set(mothership);
  23090. return {
  23091. mothership,
  23092. outerContainer
  23093. };
  23094. };
  23095. const setEditorSize = outerContainer => {
  23096. const parsedHeight = numToPx(getHeightWithFallback(editor));
  23097. const parsedWidth = numToPx(getWidthWithFallback(editor));
  23098. if (!editor.inline) {
  23099. if (isValidValue('div', 'width', parsedWidth)) {
  23100. set$8(outerContainer.element, 'width', parsedWidth);
  23101. }
  23102. if (isValidValue('div', 'height', parsedHeight)) {
  23103. set$8(outerContainer.element, 'height', parsedHeight);
  23104. } else {
  23105. set$8(outerContainer.element, 'height', '400px');
  23106. }
  23107. }
  23108. return parsedHeight;
  23109. };
  23110. const setupShortcutsAndCommands = outerContainer => {
  23111. editor.addShortcut('alt+F9', 'focus menubar', () => {
  23112. OuterContainer.focusMenubar(outerContainer);
  23113. });
  23114. editor.addShortcut('alt+F10', 'focus toolbar', () => {
  23115. OuterContainer.focusToolbar(outerContainer);
  23116. });
  23117. editor.addCommand('ToggleToolbarDrawer', () => {
  23118. OuterContainer.toggleToolbarDrawer(outerContainer);
  23119. });
  23120. editor.addQueryStateHandler('ToggleToolbarDrawer', () => OuterContainer.isToolbarDrawerToggled(outerContainer));
  23121. };
  23122. const renderUI = () => {
  23123. const {mothership, outerContainer} = renderContainer();
  23124. const {uiMothership, sink} = renderSink();
  23125. map$1(getToolbarGroups(editor), (toolbarGroupButtonConfig, name) => {
  23126. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  23127. });
  23128. const {buttons, menuItems, contextToolbars, sidebars} = editor.ui.registry.getAll();
  23129. const toolbarOpt = getMultipleToolbarsOption(editor);
  23130. const rawUiConfig = {
  23131. menuItems,
  23132. menus: getMenus(editor),
  23133. menubar: getMenubar(editor),
  23134. toolbar: toolbarOpt.getOrThunk(() => getToolbar(editor)),
  23135. allowToolbarGroups: toolbarMode === ToolbarMode$1.floating,
  23136. buttons,
  23137. sidebar: sidebars
  23138. };
  23139. setupShortcutsAndCommands(outerContainer);
  23140. setup$b(editor, mothership, uiMothership);
  23141. header.setup(editor, backstage.shared, lazyHeader);
  23142. setup$6(editor, backstage);
  23143. setup$5(editor, lazySinkResult, backstage);
  23144. setup$8(editor);
  23145. setup$7(editor, lazyThrobber, backstage.shared);
  23146. register$9(editor, contextToolbars, sink, { backstage });
  23147. setup$4(editor, sink);
  23148. const elm = editor.getElement();
  23149. const height = setEditorSize(outerContainer);
  23150. const uiComponents = {
  23151. mothership,
  23152. uiMothership,
  23153. outerContainer,
  23154. sink
  23155. };
  23156. const args = {
  23157. targetNode: elm,
  23158. height
  23159. };
  23160. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  23161. };
  23162. const getMothership = () => getLazyMothership(lazyMothership);
  23163. const getUiMothership = () => getLazyMothership(lazyUiMothership);
  23164. return {
  23165. getMothership,
  23166. getUiMothership,
  23167. backstage,
  23168. renderUI
  23169. };
  23170. };
  23171. const describedBy = (describedElement, describeElement) => {
  23172. const describeId = Optional.from(get$f(describedElement, 'id')).fold(() => {
  23173. const id = generate$6('dialog-describe');
  23174. set$9(describeElement, 'id', id);
  23175. return id;
  23176. }, identity);
  23177. set$9(describedElement, 'aria-describedby', describeId);
  23178. };
  23179. const labelledBy = (labelledElement, labelElement) => {
  23180. const labelId = getOpt(labelledElement, 'id').fold(() => {
  23181. const id = generate$6('dialog-label');
  23182. set$9(labelElement, 'id', id);
  23183. return id;
  23184. }, identity);
  23185. set$9(labelledElement, 'aria-labelledby', labelId);
  23186. };
  23187. const schema$2 = constant$1([
  23188. required$1('lazySink'),
  23189. option$3('dragBlockClass'),
  23190. defaultedFunction('getBounds', win),
  23191. defaulted('useTabstopAt', always),
  23192. defaulted('eventOrder', {}),
  23193. field('modalBehaviours', [Keying]),
  23194. onKeyboardHandler('onExecute'),
  23195. onStrictKeyboardHandler('onEscape')
  23196. ]);
  23197. const basic = { sketch: identity };
  23198. const parts$2 = constant$1([
  23199. optional({
  23200. name: 'draghandle',
  23201. overrides: (detail, spec) => {
  23202. return {
  23203. behaviours: derive$1([Dragging.config({
  23204. mode: 'mouse',
  23205. getTarget: handle => {
  23206. return ancestor(handle, '[role="dialog"]').getOr(handle);
  23207. },
  23208. 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),
  23209. getBounds: detail.getDragBounds
  23210. })])
  23211. };
  23212. }
  23213. }),
  23214. required({
  23215. schema: [required$1('dom')],
  23216. name: 'title'
  23217. }),
  23218. required({
  23219. factory: basic,
  23220. schema: [required$1('dom')],
  23221. name: 'close'
  23222. }),
  23223. required({
  23224. factory: basic,
  23225. schema: [required$1('dom')],
  23226. name: 'body'
  23227. }),
  23228. optional({
  23229. factory: basic,
  23230. schema: [required$1('dom')],
  23231. name: 'footer'
  23232. }),
  23233. external({
  23234. factory: {
  23235. sketch: (spec, detail) => ({
  23236. ...spec,
  23237. dom: detail.dom,
  23238. components: detail.components
  23239. })
  23240. },
  23241. schema: [
  23242. defaulted('dom', {
  23243. tag: 'div',
  23244. styles: {
  23245. position: 'fixed',
  23246. left: '0px',
  23247. top: '0px',
  23248. right: '0px',
  23249. bottom: '0px'
  23250. }
  23251. }),
  23252. defaulted('components', [])
  23253. ],
  23254. name: 'blocker'
  23255. })
  23256. ]);
  23257. const factory$4 = (detail, components, spec, externals) => {
  23258. const dialogComp = value$2();
  23259. const showDialog = dialog => {
  23260. dialogComp.set(dialog);
  23261. const sink = detail.lazySink(dialog).getOrDie();
  23262. const externalBlocker = externals.blocker();
  23263. const blocker = sink.getSystem().build({
  23264. ...externalBlocker,
  23265. components: externalBlocker.components.concat([premade(dialog)]),
  23266. behaviours: derive$1([
  23267. Focusing.config({}),
  23268. config('dialog-blocker-events', [runOnSource(focusin(), () => {
  23269. Keying.focusIn(dialog);
  23270. })])
  23271. ])
  23272. });
  23273. attach(sink, blocker);
  23274. Keying.focusIn(dialog);
  23275. };
  23276. const hideDialog = dialog => {
  23277. dialogComp.clear();
  23278. parent(dialog.element).each(blockerDom => {
  23279. dialog.getSystem().getByDom(blockerDom).each(blocker => {
  23280. detach(blocker);
  23281. });
  23282. });
  23283. };
  23284. const getDialogBody = dialog => getPartOrDie(dialog, detail, 'body');
  23285. const getDialogFooter = dialog => getPartOrDie(dialog, detail, 'footer');
  23286. const setBusy = (dialog, getBusySpec) => {
  23287. Blocking.block(dialog, getBusySpec);
  23288. };
  23289. const setIdle = dialog => {
  23290. Blocking.unblock(dialog);
  23291. };
  23292. const modalEventsId = generate$6('modal-events');
  23293. const eventOrder = {
  23294. ...detail.eventOrder,
  23295. [attachedToDom()]: [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || [])
  23296. };
  23297. return {
  23298. uid: detail.uid,
  23299. dom: detail.dom,
  23300. components,
  23301. apis: {
  23302. show: showDialog,
  23303. hide: hideDialog,
  23304. getBody: getDialogBody,
  23305. getFooter: getDialogFooter,
  23306. setIdle,
  23307. setBusy
  23308. },
  23309. eventOrder,
  23310. domModification: {
  23311. attributes: {
  23312. 'role': 'dialog',
  23313. 'aria-modal': 'true'
  23314. }
  23315. },
  23316. behaviours: augment(detail.modalBehaviours, [
  23317. Replacing.config({}),
  23318. Keying.config({
  23319. mode: 'cyclic',
  23320. onEnter: detail.onExecute,
  23321. onEscape: detail.onEscape,
  23322. useTabstopAt: detail.useTabstopAt
  23323. }),
  23324. Blocking.config({ getRoot: dialogComp.get }),
  23325. config(modalEventsId, [runOnAttached(c => {
  23326. labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
  23327. describedBy(c.element, getPartOrDie(c, detail, 'body').element);
  23328. })])
  23329. ])
  23330. };
  23331. };
  23332. const ModalDialog = composite({
  23333. name: 'ModalDialog',
  23334. configFields: schema$2(),
  23335. partFields: parts$2(),
  23336. factory: factory$4,
  23337. apis: {
  23338. show: (apis, dialog) => {
  23339. apis.show(dialog);
  23340. },
  23341. hide: (apis, dialog) => {
  23342. apis.hide(dialog);
  23343. },
  23344. getBody: (apis, dialog) => apis.getBody(dialog),
  23345. getFooter: (apis, dialog) => apis.getFooter(dialog),
  23346. setBusy: (apis, dialog, getBusySpec) => {
  23347. apis.setBusy(dialog, getBusySpec);
  23348. },
  23349. setIdle: (apis, dialog) => {
  23350. apis.setIdle(dialog);
  23351. }
  23352. }
  23353. });
  23354. const dialogToggleMenuItemSchema = objOf([
  23355. type,
  23356. name$1
  23357. ].concat(commonMenuItemFields));
  23358. const dialogToggleMenuItemDataProcessor = boolean;
  23359. const baseFooterButtonFields = [
  23360. generatedName('button'),
  23361. optionalIcon,
  23362. defaultedStringEnum('align', 'end', [
  23363. 'start',
  23364. 'end'
  23365. ]),
  23366. primary,
  23367. enabled,
  23368. optionStringEnum('buttonType', [
  23369. 'primary',
  23370. 'secondary'
  23371. ])
  23372. ];
  23373. const dialogFooterButtonFields = [
  23374. ...baseFooterButtonFields,
  23375. text
  23376. ];
  23377. const normalFooterButtonFields = [
  23378. requiredStringEnum('type', [
  23379. 'submit',
  23380. 'cancel',
  23381. 'custom'
  23382. ]),
  23383. ...dialogFooterButtonFields
  23384. ];
  23385. const menuFooterButtonFields = [
  23386. requiredStringEnum('type', ['menu']),
  23387. optionalText,
  23388. optionalTooltip,
  23389. optionalIcon,
  23390. requiredArrayOf('items', dialogToggleMenuItemSchema),
  23391. ...baseFooterButtonFields
  23392. ];
  23393. const dialogFooterButtonSchema = choose$1('type', {
  23394. submit: normalFooterButtonFields,
  23395. cancel: normalFooterButtonFields,
  23396. custom: normalFooterButtonFields,
  23397. menu: menuFooterButtonFields
  23398. });
  23399. const alertBannerFields = [
  23400. type,
  23401. text,
  23402. requiredStringEnum('level', [
  23403. 'info',
  23404. 'warn',
  23405. 'error',
  23406. 'success'
  23407. ]),
  23408. icon,
  23409. defaulted('url', '')
  23410. ];
  23411. const alertBannerSchema = objOf(alertBannerFields);
  23412. const createBarFields = itemsField => [
  23413. type,
  23414. itemsField
  23415. ];
  23416. const buttonFields = [
  23417. type,
  23418. text,
  23419. enabled,
  23420. generatedName('button'),
  23421. optionalIcon,
  23422. borderless,
  23423. optionStringEnum('buttonType', [
  23424. 'primary',
  23425. 'secondary',
  23426. 'toolbar'
  23427. ]),
  23428. primary
  23429. ];
  23430. const buttonSchema = objOf(buttonFields);
  23431. const formComponentFields = [
  23432. type,
  23433. name$1
  23434. ];
  23435. const formComponentWithLabelFields = formComponentFields.concat([optionalLabel]);
  23436. const checkboxFields = formComponentFields.concat([
  23437. label,
  23438. enabled
  23439. ]);
  23440. const checkboxSchema = objOf(checkboxFields);
  23441. const checkboxDataProcessor = boolean;
  23442. const collectionFields = formComponentWithLabelFields.concat([defaultedColumns('auto')]);
  23443. const collectionSchema = objOf(collectionFields);
  23444. const collectionDataProcessor = arrOfObj([
  23445. value$1,
  23446. text,
  23447. icon
  23448. ]);
  23449. const colorInputFields = formComponentWithLabelFields;
  23450. const colorInputSchema = objOf(colorInputFields);
  23451. const colorInputDataProcessor = string;
  23452. const colorPickerFields = formComponentWithLabelFields;
  23453. const colorPickerSchema = objOf(colorPickerFields);
  23454. const colorPickerDataProcessor = string;
  23455. const customEditorFields = formComponentFields.concat([
  23456. defaultedString('tag', 'textarea'),
  23457. requiredString('scriptId'),
  23458. requiredString('scriptUrl'),
  23459. defaultedPostMsg('settings', undefined)
  23460. ]);
  23461. const customEditorFieldsOld = formComponentFields.concat([
  23462. defaultedString('tag', 'textarea'),
  23463. requiredFunction('init')
  23464. ]);
  23465. const customEditorSchema = valueOf(v => asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(() => asRaw('customeditor.new', objOfOnly(customEditorFields), v)));
  23466. const customEditorDataProcessor = string;
  23467. const dropZoneFields = formComponentWithLabelFields;
  23468. const dropZoneSchema = objOf(dropZoneFields);
  23469. const dropZoneDataProcessor = arrOfVal();
  23470. const createGridFields = itemsField => [
  23471. type,
  23472. requiredNumber('columns'),
  23473. itemsField
  23474. ];
  23475. const htmlPanelFields = [
  23476. type,
  23477. requiredString('html'),
  23478. defaultedStringEnum('presets', 'presentation', [
  23479. 'presentation',
  23480. 'document'
  23481. ])
  23482. ];
  23483. const htmlPanelSchema = objOf(htmlPanelFields);
  23484. const iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  23485. const iframeSchema = objOf(iframeFields);
  23486. const iframeDataProcessor = string;
  23487. const imagePreviewSchema = objOf(formComponentFields.concat([optionString('height')]));
  23488. const imagePreviewDataProcessor = objOf([
  23489. requiredString('url'),
  23490. optionNumber('zoom'),
  23491. optionNumber('cachedWidth'),
  23492. optionNumber('cachedHeight')
  23493. ]);
  23494. const inputFields = formComponentWithLabelFields.concat([
  23495. optionString('inputMode'),
  23496. optionString('placeholder'),
  23497. defaultedBoolean('maximized', false),
  23498. enabled
  23499. ]);
  23500. const inputSchema = objOf(inputFields);
  23501. const inputDataProcessor = string;
  23502. const createLabelFields = itemsField => [
  23503. type,
  23504. label,
  23505. itemsField
  23506. ];
  23507. const listBoxSingleItemFields = [
  23508. text,
  23509. value$1
  23510. ];
  23511. const listBoxNestedItemFields = [
  23512. text,
  23513. requiredArrayOf('items', thunkOf('items', () => listBoxItemSchema))
  23514. ];
  23515. const listBoxItemSchema = oneOf([
  23516. objOf(listBoxSingleItemFields),
  23517. objOf(listBoxNestedItemFields)
  23518. ]);
  23519. const listBoxFields = formComponentWithLabelFields.concat([
  23520. requiredArrayOf('items', listBoxItemSchema),
  23521. enabled
  23522. ]);
  23523. const listBoxSchema = objOf(listBoxFields);
  23524. const listBoxDataProcessor = string;
  23525. const selectBoxFields = formComponentWithLabelFields.concat([
  23526. requiredArrayOfObj('items', [
  23527. text,
  23528. value$1
  23529. ]),
  23530. defaultedNumber('size', 1),
  23531. enabled
  23532. ]);
  23533. const selectBoxSchema = objOf(selectBoxFields);
  23534. const selectBoxDataProcessor = string;
  23535. const sizeInputFields = formComponentWithLabelFields.concat([
  23536. defaultedBoolean('constrain', true),
  23537. enabled
  23538. ]);
  23539. const sizeInputSchema = objOf(sizeInputFields);
  23540. const sizeInputDataProcessor = objOf([
  23541. requiredString('width'),
  23542. requiredString('height')
  23543. ]);
  23544. const sliderFields = formComponentFields.concat([
  23545. label,
  23546. defaultedNumber('min', 0),
  23547. defaultedNumber('max', 0)
  23548. ]);
  23549. const sliderSchema = objOf(sliderFields);
  23550. const sliderInputDataProcessor = number;
  23551. const tableFields = [
  23552. type,
  23553. requiredArrayOf('header', string),
  23554. requiredArrayOf('cells', arrOf(string))
  23555. ];
  23556. const tableSchema = objOf(tableFields);
  23557. const textAreaFields = formComponentWithLabelFields.concat([
  23558. optionString('placeholder'),
  23559. defaultedBoolean('maximized', false),
  23560. enabled
  23561. ]);
  23562. const textAreaSchema = objOf(textAreaFields);
  23563. const textAreaDataProcessor = string;
  23564. const urlInputFields = formComponentWithLabelFields.concat([
  23565. defaultedStringEnum('filetype', 'file', [
  23566. 'image',
  23567. 'media',
  23568. 'file'
  23569. ]),
  23570. enabled
  23571. ]);
  23572. const urlInputSchema = objOf(urlInputFields);
  23573. const urlInputDataProcessor = objOf([
  23574. value$1,
  23575. defaultedMeta
  23576. ]);
  23577. const createItemsField = name => field$1('items', 'items', required$2(), arrOf(valueOf(v => asRaw(`Checking item of ${ name }`, itemSchema, v).fold(sErr => Result.error(formatError(sErr)), passValue => Result.value(passValue)))));
  23578. const itemSchema = valueThunk(() => choose$2('type', {
  23579. alertbanner: alertBannerSchema,
  23580. bar: objOf(createBarFields(createItemsField('bar'))),
  23581. button: buttonSchema,
  23582. checkbox: checkboxSchema,
  23583. colorinput: colorInputSchema,
  23584. colorpicker: colorPickerSchema,
  23585. dropzone: dropZoneSchema,
  23586. grid: objOf(createGridFields(createItemsField('grid'))),
  23587. iframe: iframeSchema,
  23588. input: inputSchema,
  23589. listbox: listBoxSchema,
  23590. selectbox: selectBoxSchema,
  23591. sizeinput: sizeInputSchema,
  23592. slider: sliderSchema,
  23593. textarea: textAreaSchema,
  23594. urlinput: urlInputSchema,
  23595. customeditor: customEditorSchema,
  23596. htmlpanel: htmlPanelSchema,
  23597. imagepreview: imagePreviewSchema,
  23598. collection: collectionSchema,
  23599. label: objOf(createLabelFields(createItemsField('label'))),
  23600. table: tableSchema,
  23601. panel: panelSchema
  23602. }));
  23603. const panelFields = [
  23604. type,
  23605. defaulted('classes', []),
  23606. requiredArrayOf('items', itemSchema)
  23607. ];
  23608. const panelSchema = objOf(panelFields);
  23609. const tabFields = [
  23610. generatedName('tab'),
  23611. title,
  23612. requiredArrayOf('items', itemSchema)
  23613. ];
  23614. const tabPanelFields = [
  23615. type,
  23616. requiredArrayOfObj('tabs', tabFields)
  23617. ];
  23618. const tabPanelSchema = objOf(tabPanelFields);
  23619. const dialogButtonFields = dialogFooterButtonFields;
  23620. const dialogButtonSchema = dialogFooterButtonSchema;
  23621. const dialogSchema = objOf([
  23622. requiredString('title'),
  23623. requiredOf('body', choose$2('type', {
  23624. panel: panelSchema,
  23625. tabpanel: tabPanelSchema
  23626. })),
  23627. defaultedString('size', 'normal'),
  23628. requiredArrayOf('buttons', dialogButtonSchema),
  23629. defaulted('initialData', {}),
  23630. defaultedFunction('onAction', noop),
  23631. defaultedFunction('onChange', noop),
  23632. defaultedFunction('onSubmit', noop),
  23633. defaultedFunction('onClose', noop),
  23634. defaultedFunction('onCancel', noop),
  23635. defaultedFunction('onTabChange', noop)
  23636. ]);
  23637. const createDialog = spec => asRaw('dialog', dialogSchema, spec);
  23638. const urlDialogButtonSchema = objOf([
  23639. requiredStringEnum('type', [
  23640. 'cancel',
  23641. 'custom'
  23642. ]),
  23643. ...dialogButtonFields
  23644. ]);
  23645. const urlDialogSchema = objOf([
  23646. requiredString('title'),
  23647. requiredString('url'),
  23648. optionNumber('height'),
  23649. optionNumber('width'),
  23650. optionArrayOf('buttons', urlDialogButtonSchema),
  23651. defaultedFunction('onAction', noop),
  23652. defaultedFunction('onCancel', noop),
  23653. defaultedFunction('onClose', noop),
  23654. defaultedFunction('onMessage', noop)
  23655. ]);
  23656. const createUrlDialog = spec => asRaw('dialog', urlDialogSchema, spec);
  23657. const getAllObjects = obj => {
  23658. if (isObject(obj)) {
  23659. return [obj].concat(bind$3(values(obj), getAllObjects));
  23660. } else if (isArray(obj)) {
  23661. return bind$3(obj, getAllObjects);
  23662. } else {
  23663. return [];
  23664. }
  23665. };
  23666. const isNamedItem = obj => isString(obj.type) && isString(obj.name);
  23667. const dataProcessors = {
  23668. checkbox: checkboxDataProcessor,
  23669. colorinput: colorInputDataProcessor,
  23670. colorpicker: colorPickerDataProcessor,
  23671. dropzone: dropZoneDataProcessor,
  23672. input: inputDataProcessor,
  23673. iframe: iframeDataProcessor,
  23674. imagepreview: imagePreviewDataProcessor,
  23675. selectbox: selectBoxDataProcessor,
  23676. sizeinput: sizeInputDataProcessor,
  23677. slider: sliderInputDataProcessor,
  23678. listbox: listBoxDataProcessor,
  23679. size: sizeInputDataProcessor,
  23680. textarea: textAreaDataProcessor,
  23681. urlinput: urlInputDataProcessor,
  23682. customeditor: customEditorDataProcessor,
  23683. collection: collectionDataProcessor,
  23684. togglemenuitem: dialogToggleMenuItemDataProcessor
  23685. };
  23686. const getDataProcessor = item => Optional.from(dataProcessors[item.type]);
  23687. const getNamedItems = structure => filter$2(getAllObjects(structure), isNamedItem);
  23688. const createDataValidator = structure => {
  23689. const namedItems = getNamedItems(structure);
  23690. const fields = bind$3(namedItems, item => getDataProcessor(item).fold(() => [], schema => [requiredOf(item.name, schema)]));
  23691. return objOf(fields);
  23692. };
  23693. const extract = structure => {
  23694. const internalDialog = getOrDie(createDialog(structure));
  23695. const dataValidator = createDataValidator(structure);
  23696. const initialData = structure.initialData;
  23697. return {
  23698. internalDialog,
  23699. dataValidator,
  23700. initialData
  23701. };
  23702. };
  23703. const DialogManager = {
  23704. open: (factory, structure) => {
  23705. const extraction = extract(structure);
  23706. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  23707. },
  23708. openUrl: (factory, structure) => {
  23709. const internalDialog = getOrDie(createUrlDialog(structure));
  23710. return factory(internalDialog);
  23711. },
  23712. redial: structure => extract(structure)
  23713. };
  23714. const toValidValues = values => {
  23715. const errors = [];
  23716. const result = {};
  23717. each(values, (value, name) => {
  23718. value.fold(() => {
  23719. errors.push(name);
  23720. }, v => {
  23721. result[name] = v;
  23722. });
  23723. });
  23724. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  23725. };
  23726. const renderBodyPanel = (spec, dialogData, backstage) => {
  23727. const memForm = record(Form.sketch(parts => ({
  23728. dom: {
  23729. tag: 'div',
  23730. classes: ['tox-form'].concat(spec.classes)
  23731. },
  23732. components: map$2(spec.items, item => interpretInForm(parts, item, dialogData, backstage))
  23733. })));
  23734. return {
  23735. dom: {
  23736. tag: 'div',
  23737. classes: ['tox-dialog__body']
  23738. },
  23739. components: [{
  23740. dom: {
  23741. tag: 'div',
  23742. classes: ['tox-dialog__body-content']
  23743. },
  23744. components: [memForm.asSpec()]
  23745. }],
  23746. behaviours: derive$1([
  23747. Keying.config({
  23748. mode: 'acyclic',
  23749. useTabstopAt: not(isPseudoStop)
  23750. }),
  23751. ComposingConfigs.memento(memForm),
  23752. RepresentingConfigs.memento(memForm, {
  23753. postprocess: formValue => toValidValues(formValue).fold(err => {
  23754. console.error(err);
  23755. return {};
  23756. }, identity)
  23757. })
  23758. ])
  23759. };
  23760. };
  23761. const factory$3 = (detail, _spec) => ({
  23762. uid: detail.uid,
  23763. dom: detail.dom,
  23764. components: detail.components,
  23765. events: events$a(detail.action),
  23766. behaviours: augment(detail.tabButtonBehaviours, [
  23767. Focusing.config({}),
  23768. Keying.config({
  23769. mode: 'execution',
  23770. useSpace: true,
  23771. useEnter: true
  23772. }),
  23773. Representing.config({
  23774. store: {
  23775. mode: 'memory',
  23776. initialValue: detail.value
  23777. }
  23778. })
  23779. ]),
  23780. domModification: detail.domModification
  23781. });
  23782. const TabButton = single({
  23783. name: 'TabButton',
  23784. configFields: [
  23785. defaulted('uid', undefined),
  23786. required$1('value'),
  23787. field$1('dom', 'dom', mergeWithThunk(() => ({
  23788. attributes: {
  23789. 'role': 'tab',
  23790. 'id': generate$6('aria'),
  23791. 'aria-selected': 'false'
  23792. }
  23793. })), anyValue()),
  23794. option$3('action'),
  23795. defaulted('domModification', {}),
  23796. field('tabButtonBehaviours', [
  23797. Focusing,
  23798. Keying,
  23799. Representing
  23800. ]),
  23801. required$1('view')
  23802. ],
  23803. factory: factory$3
  23804. });
  23805. const schema$1 = constant$1([
  23806. required$1('tabs'),
  23807. required$1('dom'),
  23808. defaulted('clickToDismiss', false),
  23809. field('tabbarBehaviours', [
  23810. Highlighting,
  23811. Keying
  23812. ]),
  23813. markers$1([
  23814. 'tabClass',
  23815. 'selectedClass'
  23816. ])
  23817. ]);
  23818. const tabsPart = group({
  23819. factory: TabButton,
  23820. name: 'tabs',
  23821. unit: 'tab',
  23822. overrides: barDetail => {
  23823. const dismissTab$1 = (tabbar, button) => {
  23824. Highlighting.dehighlight(tabbar, button);
  23825. emitWith(tabbar, dismissTab(), {
  23826. tabbar,
  23827. button
  23828. });
  23829. };
  23830. const changeTab$1 = (tabbar, button) => {
  23831. Highlighting.highlight(tabbar, button);
  23832. emitWith(tabbar, changeTab(), {
  23833. tabbar,
  23834. button
  23835. });
  23836. };
  23837. return {
  23838. action: button => {
  23839. const tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  23840. const activeButton = Highlighting.isHighlighted(tabbar, button);
  23841. const response = (() => {
  23842. if (activeButton && barDetail.clickToDismiss) {
  23843. return dismissTab$1;
  23844. } else if (!activeButton) {
  23845. return changeTab$1;
  23846. } else {
  23847. return noop;
  23848. }
  23849. })();
  23850. response(tabbar, button);
  23851. },
  23852. domModification: { classes: [barDetail.markers.tabClass] }
  23853. };
  23854. }
  23855. });
  23856. const parts$1 = constant$1([tabsPart]);
  23857. const factory$2 = (detail, components, _spec, _externals) => ({
  23858. 'uid': detail.uid,
  23859. 'dom': detail.dom,
  23860. components,
  23861. 'debug.sketcher': 'Tabbar',
  23862. 'domModification': { attributes: { role: 'tablist' } },
  23863. 'behaviours': augment(detail.tabbarBehaviours, [
  23864. Highlighting.config({
  23865. highlightClass: detail.markers.selectedClass,
  23866. itemClass: detail.markers.tabClass,
  23867. onHighlight: (tabbar, tab) => {
  23868. set$9(tab.element, 'aria-selected', 'true');
  23869. },
  23870. onDehighlight: (tabbar, tab) => {
  23871. set$9(tab.element, 'aria-selected', 'false');
  23872. }
  23873. }),
  23874. Keying.config({
  23875. mode: 'flow',
  23876. getInitial: tabbar => {
  23877. return Highlighting.getHighlighted(tabbar).map(tab => tab.element);
  23878. },
  23879. selector: '.' + detail.markers.tabClass,
  23880. executeOnMove: true
  23881. })
  23882. ])
  23883. });
  23884. const Tabbar = composite({
  23885. name: 'Tabbar',
  23886. configFields: schema$1(),
  23887. partFields: parts$1(),
  23888. factory: factory$2
  23889. });
  23890. const factory$1 = (detail, _spec) => ({
  23891. uid: detail.uid,
  23892. dom: detail.dom,
  23893. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  23894. domModification: { attributes: { role: 'tabpanel' } }
  23895. });
  23896. const Tabview = single({
  23897. name: 'Tabview',
  23898. configFields: [field('tabviewBehaviours', [Replacing])],
  23899. factory: factory$1
  23900. });
  23901. const schema = constant$1([
  23902. defaulted('selectFirst', true),
  23903. onHandler('onChangeTab'),
  23904. onHandler('onDismissTab'),
  23905. defaulted('tabs', []),
  23906. field('tabSectionBehaviours', [])
  23907. ]);
  23908. const barPart = required({
  23909. factory: Tabbar,
  23910. schema: [
  23911. required$1('dom'),
  23912. requiredObjOf('markers', [
  23913. required$1('tabClass'),
  23914. required$1('selectedClass')
  23915. ])
  23916. ],
  23917. name: 'tabbar',
  23918. defaults: detail => {
  23919. return { tabs: detail.tabs };
  23920. }
  23921. });
  23922. const viewPart = required({
  23923. factory: Tabview,
  23924. name: 'tabview'
  23925. });
  23926. const parts = constant$1([
  23927. barPart,
  23928. viewPart
  23929. ]);
  23930. const factory = (detail, components, _spec, _externals) => {
  23931. const changeTab$1 = button => {
  23932. const tabValue = Representing.getValue(button);
  23933. getPart(button, detail, 'tabview').each(tabview => {
  23934. const tabWithValue = find$5(detail.tabs, t => t.value === tabValue);
  23935. tabWithValue.each(tabData => {
  23936. const panel = tabData.view();
  23937. getOpt(button.element, 'id').each(id => {
  23938. set$9(tabview.element, 'aria-labelledby', id);
  23939. });
  23940. Replacing.set(tabview, panel);
  23941. detail.onChangeTab(tabview, button, panel);
  23942. });
  23943. });
  23944. };
  23945. const changeTabBy = (section, byPred) => {
  23946. getPart(section, detail, 'tabbar').each(tabbar => {
  23947. byPred(tabbar).each(emitExecute);
  23948. });
  23949. };
  23950. return {
  23951. uid: detail.uid,
  23952. dom: detail.dom,
  23953. components,
  23954. behaviours: get$3(detail.tabSectionBehaviours),
  23955. events: derive$2(flatten([
  23956. detail.selectFirst ? [runOnAttached((section, _simulatedEvent) => {
  23957. changeTabBy(section, Highlighting.getFirst);
  23958. })] : [],
  23959. [
  23960. run$1(changeTab(), (section, simulatedEvent) => {
  23961. const button = simulatedEvent.event.button;
  23962. changeTab$1(button);
  23963. }),
  23964. run$1(dismissTab(), (section, simulatedEvent) => {
  23965. const button = simulatedEvent.event.button;
  23966. detail.onDismissTab(section, button);
  23967. })
  23968. ]
  23969. ])),
  23970. apis: {
  23971. getViewItems: section => {
  23972. return getPart(section, detail, 'tabview').map(tabview => Replacing.contents(tabview)).getOr([]);
  23973. },
  23974. showTab: (section, tabKey) => {
  23975. const getTabIfNotActive = tabbar => {
  23976. const candidates = Highlighting.getCandidates(tabbar);
  23977. const optTab = find$5(candidates, c => Representing.getValue(c) === tabKey);
  23978. return optTab.filter(tab => !Highlighting.isHighlighted(tabbar, tab));
  23979. };
  23980. changeTabBy(section, getTabIfNotActive);
  23981. }
  23982. }
  23983. };
  23984. };
  23985. const TabSection = composite({
  23986. name: 'TabSection',
  23987. configFields: schema(),
  23988. partFields: parts(),
  23989. factory,
  23990. apis: {
  23991. getViewItems: (apis, component) => apis.getViewItems(component),
  23992. showTab: (apis, component, tabKey) => {
  23993. apis.showTab(component, tabKey);
  23994. }
  23995. }
  23996. });
  23997. const measureHeights = (allTabs, tabview, tabviewComp) => map$2(allTabs, (_tab, i) => {
  23998. Replacing.set(tabviewComp, allTabs[i].view());
  23999. const rect = tabview.dom.getBoundingClientRect();
  24000. Replacing.set(tabviewComp, []);
  24001. return rect.height;
  24002. });
  24003. const getMaxHeight = heights => head(sort(heights, (a, b) => {
  24004. if (a > b) {
  24005. return -1;
  24006. } else if (a < b) {
  24007. return +1;
  24008. } else {
  24009. return 0;
  24010. }
  24011. }));
  24012. const getMaxTabviewHeight = (dialog, tabview, tablist) => {
  24013. const documentElement$1 = documentElement(dialog).dom;
  24014. const rootElm = ancestor(dialog, '.tox-dialog-wrap').getOr(dialog);
  24015. const isFixed = get$e(rootElm, 'position') === 'fixed';
  24016. let maxHeight;
  24017. if (isFixed) {
  24018. maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
  24019. } else {
  24020. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  24021. }
  24022. const tabviewHeight = get$d(tabview);
  24023. const isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$c(tablist);
  24024. const currentTabHeight = isTabListBeside ? Math.max(get$d(tablist), tabviewHeight) : tabviewHeight;
  24025. const dialogTopMargin = parseInt(get$e(dialog, 'margin-top'), 10) || 0;
  24026. const dialogBottomMargin = parseInt(get$e(dialog, 'margin-bottom'), 10) || 0;
  24027. const dialogHeight = get$d(dialog) + dialogTopMargin + dialogBottomMargin;
  24028. const chromeHeight = dialogHeight - currentTabHeight;
  24029. return maxHeight - chromeHeight;
  24030. };
  24031. const showTab = (allTabs, comp) => {
  24032. head(allTabs).each(tab => TabSection.showTab(comp, tab.value));
  24033. };
  24034. const setTabviewHeight = (tabview, height) => {
  24035. set$8(tabview, 'height', height + 'px');
  24036. set$8(tabview, 'flex-basis', height + 'px');
  24037. };
  24038. const updateTabviewHeight = (dialogBody, tabview, maxTabHeight) => {
  24039. ancestor(dialogBody, '[role="dialog"]').each(dialog => {
  24040. descendant(dialog, '[role="tablist"]').each(tablist => {
  24041. maxTabHeight.get().map(height => {
  24042. set$8(tabview, 'height', '0');
  24043. set$8(tabview, 'flex-basis', '0');
  24044. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  24045. }).each(height => {
  24046. setTabviewHeight(tabview, height);
  24047. });
  24048. });
  24049. });
  24050. };
  24051. const getTabview = dialog => descendant(dialog, '[role="tabpanel"]');
  24052. const setMode = allTabs => {
  24053. const smartTabHeight = (() => {
  24054. const maxTabHeight = value$2();
  24055. const extraEvents = [
  24056. runOnAttached(comp => {
  24057. const dialog = comp.element;
  24058. getTabview(dialog).each(tabview => {
  24059. set$8(tabview, 'visibility', 'hidden');
  24060. comp.getSystem().getByDom(tabview).toOptional().each(tabviewComp => {
  24061. const heights = measureHeights(allTabs, tabview, tabviewComp);
  24062. const maxTabHeightOpt = getMaxHeight(heights);
  24063. maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
  24064. });
  24065. updateTabviewHeight(dialog, tabview, maxTabHeight);
  24066. remove$6(tabview, 'visibility');
  24067. showTab(allTabs, comp);
  24068. requestAnimationFrame(() => {
  24069. updateTabviewHeight(dialog, tabview, maxTabHeight);
  24070. });
  24071. });
  24072. }),
  24073. run$1(windowResize(), comp => {
  24074. const dialog = comp.element;
  24075. getTabview(dialog).each(tabview => {
  24076. updateTabviewHeight(dialog, tabview, maxTabHeight);
  24077. });
  24078. }),
  24079. run$1(formResizeEvent, (comp, _se) => {
  24080. const dialog = comp.element;
  24081. getTabview(dialog).each(tabview => {
  24082. const oldFocus = active$1(getRootNode(tabview));
  24083. set$8(tabview, 'visibility', 'hidden');
  24084. const oldHeight = getRaw(tabview, 'height').map(h => parseInt(h, 10));
  24085. remove$6(tabview, 'height');
  24086. remove$6(tabview, 'flex-basis');
  24087. const newHeight = tabview.dom.getBoundingClientRect().height;
  24088. const hasGrown = oldHeight.forall(h => newHeight > h);
  24089. if (hasGrown) {
  24090. maxTabHeight.set(newHeight);
  24091. updateTabviewHeight(dialog, tabview, maxTabHeight);
  24092. } else {
  24093. oldHeight.each(h => {
  24094. setTabviewHeight(tabview, h);
  24095. });
  24096. }
  24097. remove$6(tabview, 'visibility');
  24098. oldFocus.each(focus$3);
  24099. });
  24100. })
  24101. ];
  24102. const selectFirst = false;
  24103. return {
  24104. extraEvents,
  24105. selectFirst
  24106. };
  24107. })();
  24108. const naiveTabHeight = (() => {
  24109. const extraEvents = [];
  24110. const selectFirst = true;
  24111. return {
  24112. extraEvents,
  24113. selectFirst
  24114. };
  24115. })();
  24116. return {
  24117. smartTabHeight,
  24118. naiveTabHeight
  24119. };
  24120. };
  24121. const SendDataToSectionChannel = 'send-data-to-section';
  24122. const SendDataToViewChannel = 'send-data-to-view';
  24123. const renderTabPanel = (spec, dialogData, backstage) => {
  24124. const storedValue = Cell({});
  24125. const updateDataWithForm = form => {
  24126. const formData = Representing.getValue(form);
  24127. const validData = toValidValues(formData).getOr({});
  24128. const currentData = storedValue.get();
  24129. const newData = deepMerge(currentData, validData);
  24130. storedValue.set(newData);
  24131. };
  24132. const setDataOnForm = form => {
  24133. const tabData = storedValue.get();
  24134. Representing.setValue(form, tabData);
  24135. };
  24136. const oldTab = Cell(null);
  24137. const allTabs = map$2(spec.tabs, tab => {
  24138. return {
  24139. value: tab.name,
  24140. dom: {
  24141. tag: 'div',
  24142. classes: ['tox-dialog__body-nav-item']
  24143. },
  24144. components: [text$1(backstage.shared.providers.translate(tab.title))],
  24145. view: () => {
  24146. return [Form.sketch(parts => ({
  24147. dom: {
  24148. tag: 'div',
  24149. classes: ['tox-form']
  24150. },
  24151. components: map$2(tab.items, item => interpretInForm(parts, item, dialogData, backstage)),
  24152. formBehaviours: derive$1([
  24153. Keying.config({
  24154. mode: 'acyclic',
  24155. useTabstopAt: not(isPseudoStop)
  24156. }),
  24157. config('TabView.form.events', [
  24158. runOnAttached(setDataOnForm),
  24159. runOnDetached(updateDataWithForm)
  24160. ]),
  24161. Receiving.config({
  24162. channels: wrapAll([
  24163. {
  24164. key: SendDataToSectionChannel,
  24165. value: { onReceive: updateDataWithForm }
  24166. },
  24167. {
  24168. key: SendDataToViewChannel,
  24169. value: { onReceive: setDataOnForm }
  24170. }
  24171. ])
  24172. })
  24173. ])
  24174. }))];
  24175. }
  24176. };
  24177. });
  24178. const tabMode = setMode(allTabs).smartTabHeight;
  24179. return TabSection.sketch({
  24180. dom: {
  24181. tag: 'div',
  24182. classes: ['tox-dialog__body']
  24183. },
  24184. onChangeTab: (section, button, _viewItems) => {
  24185. const name = Representing.getValue(button);
  24186. emitWith(section, formTabChangeEvent, {
  24187. name,
  24188. oldName: oldTab.get()
  24189. });
  24190. oldTab.set(name);
  24191. },
  24192. tabs: allTabs,
  24193. components: [
  24194. TabSection.parts.tabbar({
  24195. dom: {
  24196. tag: 'div',
  24197. classes: ['tox-dialog__body-nav']
  24198. },
  24199. components: [Tabbar.parts.tabs({})],
  24200. markers: {
  24201. tabClass: 'tox-tab',
  24202. selectedClass: 'tox-dialog__body-nav-item--active'
  24203. },
  24204. tabbarBehaviours: derive$1([Tabstopping.config({})])
  24205. }),
  24206. TabSection.parts.tabview({
  24207. dom: {
  24208. tag: 'div',
  24209. classes: ['tox-dialog__body-content']
  24210. }
  24211. })
  24212. ],
  24213. selectFirst: tabMode.selectFirst,
  24214. tabSectionBehaviours: derive$1([
  24215. config('tabpanel', tabMode.extraEvents),
  24216. Keying.config({ mode: 'acyclic' }),
  24217. Composing.config({ find: comp => head(TabSection.getViewItems(comp)) }),
  24218. RepresentingConfigs.withComp(Optional.none(), tsection => {
  24219. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  24220. return storedValue.get();
  24221. }, (tsection, value) => {
  24222. storedValue.set(value);
  24223. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  24224. })
  24225. ])
  24226. });
  24227. };
  24228. const dialogChannel = generate$6('update-dialog');
  24229. const titleChannel = generate$6('update-title');
  24230. const bodyChannel = generate$6('update-body');
  24231. const footerChannel = generate$6('update-footer');
  24232. const bodySendMessageChannel = generate$6('body-send-message');
  24233. const renderBody = (spec, dialogId, contentId, backstage, ariaAttrs) => {
  24234. const renderComponents = incoming => {
  24235. const body = incoming.body;
  24236. switch (body.type) {
  24237. case 'tabpanel': {
  24238. return [renderTabPanel(body, incoming.initialData, backstage)];
  24239. }
  24240. default: {
  24241. return [renderBodyPanel(body, incoming.initialData, backstage)];
  24242. }
  24243. }
  24244. };
  24245. const updateState = (_comp, incoming) => Optional.some({ isTabPanel: () => incoming.body.type === 'tabpanel' });
  24246. const ariaAttributes = { 'aria-live': 'polite' };
  24247. return {
  24248. dom: {
  24249. tag: 'div',
  24250. classes: ['tox-dialog__content-js'],
  24251. attributes: {
  24252. ...contentId.map(x => ({ id: x })).getOr({}),
  24253. ...ariaAttrs ? ariaAttributes : {}
  24254. }
  24255. },
  24256. components: [],
  24257. behaviours: derive$1([
  24258. ComposingConfigs.childAt(0),
  24259. Reflecting.config({
  24260. channel: `${ bodyChannel }-${ dialogId }`,
  24261. updateState,
  24262. renderComponents,
  24263. initialData: spec
  24264. })
  24265. ])
  24266. };
  24267. };
  24268. const renderInlineBody = (spec, dialogId, contentId, backstage, ariaAttrs) => renderBody(spec, dialogId, Optional.some(contentId), backstage, ariaAttrs);
  24269. const renderModalBody = (spec, dialogId, backstage) => {
  24270. const bodySpec = renderBody(spec, dialogId, Optional.none(), backstage, false);
  24271. return ModalDialog.parts.body(bodySpec);
  24272. };
  24273. const renderIframeBody = spec => {
  24274. const bodySpec = {
  24275. dom: {
  24276. tag: 'div',
  24277. classes: ['tox-dialog__content-js']
  24278. },
  24279. components: [{
  24280. dom: {
  24281. tag: 'div',
  24282. classes: ['tox-dialog__body-iframe']
  24283. },
  24284. components: [craft({
  24285. dom: {
  24286. tag: 'iframe',
  24287. attributes: { src: spec.url }
  24288. },
  24289. behaviours: derive$1([
  24290. Tabstopping.config({}),
  24291. Focusing.config({})
  24292. ])
  24293. })]
  24294. }],
  24295. behaviours: derive$1([Keying.config({
  24296. mode: 'acyclic',
  24297. useTabstopAt: not(isPseudoStop)
  24298. })])
  24299. };
  24300. return ModalDialog.parts.body(bodySpec);
  24301. };
  24302. const isTouch = global$5.deviceType.isTouch();
  24303. const hiddenHeader = (title, close) => ({
  24304. dom: {
  24305. tag: 'div',
  24306. styles: { display: 'none' },
  24307. classes: ['tox-dialog__header']
  24308. },
  24309. components: [
  24310. title,
  24311. close
  24312. ]
  24313. });
  24314. const pClose = (onClose, providersBackstage) => ModalDialog.parts.close(Button.sketch({
  24315. dom: {
  24316. tag: 'button',
  24317. classes: [
  24318. 'tox-button',
  24319. 'tox-button--icon',
  24320. 'tox-button--naked'
  24321. ],
  24322. attributes: {
  24323. 'type': 'button',
  24324. 'aria-label': providersBackstage.translate('Close')
  24325. }
  24326. },
  24327. action: onClose,
  24328. buttonBehaviours: derive$1([Tabstopping.config({})])
  24329. }));
  24330. const pUntitled = () => ModalDialog.parts.title({
  24331. dom: {
  24332. tag: 'div',
  24333. classes: ['tox-dialog__title'],
  24334. innerHtml: '',
  24335. styles: { display: 'none' }
  24336. }
  24337. });
  24338. const pBodyMessage = (message, providersBackstage) => ModalDialog.parts.body({
  24339. dom: {
  24340. tag: 'div',
  24341. classes: ['tox-dialog__body']
  24342. },
  24343. components: [{
  24344. dom: {
  24345. tag: 'div',
  24346. classes: ['tox-dialog__body-content']
  24347. },
  24348. components: [{ dom: fromHtml(`<p>${ providersBackstage.translate(message) }</p>`) }]
  24349. }]
  24350. });
  24351. const pFooter = buttons => ModalDialog.parts.footer({
  24352. dom: {
  24353. tag: 'div',
  24354. classes: ['tox-dialog__footer']
  24355. },
  24356. components: buttons
  24357. });
  24358. const pFooterGroup = (startButtons, endButtons) => [
  24359. Container.sketch({
  24360. dom: {
  24361. tag: 'div',
  24362. classes: ['tox-dialog__footer-start']
  24363. },
  24364. components: startButtons
  24365. }),
  24366. Container.sketch({
  24367. dom: {
  24368. tag: 'div',
  24369. classes: ['tox-dialog__footer-end']
  24370. },
  24371. components: endButtons
  24372. })
  24373. ];
  24374. const renderDialog$1 = spec => {
  24375. const dialogClass = 'tox-dialog';
  24376. const blockerClass = dialogClass + '-wrap';
  24377. const blockerBackdropClass = blockerClass + '__backdrop';
  24378. const scrollLockClass = dialogClass + '__disable-scroll';
  24379. return ModalDialog.sketch({
  24380. lazySink: spec.lazySink,
  24381. onEscape: comp => {
  24382. spec.onEscape(comp);
  24383. return Optional.some(true);
  24384. },
  24385. useTabstopAt: elem => !isPseudoStop(elem),
  24386. dom: {
  24387. tag: 'div',
  24388. classes: [dialogClass].concat(spec.extraClasses),
  24389. styles: {
  24390. position: 'relative',
  24391. ...spec.extraStyles
  24392. }
  24393. },
  24394. components: [
  24395. spec.header,
  24396. spec.body,
  24397. ...spec.footer.toArray()
  24398. ],
  24399. parts: {
  24400. blocker: {
  24401. dom: fromHtml(`<div class="${ blockerClass }"></div>`),
  24402. components: [{
  24403. dom: {
  24404. tag: 'div',
  24405. classes: isTouch ? [
  24406. blockerBackdropClass,
  24407. blockerBackdropClass + '--opaque'
  24408. ] : [blockerBackdropClass]
  24409. }
  24410. }]
  24411. }
  24412. },
  24413. dragBlockClass: blockerClass,
  24414. modalBehaviours: derive$1([
  24415. Focusing.config({}),
  24416. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), (comp, _se) => {
  24417. Keying.focusIn(comp);
  24418. })])),
  24419. config('scroll-lock', [
  24420. runOnAttached(() => {
  24421. add$2(body(), scrollLockClass);
  24422. }),
  24423. runOnDetached(() => {
  24424. remove$2(body(), scrollLockClass);
  24425. })
  24426. ]),
  24427. ...spec.extraBehaviours
  24428. ]),
  24429. eventOrder: {
  24430. [execute$5()]: ['dialog-events'],
  24431. [attachedToDom()]: [
  24432. 'scroll-lock',
  24433. 'dialog-events',
  24434. 'alloy.base.behaviour'
  24435. ],
  24436. [detachedFromDom()]: [
  24437. 'alloy.base.behaviour',
  24438. 'dialog-events',
  24439. 'scroll-lock'
  24440. ],
  24441. ...spec.eventOrder
  24442. }
  24443. });
  24444. };
  24445. const renderClose = providersBackstage => Button.sketch({
  24446. dom: {
  24447. tag: 'button',
  24448. classes: [
  24449. 'tox-button',
  24450. 'tox-button--icon',
  24451. 'tox-button--naked'
  24452. ],
  24453. attributes: {
  24454. 'type': 'button',
  24455. 'aria-label': providersBackstage.translate('Close'),
  24456. 'title': providersBackstage.translate('Close')
  24457. }
  24458. },
  24459. components: [render$3('close', {
  24460. tag: 'div',
  24461. classes: ['tox-icon']
  24462. }, providersBackstage.icons)],
  24463. action: comp => {
  24464. emit(comp, formCancelEvent);
  24465. }
  24466. });
  24467. const renderTitle = (spec, dialogId, titleId, providersBackstage) => {
  24468. const renderComponents = data => [text$1(providersBackstage.translate(data.title))];
  24469. return {
  24470. dom: {
  24471. tag: 'div',
  24472. classes: ['tox-dialog__title'],
  24473. attributes: { ...titleId.map(x => ({ id: x })).getOr({}) }
  24474. },
  24475. components: [],
  24476. behaviours: derive$1([Reflecting.config({
  24477. channel: `${ titleChannel }-${ dialogId }`,
  24478. initialData: spec,
  24479. renderComponents
  24480. })])
  24481. };
  24482. };
  24483. const renderDragHandle = () => ({ dom: fromHtml('<div class="tox-dialog__draghandle"></div>') });
  24484. const renderInlineHeader = (spec, dialogId, titleId, providersBackstage) => Container.sketch({
  24485. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  24486. components: [
  24487. renderTitle(spec, dialogId, Optional.some(titleId), providersBackstage),
  24488. renderDragHandle(),
  24489. renderClose(providersBackstage)
  24490. ],
  24491. containerBehaviours: derive$1([Dragging.config({
  24492. mode: 'mouse',
  24493. blockerClass: 'blocker',
  24494. getTarget: handle => {
  24495. return closest$1(handle, '[role="dialog"]').getOrDie();
  24496. },
  24497. snaps: {
  24498. getSnapPoints: () => [],
  24499. leftAttr: 'data-drag-left',
  24500. topAttr: 'data-drag-top'
  24501. }
  24502. })])
  24503. });
  24504. const renderModalHeader = (spec, dialogId, providersBackstage) => {
  24505. const pTitle = ModalDialog.parts.title(renderTitle(spec, dialogId, Optional.none(), providersBackstage));
  24506. const pHandle = ModalDialog.parts.draghandle(renderDragHandle());
  24507. const pClose = ModalDialog.parts.close(renderClose(providersBackstage));
  24508. const components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  24509. return Container.sketch({
  24510. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  24511. components
  24512. });
  24513. };
  24514. const getHeader = (title, dialogId, backstage) => renderModalHeader({
  24515. title: backstage.shared.providers.translate(title),
  24516. draggable: backstage.dialog.isDraggableModal()
  24517. }, dialogId, backstage.shared.providers);
  24518. const getBusySpec = (message, bs, providers) => ({
  24519. dom: {
  24520. tag: 'div',
  24521. classes: ['tox-dialog__busy-spinner'],
  24522. attributes: { 'aria-label': providers.translate(message) },
  24523. styles: {
  24524. left: '0px',
  24525. right: '0px',
  24526. bottom: '0px',
  24527. top: '0px',
  24528. position: 'absolute'
  24529. }
  24530. },
  24531. behaviours: bs,
  24532. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  24533. });
  24534. const getEventExtras = (lazyDialog, providers, extra) => ({
  24535. onClose: () => extra.closeWindow(),
  24536. onBlock: blockEvent => {
  24537. ModalDialog.setBusy(lazyDialog(), (_comp, bs) => getBusySpec(blockEvent.message, bs, providers));
  24538. },
  24539. onUnblock: () => {
  24540. ModalDialog.setIdle(lazyDialog());
  24541. }
  24542. });
  24543. const renderModalDialog = (spec, initialData, dialogEvents, backstage) => {
  24544. const updateState = (_comp, incoming) => Optional.some(incoming);
  24545. return build$1(renderDialog$1({
  24546. ...spec,
  24547. lazySink: backstage.shared.getSink,
  24548. extraBehaviours: [
  24549. Reflecting.config({
  24550. channel: `${ dialogChannel }-${ spec.id }`,
  24551. updateState,
  24552. initialData
  24553. }),
  24554. RepresentingConfigs.memory({}),
  24555. ...spec.extraBehaviours
  24556. ],
  24557. onEscape: comp => {
  24558. emit(comp, formCancelEvent);
  24559. },
  24560. dialogEvents,
  24561. eventOrder: {
  24562. [receive()]: [
  24563. Reflecting.name(),
  24564. Receiving.name()
  24565. ],
  24566. [attachedToDom()]: [
  24567. 'scroll-lock',
  24568. Reflecting.name(),
  24569. 'messages',
  24570. 'dialog-events',
  24571. 'alloy.base.behaviour'
  24572. ],
  24573. [detachedFromDom()]: [
  24574. 'alloy.base.behaviour',
  24575. 'dialog-events',
  24576. 'messages',
  24577. Reflecting.name(),
  24578. 'scroll-lock'
  24579. ]
  24580. }
  24581. }));
  24582. };
  24583. const mapMenuButtons = buttons => {
  24584. const mapItems = button => {
  24585. const items = map$2(button.items, item => {
  24586. const cell = Cell(false);
  24587. return {
  24588. ...item,
  24589. storage: cell
  24590. };
  24591. });
  24592. return {
  24593. ...button,
  24594. items
  24595. };
  24596. };
  24597. return map$2(buttons, button => {
  24598. if (button.type === 'menu') {
  24599. return mapItems(button);
  24600. }
  24601. return button;
  24602. });
  24603. };
  24604. const extractCellsToObject = buttons => foldl(buttons, (acc, button) => {
  24605. if (button.type === 'menu') {
  24606. const menuButton = button;
  24607. return foldl(menuButton.items, (innerAcc, item) => {
  24608. innerAcc[item.name] = item.storage;
  24609. return innerAcc;
  24610. }, acc);
  24611. }
  24612. return acc;
  24613. }, {});
  24614. const initCommonEvents = (fireApiEvent, extras) => [
  24615. runWithTarget(focusin(), onFocus),
  24616. fireApiEvent(formCloseEvent, (_api, spec) => {
  24617. extras.onClose();
  24618. spec.onClose();
  24619. }),
  24620. fireApiEvent(formCancelEvent, (api, spec, _event, self) => {
  24621. spec.onCancel(api);
  24622. emit(self, formCloseEvent);
  24623. }),
  24624. run$1(formUnblockEvent, (_c, _se) => extras.onUnblock()),
  24625. run$1(formBlockEvent, (_c, se) => extras.onBlock(se.event))
  24626. ];
  24627. const initUrlDialog = (getInstanceApi, extras) => {
  24628. const fireApiEvent = (eventName, f) => run$1(eventName, (c, se) => {
  24629. withSpec(c, (spec, _c) => {
  24630. f(getInstanceApi(), spec, se.event, c);
  24631. });
  24632. });
  24633. const withSpec = (c, f) => {
  24634. Reflecting.getState(c).get().each(currentDialog => {
  24635. f(currentDialog, c);
  24636. });
  24637. };
  24638. return [
  24639. ...initCommonEvents(fireApiEvent, extras),
  24640. fireApiEvent(formActionEvent, (api, spec, event) => {
  24641. spec.onAction(api, { name: event.name });
  24642. })
  24643. ];
  24644. };
  24645. const initDialog = (getInstanceApi, extras, getSink) => {
  24646. const fireApiEvent = (eventName, f) => run$1(eventName, (c, se) => {
  24647. withSpec(c, (spec, _c) => {
  24648. f(getInstanceApi(), spec, se.event, c);
  24649. });
  24650. });
  24651. const withSpec = (c, f) => {
  24652. Reflecting.getState(c).get().each(currentDialogInit => {
  24653. f(currentDialogInit.internalDialog, c);
  24654. });
  24655. };
  24656. return [
  24657. ...initCommonEvents(fireApiEvent, extras),
  24658. fireApiEvent(formSubmitEvent, (api, spec) => spec.onSubmit(api)),
  24659. fireApiEvent(formChangeEvent, (api, spec, event) => {
  24660. spec.onChange(api, { name: event.name });
  24661. }),
  24662. fireApiEvent(formActionEvent, (api, spec, event, component) => {
  24663. const focusIn = () => Keying.focusIn(component);
  24664. const isDisabled = focused => has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(val => val === 'true');
  24665. const rootNode = getRootNode(component.element);
  24666. const current = active$1(rootNode);
  24667. spec.onAction(api, {
  24668. name: event.name,
  24669. value: event.value
  24670. });
  24671. active$1(rootNode).fold(focusIn, focused => {
  24672. if (isDisabled(focused)) {
  24673. focusIn();
  24674. } else if (current.exists(cur => contains(focused, cur) && isDisabled(cur))) {
  24675. focusIn();
  24676. } else {
  24677. getSink().toOptional().filter(sink => !contains(sink.element, focused)).each(focusIn);
  24678. }
  24679. });
  24680. }),
  24681. fireApiEvent(formTabChangeEvent, (api, spec, event) => {
  24682. spec.onTabChange(api, {
  24683. newTabName: event.name,
  24684. oldTabName: event.oldName
  24685. });
  24686. }),
  24687. runOnDetached(component => {
  24688. const api = getInstanceApi();
  24689. Representing.setValue(component, api.getData());
  24690. })
  24691. ];
  24692. };
  24693. const SilverDialogEvents = {
  24694. initUrlDialog,
  24695. initDialog
  24696. };
  24697. const makeButton = (button, backstage) => renderFooterButton(button, button.type, backstage);
  24698. const lookup = (compInSystem, footerButtons, buttonName) => find$5(footerButtons, button => button.name === buttonName).bind(memButton => memButton.memento.getOpt(compInSystem));
  24699. const renderComponents = (_data, state) => {
  24700. const footerButtons = state.map(s => s.footerButtons).getOr([]);
  24701. const buttonGroups = partition$3(footerButtons, button => button.align === 'start');
  24702. const makeGroup = (edge, buttons) => Container.sketch({
  24703. dom: {
  24704. tag: 'div',
  24705. classes: [`tox-dialog__footer-${ edge }`]
  24706. },
  24707. components: map$2(buttons, button => button.memento.asSpec())
  24708. });
  24709. const startButtons = makeGroup('start', buttonGroups.pass);
  24710. const endButtons = makeGroup('end', buttonGroups.fail);
  24711. return [
  24712. startButtons,
  24713. endButtons
  24714. ];
  24715. };
  24716. const renderFooter = (initSpec, dialogId, backstage) => {
  24717. const updateState = (comp, data) => {
  24718. const footerButtons = map$2(data.buttons, button => {
  24719. const memButton = record(makeButton(button, backstage));
  24720. return {
  24721. name: button.name,
  24722. align: button.align,
  24723. memento: memButton
  24724. };
  24725. });
  24726. const lookupByName = buttonName => lookup(comp, footerButtons, buttonName);
  24727. return Optional.some({
  24728. lookupByName,
  24729. footerButtons
  24730. });
  24731. };
  24732. return {
  24733. dom: fromHtml('<div class="tox-dialog__footer"></div>'),
  24734. components: [],
  24735. behaviours: derive$1([Reflecting.config({
  24736. channel: `${ footerChannel }-${ dialogId }`,
  24737. initialData: initSpec,
  24738. updateState,
  24739. renderComponents
  24740. })])
  24741. };
  24742. };
  24743. const renderInlineFooter = (initSpec, dialogId, backstage) => renderFooter(initSpec, dialogId, backstage);
  24744. const renderModalFooter = (initSpec, dialogId, backstage) => ModalDialog.parts.footer(renderFooter(initSpec, dialogId, backstage));
  24745. const getCompByName = (access, name) => {
  24746. const root = access.getRoot();
  24747. if (root.getSystem().isConnected()) {
  24748. const form = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  24749. return Form.getField(form, name).orThunk(() => {
  24750. const footer = access.getFooter();
  24751. const footerState = Reflecting.getState(footer).get();
  24752. return footerState.bind(f => f.lookupByName(name));
  24753. });
  24754. } else {
  24755. return Optional.none();
  24756. }
  24757. };
  24758. const validateData$1 = (access, data) => {
  24759. const root = access.getRoot();
  24760. return Reflecting.getState(root).get().map(dialogState => getOrDie(asRaw('data', dialogState.dataValidator, data))).getOr(data);
  24761. };
  24762. const getDialogApi = (access, doRedial, menuItemStates) => {
  24763. const withRoot = f => {
  24764. const root = access.getRoot();
  24765. if (root.getSystem().isConnected()) {
  24766. f(root);
  24767. }
  24768. };
  24769. const getData = () => {
  24770. const root = access.getRoot();
  24771. const valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  24772. const representedValues = Representing.getValue(valueComp);
  24773. const menuItemCurrentState = map$1(menuItemStates, cell => cell.get());
  24774. return {
  24775. ...representedValues,
  24776. ...menuItemCurrentState
  24777. };
  24778. };
  24779. const setData = newData => {
  24780. withRoot(_ => {
  24781. const prevData = instanceApi.getData();
  24782. const mergedData = deepMerge(prevData, newData);
  24783. const newInternalData = validateData$1(access, mergedData);
  24784. const form = access.getFormWrapper();
  24785. Representing.setValue(form, newInternalData);
  24786. each(menuItemStates, (v, k) => {
  24787. if (has$2(mergedData, k)) {
  24788. v.set(mergedData[k]);
  24789. }
  24790. });
  24791. });
  24792. };
  24793. const setEnabled = (name, state) => {
  24794. getCompByName(access, name).each(state ? Disabling.enable : Disabling.disable);
  24795. };
  24796. const focus = name => {
  24797. getCompByName(access, name).each(Focusing.focus);
  24798. };
  24799. const block = message => {
  24800. if (!isString(message)) {
  24801. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  24802. }
  24803. withRoot(root => {
  24804. emitWith(root, formBlockEvent, { message });
  24805. });
  24806. };
  24807. const unblock = () => {
  24808. withRoot(root => {
  24809. emit(root, formUnblockEvent);
  24810. });
  24811. };
  24812. const showTab = name => {
  24813. withRoot(_ => {
  24814. const body = access.getBody();
  24815. const bodyState = Reflecting.getState(body);
  24816. if (bodyState.get().exists(b => b.isTabPanel())) {
  24817. Composing.getCurrent(body).each(tabSection => {
  24818. TabSection.showTab(tabSection, name);
  24819. });
  24820. }
  24821. });
  24822. };
  24823. const redial = d => {
  24824. withRoot(root => {
  24825. const id = access.getId();
  24826. const dialogInit = doRedial(d);
  24827. root.getSystem().broadcastOn([`${ dialogChannel }-${ id }`], dialogInit);
  24828. root.getSystem().broadcastOn([`${ titleChannel }-${ id }`], dialogInit.internalDialog);
  24829. root.getSystem().broadcastOn([`${ bodyChannel }-${ id }`], dialogInit.internalDialog);
  24830. root.getSystem().broadcastOn([`${ footerChannel }-${ id }`], dialogInit.internalDialog);
  24831. instanceApi.setData(dialogInit.initialData);
  24832. });
  24833. };
  24834. const close = () => {
  24835. withRoot(root => {
  24836. emit(root, formCloseEvent);
  24837. });
  24838. };
  24839. const instanceApi = {
  24840. getData,
  24841. setData,
  24842. setEnabled,
  24843. focus,
  24844. block,
  24845. unblock,
  24846. showTab,
  24847. redial,
  24848. close
  24849. };
  24850. return instanceApi;
  24851. };
  24852. const getDialogSizeClasses = size => {
  24853. switch (size) {
  24854. case 'large':
  24855. return ['tox-dialog--width-lg'];
  24856. case 'medium':
  24857. return ['tox-dialog--width-md'];
  24858. default:
  24859. return [];
  24860. }
  24861. };
  24862. const renderDialog = (dialogInit, extra, backstage) => {
  24863. const dialogId = generate$6('dialog');
  24864. const internalDialog = dialogInit.internalDialog;
  24865. const header = getHeader(internalDialog.title, dialogId, backstage);
  24866. const body = renderModalBody({
  24867. body: internalDialog.body,
  24868. initialData: internalDialog.initialData
  24869. }, dialogId, backstage);
  24870. const storagedMenuButtons = mapMenuButtons(internalDialog.buttons);
  24871. const objOfCells = extractCellsToObject(storagedMenuButtons);
  24872. const footer = renderModalFooter({ buttons: storagedMenuButtons }, dialogId, backstage);
  24873. const dialogEvents = SilverDialogEvents.initDialog(() => instanceApi, getEventExtras(() => dialog, backstage.shared.providers, extra), backstage.shared.getSink);
  24874. const dialogSize = getDialogSizeClasses(internalDialog.size);
  24875. const spec = {
  24876. id: dialogId,
  24877. header,
  24878. body,
  24879. footer: Optional.some(footer),
  24880. extraClasses: dialogSize,
  24881. extraBehaviours: [],
  24882. extraStyles: {}
  24883. };
  24884. const dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  24885. const modalAccess = (() => {
  24886. const getForm = () => {
  24887. const outerForm = ModalDialog.getBody(dialog);
  24888. return Composing.getCurrent(outerForm).getOr(outerForm);
  24889. };
  24890. return {
  24891. getId: constant$1(dialogId),
  24892. getRoot: constant$1(dialog),
  24893. getBody: () => ModalDialog.getBody(dialog),
  24894. getFooter: () => ModalDialog.getFooter(dialog),
  24895. getFormWrapper: getForm
  24896. };
  24897. })();
  24898. const instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  24899. return {
  24900. dialog,
  24901. instanceApi
  24902. };
  24903. };
  24904. const renderInlineDialog = (dialogInit, extra, backstage, ariaAttrs) => {
  24905. const dialogId = generate$6('dialog');
  24906. const dialogLabelId = generate$6('dialog-label');
  24907. const dialogContentId = generate$6('dialog-content');
  24908. const internalDialog = dialogInit.internalDialog;
  24909. const updateState = (_comp, incoming) => Optional.some(incoming);
  24910. const memHeader = record(renderInlineHeader({
  24911. title: internalDialog.title,
  24912. draggable: true
  24913. }, dialogId, dialogLabelId, backstage.shared.providers));
  24914. const memBody = record(renderInlineBody({
  24915. body: internalDialog.body,
  24916. initialData: internalDialog.initialData
  24917. }, dialogId, dialogContentId, backstage, ariaAttrs));
  24918. const storagedMenuButtons = mapMenuButtons(internalDialog.buttons);
  24919. const objOfCells = extractCellsToObject(storagedMenuButtons);
  24920. const memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, dialogId, backstage));
  24921. const dialogEvents = SilverDialogEvents.initDialog(() => instanceApi, {
  24922. onBlock: event => {
  24923. Blocking.block(dialog, (_comp, bs) => getBusySpec(event.message, bs, backstage.shared.providers));
  24924. },
  24925. onUnblock: () => {
  24926. Blocking.unblock(dialog);
  24927. },
  24928. onClose: () => extra.closeWindow()
  24929. }, backstage.shared.getSink);
  24930. const dialog = build$1({
  24931. dom: {
  24932. tag: 'div',
  24933. classes: [
  24934. 'tox-dialog',
  24935. 'tox-dialog-inline'
  24936. ],
  24937. attributes: {
  24938. role: 'dialog',
  24939. ['aria-labelledby']: dialogLabelId,
  24940. ['aria-describedby']: dialogContentId
  24941. }
  24942. },
  24943. eventOrder: {
  24944. [receive()]: [
  24945. Reflecting.name(),
  24946. Receiving.name()
  24947. ],
  24948. [execute$5()]: ['execute-on-form'],
  24949. [attachedToDom()]: [
  24950. 'reflecting',
  24951. 'execute-on-form'
  24952. ]
  24953. },
  24954. behaviours: derive$1([
  24955. Keying.config({
  24956. mode: 'cyclic',
  24957. onEscape: c => {
  24958. emit(c, formCloseEvent);
  24959. return Optional.some(true);
  24960. },
  24961. useTabstopAt: elem => !isPseudoStop(elem) && (name$3(elem) !== 'button' || get$f(elem, 'disabled') !== 'disabled')
  24962. }),
  24963. Reflecting.config({
  24964. channel: `${ dialogChannel }-${ dialogId }`,
  24965. updateState,
  24966. initialData: dialogInit
  24967. }),
  24968. Focusing.config({}),
  24969. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), (comp, _se) => {
  24970. Keying.focusIn(comp);
  24971. })])),
  24972. Blocking.config({ getRoot: () => Optional.some(dialog) }),
  24973. Replacing.config({}),
  24974. RepresentingConfigs.memory({})
  24975. ]),
  24976. components: [
  24977. memHeader.asSpec(),
  24978. memBody.asSpec(),
  24979. memFooter.asSpec()
  24980. ]
  24981. });
  24982. const instanceApi = getDialogApi({
  24983. getId: constant$1(dialogId),
  24984. getRoot: constant$1(dialog),
  24985. getFooter: () => memFooter.get(dialog),
  24986. getBody: () => memBody.get(dialog),
  24987. getFormWrapper: () => {
  24988. const body = memBody.get(dialog);
  24989. return Composing.getCurrent(body).getOr(body);
  24990. }
  24991. }, extra.redial, objOfCells);
  24992. return {
  24993. dialog,
  24994. instanceApi
  24995. };
  24996. };
  24997. var global = tinymce.util.Tools.resolve('tinymce.util.URI');
  24998. const getUrlDialogApi = root => {
  24999. const withRoot = f => {
  25000. if (root.getSystem().isConnected()) {
  25001. f(root);
  25002. }
  25003. };
  25004. const block = message => {
  25005. if (!isString(message)) {
  25006. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  25007. }
  25008. withRoot(root => {
  25009. emitWith(root, formBlockEvent, { message });
  25010. });
  25011. };
  25012. const unblock = () => {
  25013. withRoot(root => {
  25014. emit(root, formUnblockEvent);
  25015. });
  25016. };
  25017. const close = () => {
  25018. withRoot(root => {
  25019. emit(root, formCloseEvent);
  25020. });
  25021. };
  25022. const sendMessage = data => {
  25023. withRoot(root => {
  25024. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  25025. });
  25026. };
  25027. return {
  25028. block,
  25029. unblock,
  25030. close,
  25031. sendMessage
  25032. };
  25033. };
  25034. const SUPPORTED_MESSAGE_ACTIONS = [
  25035. 'insertContent',
  25036. 'setContent',
  25037. 'execCommand',
  25038. 'close',
  25039. 'block',
  25040. 'unblock'
  25041. ];
  25042. const isSupportedMessage = data => isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  25043. const isCustomMessage = data => !isSupportedMessage(data) && isObject(data) && has$2(data, 'mceAction');
  25044. const handleMessage = (editor, api, data) => {
  25045. switch (data.mceAction) {
  25046. case 'insertContent':
  25047. editor.insertContent(data.content);
  25048. break;
  25049. case 'setContent':
  25050. editor.setContent(data.content);
  25051. break;
  25052. case 'execCommand':
  25053. const ui = isBoolean(data.ui) ? data.ui : false;
  25054. editor.execCommand(data.cmd, ui, data.value);
  25055. break;
  25056. case 'close':
  25057. api.close();
  25058. break;
  25059. case 'block':
  25060. api.block(data.message);
  25061. break;
  25062. case 'unblock':
  25063. api.unblock();
  25064. break;
  25065. }
  25066. };
  25067. const renderUrlDialog = (internalDialog, extra, editor, backstage) => {
  25068. const dialogId = generate$6('dialog');
  25069. const header = getHeader(internalDialog.title, dialogId, backstage);
  25070. const body = renderIframeBody(internalDialog);
  25071. const footer = internalDialog.buttons.bind(buttons => {
  25072. if (buttons.length === 0) {
  25073. return Optional.none();
  25074. } else {
  25075. return Optional.some(renderModalFooter({ buttons }, dialogId, backstage));
  25076. }
  25077. });
  25078. const dialogEvents = SilverDialogEvents.initUrlDialog(() => instanceApi, getEventExtras(() => dialog, backstage.shared.providers, extra));
  25079. const styles = {
  25080. ...internalDialog.height.fold(() => ({}), height => ({
  25081. 'height': height + 'px',
  25082. 'max-height': height + 'px'
  25083. })),
  25084. ...internalDialog.width.fold(() => ({}), width => ({
  25085. 'width': width + 'px',
  25086. 'max-width': width + 'px'
  25087. }))
  25088. };
  25089. const classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  25090. const iframeUri = new global(internalDialog.url, { base_uri: new global(window.location.href) });
  25091. const iframeDomain = `${ iframeUri.protocol }://${ iframeUri.host }${ iframeUri.port ? ':' + iframeUri.port : '' }`;
  25092. const messageHandlerUnbinder = unbindable();
  25093. const extraBehaviours = [
  25094. config('messages', [
  25095. runOnAttached(() => {
  25096. const unbind = bind(SugarElement.fromDom(window), 'message', e => {
  25097. if (iframeUri.isSameOrigin(new global(e.raw.origin))) {
  25098. const data = e.raw.data;
  25099. if (isSupportedMessage(data)) {
  25100. handleMessage(editor, instanceApi, data);
  25101. } else if (isCustomMessage(data)) {
  25102. internalDialog.onMessage(instanceApi, data);
  25103. }
  25104. }
  25105. });
  25106. messageHandlerUnbinder.set(unbind);
  25107. }),
  25108. runOnDetached(messageHandlerUnbinder.clear)
  25109. ]),
  25110. Receiving.config({
  25111. channels: {
  25112. [bodySendMessageChannel]: {
  25113. onReceive: (comp, data) => {
  25114. descendant(comp.element, 'iframe').each(iframeEle => {
  25115. const iframeWin = iframeEle.dom.contentWindow;
  25116. iframeWin.postMessage(data, iframeDomain);
  25117. });
  25118. }
  25119. }
  25120. }
  25121. })
  25122. ];
  25123. const spec = {
  25124. id: dialogId,
  25125. header,
  25126. body,
  25127. footer,
  25128. extraClasses: classes,
  25129. extraBehaviours,
  25130. extraStyles: styles
  25131. };
  25132. const dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  25133. const instanceApi = getUrlDialogApi(dialog);
  25134. return {
  25135. dialog,
  25136. instanceApi
  25137. };
  25138. };
  25139. const setup$2 = extras => {
  25140. const sharedBackstage = extras.backstage.shared;
  25141. const open = (message, callback) => {
  25142. const closeDialog = () => {
  25143. ModalDialog.hide(alertDialog);
  25144. callback();
  25145. };
  25146. const memFooterClose = record(renderFooterButton({
  25147. name: 'close-alert',
  25148. text: 'OK',
  25149. primary: true,
  25150. buttonType: Optional.some('primary'),
  25151. align: 'end',
  25152. enabled: true,
  25153. icon: Optional.none()
  25154. }, 'cancel', extras.backstage));
  25155. const titleSpec = pUntitled();
  25156. const closeSpec = pClose(closeDialog, sharedBackstage.providers);
  25157. const alertDialog = build$1(renderDialog$1({
  25158. lazySink: () => sharedBackstage.getSink(),
  25159. header: hiddenHeader(titleSpec, closeSpec),
  25160. body: pBodyMessage(message, sharedBackstage.providers),
  25161. footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  25162. onEscape: closeDialog,
  25163. extraClasses: ['tox-alert-dialog'],
  25164. extraBehaviours: [],
  25165. extraStyles: {},
  25166. dialogEvents: [run$1(formCancelEvent, closeDialog)],
  25167. eventOrder: {}
  25168. }));
  25169. ModalDialog.show(alertDialog);
  25170. const footerCloseButton = memFooterClose.get(alertDialog);
  25171. Focusing.focus(footerCloseButton);
  25172. };
  25173. return { open };
  25174. };
  25175. const setup$1 = extras => {
  25176. const sharedBackstage = extras.backstage.shared;
  25177. const open = (message, callback) => {
  25178. const closeDialog = state => {
  25179. ModalDialog.hide(confirmDialog);
  25180. callback(state);
  25181. };
  25182. const memFooterYes = record(renderFooterButton({
  25183. name: 'yes',
  25184. text: 'Yes',
  25185. primary: true,
  25186. buttonType: Optional.some('primary'),
  25187. align: 'end',
  25188. enabled: true,
  25189. icon: Optional.none()
  25190. }, 'submit', extras.backstage));
  25191. const footerNo = renderFooterButton({
  25192. name: 'no',
  25193. text: 'No',
  25194. primary: false,
  25195. buttonType: Optional.some('secondary'),
  25196. align: 'end',
  25197. enabled: true,
  25198. icon: Optional.none()
  25199. }, 'cancel', extras.backstage);
  25200. const titleSpec = pUntitled();
  25201. const closeSpec = pClose(() => closeDialog(false), sharedBackstage.providers);
  25202. const confirmDialog = build$1(renderDialog$1({
  25203. lazySink: () => sharedBackstage.getSink(),
  25204. header: hiddenHeader(titleSpec, closeSpec),
  25205. body: pBodyMessage(message, sharedBackstage.providers),
  25206. footer: Optional.some(pFooter(pFooterGroup([], [
  25207. footerNo,
  25208. memFooterYes.asSpec()
  25209. ]))),
  25210. onEscape: () => closeDialog(false),
  25211. extraClasses: ['tox-confirm-dialog'],
  25212. extraBehaviours: [],
  25213. extraStyles: {},
  25214. dialogEvents: [
  25215. run$1(formCancelEvent, () => closeDialog(false)),
  25216. run$1(formSubmitEvent, () => closeDialog(true))
  25217. ],
  25218. eventOrder: {}
  25219. }));
  25220. ModalDialog.show(confirmDialog);
  25221. const footerYesButton = memFooterYes.get(confirmDialog);
  25222. Focusing.focus(footerYesButton);
  25223. };
  25224. return { open };
  25225. };
  25226. const validateData = (data, validator) => getOrDie(asRaw('data', validator, data));
  25227. const isAlertOrConfirmDialog = target => closest(target, '.tox-alert-dialog') || closest(target, '.tox-confirm-dialog');
  25228. const inlineAdditionalBehaviours = (editor, isStickyToolbar, isToolbarLocationTop) => {
  25229. if (isStickyToolbar && isToolbarLocationTop) {
  25230. return [];
  25231. } else {
  25232. return [Docking.config({
  25233. contextual: {
  25234. lazyContext: () => Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer()))),
  25235. fadeInClass: 'tox-dialog-dock-fadein',
  25236. fadeOutClass: 'tox-dialog-dock-fadeout',
  25237. transitionClass: 'tox-dialog-dock-transition'
  25238. },
  25239. modes: ['top']
  25240. })];
  25241. }
  25242. };
  25243. const setup = extras => {
  25244. const backstage = extras.backstage;
  25245. const editor = extras.editor;
  25246. const isStickyToolbar$1 = isStickyToolbar(editor);
  25247. const alertDialog = setup$2(extras);
  25248. const confirmDialog = setup$1(extras);
  25249. const open = (config, params, closeWindow) => {
  25250. if (params !== undefined && params.inline === 'toolbar') {
  25251. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  25252. } else if (params !== undefined && params.inline === 'cursor') {
  25253. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  25254. } else {
  25255. return openModalDialog(config, closeWindow);
  25256. }
  25257. };
  25258. const openUrl = (config, closeWindow) => openModalUrlDialog(config, closeWindow);
  25259. const openModalUrlDialog = (config, closeWindow) => {
  25260. const factory = contents => {
  25261. const dialog = renderUrlDialog(contents, {
  25262. closeWindow: () => {
  25263. ModalDialog.hide(dialog.dialog);
  25264. closeWindow(dialog.instanceApi);
  25265. }
  25266. }, editor, backstage);
  25267. ModalDialog.show(dialog.dialog);
  25268. return dialog.instanceApi;
  25269. };
  25270. return DialogManager.openUrl(factory, config);
  25271. };
  25272. const openModalDialog = (config, closeWindow) => {
  25273. const factory = (contents, internalInitialData, dataValidator) => {
  25274. const initialData = internalInitialData;
  25275. const dialogInit = {
  25276. dataValidator,
  25277. initialData,
  25278. internalDialog: contents
  25279. };
  25280. const dialog = renderDialog(dialogInit, {
  25281. redial: DialogManager.redial,
  25282. closeWindow: () => {
  25283. ModalDialog.hide(dialog.dialog);
  25284. closeWindow(dialog.instanceApi);
  25285. }
  25286. }, backstage);
  25287. ModalDialog.show(dialog.dialog);
  25288. dialog.instanceApi.setData(initialData);
  25289. return dialog.instanceApi;
  25290. };
  25291. return DialogManager.open(factory, config);
  25292. };
  25293. const openInlineDialog = (config$1, anchor, closeWindow, ariaAttrs) => {
  25294. const factory = (contents, internalInitialData, dataValidator) => {
  25295. const initialData = validateData(internalInitialData, dataValidator);
  25296. const inlineDialog = value$2();
  25297. const isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  25298. const dialogInit = {
  25299. dataValidator,
  25300. initialData,
  25301. internalDialog: contents
  25302. };
  25303. const refreshDocking = () => inlineDialog.on(dialog => {
  25304. InlineView.reposition(dialog);
  25305. Docking.refresh(dialog);
  25306. });
  25307. const dialogUi = renderInlineDialog(dialogInit, {
  25308. redial: DialogManager.redial,
  25309. closeWindow: () => {
  25310. inlineDialog.on(InlineView.hide);
  25311. editor.off('ResizeEditor', refreshDocking);
  25312. inlineDialog.clear();
  25313. closeWindow(dialogUi.instanceApi);
  25314. }
  25315. }, backstage, ariaAttrs);
  25316. const inlineDialogComp = build$1(InlineView.sketch({
  25317. lazySink: backstage.shared.getSink,
  25318. dom: {
  25319. tag: 'div',
  25320. classes: []
  25321. },
  25322. fireDismissalEventInstead: {},
  25323. ...isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} },
  25324. inlineBehaviours: derive$1([
  25325. config('window-manager-inline-events', [run$1(dismissRequested(), (_comp, _se) => {
  25326. emit(dialogUi.dialog, formCancelEvent);
  25327. })]),
  25328. ...inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop)
  25329. ]),
  25330. isExtraPart: (_comp, target) => isAlertOrConfirmDialog(target)
  25331. }));
  25332. inlineDialog.set(inlineDialogComp);
  25333. InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor }, Optional.some(body()));
  25334. if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  25335. Docking.refresh(inlineDialogComp);
  25336. editor.on('ResizeEditor', refreshDocking);
  25337. }
  25338. dialogUi.instanceApi.setData(initialData);
  25339. Keying.focusIn(dialogUi.dialog);
  25340. return dialogUi.instanceApi;
  25341. };
  25342. return DialogManager.open(factory, config$1);
  25343. };
  25344. const confirm = (message, callback) => {
  25345. confirmDialog.open(message, state => {
  25346. callback(state);
  25347. });
  25348. };
  25349. const alert = (message, callback) => {
  25350. alertDialog.open(message, () => {
  25351. callback();
  25352. });
  25353. };
  25354. const close = instanceApi => {
  25355. instanceApi.close();
  25356. };
  25357. return {
  25358. open,
  25359. openUrl,
  25360. alert,
  25361. close,
  25362. confirm
  25363. };
  25364. };
  25365. const registerOptions = editor => {
  25366. register$e(editor);
  25367. register$d(editor);
  25368. register(editor);
  25369. };
  25370. var Theme = () => {
  25371. global$a.add('silver', editor => {
  25372. registerOptions(editor);
  25373. const {getUiMothership, backstage, renderUI} = setup$3(editor);
  25374. Autocompleter.register(editor, backstage.shared);
  25375. const windowMgr = setup({
  25376. editor,
  25377. backstage
  25378. });
  25379. return {
  25380. renderUI,
  25381. getWindowManagerImpl: constant$1(windowMgr),
  25382. getNotificationManagerImpl: () => NotificationManagerImpl(editor, { backstage }, getUiMothership())
  25383. };
  25384. });
  25385. };
  25386. Theme();
  25387. })();