theme.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.9.1 (2021-08-27)
  8. */
  9. (function () {
  10. 'use strict';
  11. var typeOf = function (x) {
  12. var t = typeof x;
  13. if (x === null) {
  14. return 'null';
  15. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  16. return 'array';
  17. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  18. return 'string';
  19. } else {
  20. return t;
  21. }
  22. };
  23. var isType$1 = function (type) {
  24. return function (value) {
  25. return typeOf(value) === type;
  26. };
  27. };
  28. var isSimpleType = function (type) {
  29. return function (value) {
  30. return typeof value === type;
  31. };
  32. };
  33. var eq$1 = function (t) {
  34. return function (a) {
  35. return t === a;
  36. };
  37. };
  38. var isString = isType$1('string');
  39. var isObject = isType$1('object');
  40. var isArray = isType$1('array');
  41. var isNull = eq$1(null);
  42. var isBoolean = isSimpleType('boolean');
  43. var isUndefined = eq$1(undefined);
  44. var isNullable = function (a) {
  45. return a === null || a === undefined;
  46. };
  47. var isNonNullable = function (a) {
  48. return !isNullable(a);
  49. };
  50. var isFunction = isSimpleType('function');
  51. var isNumber = isSimpleType('number');
  52. var isArrayOf = function (value, pred) {
  53. if (isArray(value)) {
  54. for (var i = 0, len = value.length; i < len; ++i) {
  55. if (!pred(value[i])) {
  56. return false;
  57. }
  58. }
  59. return true;
  60. }
  61. return false;
  62. };
  63. var noop = function () {
  64. };
  65. var noarg = function (f) {
  66. return function () {
  67. return f();
  68. };
  69. };
  70. var compose = function (fa, fb) {
  71. return function () {
  72. var args = [];
  73. for (var _i = 0; _i < arguments.length; _i++) {
  74. args[_i] = arguments[_i];
  75. }
  76. return fa(fb.apply(null, args));
  77. };
  78. };
  79. var compose1 = function (fbc, fab) {
  80. return function (a) {
  81. return fbc(fab(a));
  82. };
  83. };
  84. var constant$1 = function (value) {
  85. return function () {
  86. return value;
  87. };
  88. };
  89. var identity$1 = function (x) {
  90. return x;
  91. };
  92. var tripleEquals = function (a, b) {
  93. return a === b;
  94. };
  95. function curry(fn) {
  96. var initialArgs = [];
  97. for (var _i = 1; _i < arguments.length; _i++) {
  98. initialArgs[_i - 1] = arguments[_i];
  99. }
  100. return function () {
  101. var restArgs = [];
  102. for (var _i = 0; _i < arguments.length; _i++) {
  103. restArgs[_i] = arguments[_i];
  104. }
  105. var all = initialArgs.concat(restArgs);
  106. return fn.apply(null, all);
  107. };
  108. }
  109. var not = function (f) {
  110. return function (t) {
  111. return !f(t);
  112. };
  113. };
  114. var die = function (msg) {
  115. return function () {
  116. throw new Error(msg);
  117. };
  118. };
  119. var never = constant$1(false);
  120. var always = constant$1(true);
  121. var global$h = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  122. var __assign = function () {
  123. __assign = Object.assign || function __assign(t) {
  124. for (var s, i = 1, n = arguments.length; i < n; i++) {
  125. s = arguments[i];
  126. for (var p in s)
  127. if (Object.prototype.hasOwnProperty.call(s, p))
  128. t[p] = s[p];
  129. }
  130. return t;
  131. };
  132. return __assign.apply(this, arguments);
  133. };
  134. function __rest(s, e) {
  135. var t = {};
  136. for (var p in s)
  137. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  138. t[p] = s[p];
  139. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  140. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  141. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  142. t[p[i]] = s[p[i]];
  143. }
  144. return t;
  145. }
  146. function __spreadArray(to, from, pack) {
  147. if (pack || arguments.length === 2)
  148. for (var i = 0, l = from.length, ar; i < l; i++) {
  149. if (ar || !(i in from)) {
  150. if (!ar)
  151. ar = Array.prototype.slice.call(from, 0, i);
  152. ar[i] = from[i];
  153. }
  154. }
  155. return to.concat(ar || Array.prototype.slice.call(from));
  156. }
  157. var none = function () {
  158. return NONE;
  159. };
  160. var NONE = function () {
  161. var call = function (thunk) {
  162. return thunk();
  163. };
  164. var id = identity$1;
  165. var me = {
  166. fold: function (n, _s) {
  167. return n();
  168. },
  169. isSome: never,
  170. isNone: always,
  171. getOr: id,
  172. getOrThunk: call,
  173. getOrDie: function (msg) {
  174. throw new Error(msg || 'error: getOrDie called on none.');
  175. },
  176. getOrNull: constant$1(null),
  177. getOrUndefined: constant$1(undefined),
  178. or: id,
  179. orThunk: call,
  180. map: none,
  181. each: noop,
  182. bind: none,
  183. exists: never,
  184. forall: always,
  185. filter: function () {
  186. return none();
  187. },
  188. toArray: function () {
  189. return [];
  190. },
  191. toString: constant$1('none()')
  192. };
  193. return me;
  194. }();
  195. var some = function (a) {
  196. var constant_a = constant$1(a);
  197. var self = function () {
  198. return me;
  199. };
  200. var bind = function (f) {
  201. return f(a);
  202. };
  203. var me = {
  204. fold: function (n, s) {
  205. return s(a);
  206. },
  207. isSome: always,
  208. isNone: never,
  209. getOr: constant_a,
  210. getOrThunk: constant_a,
  211. getOrDie: constant_a,
  212. getOrNull: constant_a,
  213. getOrUndefined: constant_a,
  214. or: self,
  215. orThunk: self,
  216. map: function (f) {
  217. return some(f(a));
  218. },
  219. each: function (f) {
  220. f(a);
  221. },
  222. bind: bind,
  223. exists: bind,
  224. forall: bind,
  225. filter: function (f) {
  226. return f(a) ? me : NONE;
  227. },
  228. toArray: function () {
  229. return [a];
  230. },
  231. toString: function () {
  232. return 'some(' + a + ')';
  233. }
  234. };
  235. return me;
  236. };
  237. var from$1 = function (value) {
  238. return value === null || value === undefined ? NONE : some(value);
  239. };
  240. var Optional = {
  241. some: some,
  242. none: none,
  243. from: from$1
  244. };
  245. var nativeSlice = Array.prototype.slice;
  246. var nativeIndexOf = Array.prototype.indexOf;
  247. var nativePush = Array.prototype.push;
  248. var rawIndexOf = function (ts, t) {
  249. return nativeIndexOf.call(ts, t);
  250. };
  251. var indexOf = function (xs, x) {
  252. var r = rawIndexOf(xs, x);
  253. return r === -1 ? Optional.none() : Optional.some(r);
  254. };
  255. var contains$2 = function (xs, x) {
  256. return rawIndexOf(xs, x) > -1;
  257. };
  258. var exists = function (xs, pred) {
  259. for (var i = 0, len = xs.length; i < len; i++) {
  260. var x = xs[i];
  261. if (pred(x, i)) {
  262. return true;
  263. }
  264. }
  265. return false;
  266. };
  267. var range$2 = function (num, f) {
  268. var r = [];
  269. for (var i = 0; i < num; i++) {
  270. r.push(f(i));
  271. }
  272. return r;
  273. };
  274. var chunk$1 = function (array, size) {
  275. var r = [];
  276. for (var i = 0; i < array.length; i += size) {
  277. var s = nativeSlice.call(array, i, i + size);
  278. r.push(s);
  279. }
  280. return r;
  281. };
  282. var map$2 = function (xs, f) {
  283. var len = xs.length;
  284. var r = new Array(len);
  285. for (var i = 0; i < len; i++) {
  286. var x = xs[i];
  287. r[i] = f(x, i);
  288. }
  289. return r;
  290. };
  291. var each$1 = function (xs, f) {
  292. for (var i = 0, len = xs.length; i < len; i++) {
  293. var x = xs[i];
  294. f(x, i);
  295. }
  296. };
  297. var eachr = function (xs, f) {
  298. for (var i = xs.length - 1; i >= 0; i--) {
  299. var x = xs[i];
  300. f(x, i);
  301. }
  302. };
  303. var partition$3 = function (xs, pred) {
  304. var pass = [];
  305. var fail = [];
  306. for (var i = 0, len = xs.length; i < len; i++) {
  307. var x = xs[i];
  308. var arr = pred(x, i) ? pass : fail;
  309. arr.push(x);
  310. }
  311. return {
  312. pass: pass,
  313. fail: fail
  314. };
  315. };
  316. var filter$2 = function (xs, pred) {
  317. var r = [];
  318. for (var i = 0, len = xs.length; i < len; i++) {
  319. var x = xs[i];
  320. if (pred(x, i)) {
  321. r.push(x);
  322. }
  323. }
  324. return r;
  325. };
  326. var foldr = function (xs, f, acc) {
  327. eachr(xs, function (x, i) {
  328. acc = f(acc, x, i);
  329. });
  330. return acc;
  331. };
  332. var foldl = function (xs, f, acc) {
  333. each$1(xs, function (x, i) {
  334. acc = f(acc, x, i);
  335. });
  336. return acc;
  337. };
  338. var findUntil = function (xs, pred, until) {
  339. for (var i = 0, len = xs.length; i < len; i++) {
  340. var x = xs[i];
  341. if (pred(x, i)) {
  342. return Optional.some(x);
  343. } else if (until(x, i)) {
  344. break;
  345. }
  346. }
  347. return Optional.none();
  348. };
  349. var find$5 = function (xs, pred) {
  350. return findUntil(xs, pred, never);
  351. };
  352. var findIndex$1 = function (xs, pred) {
  353. for (var i = 0, len = xs.length; i < len; i++) {
  354. var x = xs[i];
  355. if (pred(x, i)) {
  356. return Optional.some(i);
  357. }
  358. }
  359. return Optional.none();
  360. };
  361. var flatten = function (xs) {
  362. var r = [];
  363. for (var i = 0, len = xs.length; i < len; ++i) {
  364. if (!isArray(xs[i])) {
  365. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  366. }
  367. nativePush.apply(r, xs[i]);
  368. }
  369. return r;
  370. };
  371. var bind$3 = function (xs, f) {
  372. return flatten(map$2(xs, f));
  373. };
  374. var forall = function (xs, pred) {
  375. for (var i = 0, len = xs.length; i < len; ++i) {
  376. var x = xs[i];
  377. if (pred(x, i) !== true) {
  378. return false;
  379. }
  380. }
  381. return true;
  382. };
  383. var reverse = function (xs) {
  384. var r = nativeSlice.call(xs, 0);
  385. r.reverse();
  386. return r;
  387. };
  388. var difference = function (a1, a2) {
  389. return filter$2(a1, function (x) {
  390. return !contains$2(a2, x);
  391. });
  392. };
  393. var mapToObject = function (xs, f) {
  394. var r = {};
  395. for (var i = 0, len = xs.length; i < len; i++) {
  396. var x = xs[i];
  397. r[String(x)] = f(x, i);
  398. }
  399. return r;
  400. };
  401. var pure$2 = function (x) {
  402. return [x];
  403. };
  404. var sort = function (xs, comparator) {
  405. var copy = nativeSlice.call(xs, 0);
  406. copy.sort(comparator);
  407. return copy;
  408. };
  409. var get$f = function (xs, i) {
  410. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  411. };
  412. var head = function (xs) {
  413. return get$f(xs, 0);
  414. };
  415. var last$2 = function (xs) {
  416. return get$f(xs, xs.length - 1);
  417. };
  418. var from = isFunction(Array.from) ? Array.from : function (x) {
  419. return nativeSlice.call(x);
  420. };
  421. var findMap = function (arr, f) {
  422. for (var i = 0; i < arr.length; i++) {
  423. var r = f(arr[i], i);
  424. if (r.isSome()) {
  425. return r;
  426. }
  427. }
  428. return Optional.none();
  429. };
  430. var value$3 = function (o) {
  431. var or = function (_opt) {
  432. return value$3(o);
  433. };
  434. var orThunk = function (_f) {
  435. return value$3(o);
  436. };
  437. var map = function (f) {
  438. return value$3(f(o));
  439. };
  440. var mapError = function (_f) {
  441. return value$3(o);
  442. };
  443. var each = function (f) {
  444. f(o);
  445. };
  446. var bind = function (f) {
  447. return f(o);
  448. };
  449. var fold = function (_, onValue) {
  450. return onValue(o);
  451. };
  452. var exists = function (f) {
  453. return f(o);
  454. };
  455. var forall = function (f) {
  456. return f(o);
  457. };
  458. var toOptional = function () {
  459. return Optional.some(o);
  460. };
  461. return {
  462. isValue: always,
  463. isError: never,
  464. getOr: constant$1(o),
  465. getOrThunk: constant$1(o),
  466. getOrDie: constant$1(o),
  467. or: or,
  468. orThunk: orThunk,
  469. fold: fold,
  470. map: map,
  471. mapError: mapError,
  472. each: each,
  473. bind: bind,
  474. exists: exists,
  475. forall: forall,
  476. toOptional: toOptional
  477. };
  478. };
  479. var error$1 = function (message) {
  480. var getOrThunk = function (f) {
  481. return f();
  482. };
  483. var getOrDie = function () {
  484. return die(String(message))();
  485. };
  486. var or = identity$1;
  487. var orThunk = function (f) {
  488. return f();
  489. };
  490. var map = function (_f) {
  491. return error$1(message);
  492. };
  493. var mapError = function (f) {
  494. return error$1(f(message));
  495. };
  496. var bind = function (_f) {
  497. return error$1(message);
  498. };
  499. var fold = function (onError, _) {
  500. return onError(message);
  501. };
  502. return {
  503. isValue: never,
  504. isError: always,
  505. getOr: identity$1,
  506. getOrThunk: getOrThunk,
  507. getOrDie: getOrDie,
  508. or: or,
  509. orThunk: orThunk,
  510. fold: fold,
  511. map: map,
  512. mapError: mapError,
  513. each: noop,
  514. bind: bind,
  515. exists: never,
  516. forall: always,
  517. toOptional: Optional.none
  518. };
  519. };
  520. var fromOption = function (opt, err) {
  521. return opt.fold(function () {
  522. return error$1(err);
  523. }, value$3);
  524. };
  525. var Result = {
  526. value: value$3,
  527. error: error$1,
  528. fromOption: fromOption
  529. };
  530. var SimpleResultType;
  531. (function (SimpleResultType) {
  532. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  533. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  534. }(SimpleResultType || (SimpleResultType = {})));
  535. var fold$1 = function (res, onError, onValue) {
  536. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  537. };
  538. var partition$2 = function (results) {
  539. var values = [];
  540. var errors = [];
  541. each$1(results, function (obj) {
  542. fold$1(obj, function (err) {
  543. return errors.push(err);
  544. }, function (val) {
  545. return values.push(val);
  546. });
  547. });
  548. return {
  549. values: values,
  550. errors: errors
  551. };
  552. };
  553. var mapError = function (res, f) {
  554. if (res.stype === SimpleResultType.Error) {
  555. return {
  556. stype: SimpleResultType.Error,
  557. serror: f(res.serror)
  558. };
  559. } else {
  560. return res;
  561. }
  562. };
  563. var map$1 = function (res, f) {
  564. if (res.stype === SimpleResultType.Value) {
  565. return {
  566. stype: SimpleResultType.Value,
  567. svalue: f(res.svalue)
  568. };
  569. } else {
  570. return res;
  571. }
  572. };
  573. var bind$2 = function (res, f) {
  574. if (res.stype === SimpleResultType.Value) {
  575. return f(res.svalue);
  576. } else {
  577. return res;
  578. }
  579. };
  580. var bindError = function (res, f) {
  581. if (res.stype === SimpleResultType.Error) {
  582. return f(res.serror);
  583. } else {
  584. return res;
  585. }
  586. };
  587. var svalue = function (v) {
  588. return {
  589. stype: SimpleResultType.Value,
  590. svalue: v
  591. };
  592. };
  593. var serror = function (e) {
  594. return {
  595. stype: SimpleResultType.Error,
  596. serror: e
  597. };
  598. };
  599. var toResult$1 = function (res) {
  600. return fold$1(res, Result.error, Result.value);
  601. };
  602. var fromResult$1 = function (res) {
  603. return res.fold(serror, svalue);
  604. };
  605. var SimpleResult = {
  606. fromResult: fromResult$1,
  607. toResult: toResult$1,
  608. svalue: svalue,
  609. partition: partition$2,
  610. serror: serror,
  611. bind: bind$2,
  612. bindError: bindError,
  613. map: map$1,
  614. mapError: mapError,
  615. fold: fold$1
  616. };
  617. var field$2 = function (key, newKey, presence, prop) {
  618. return {
  619. tag: 'field',
  620. key: key,
  621. newKey: newKey,
  622. presence: presence,
  623. prop: prop
  624. };
  625. };
  626. var customField$1 = function (newKey, instantiator) {
  627. return {
  628. tag: 'custom',
  629. newKey: newKey,
  630. instantiator: instantiator
  631. };
  632. };
  633. var fold = function (value, ifField, ifCustom) {
  634. switch (value.tag) {
  635. case 'field':
  636. return ifField(value.key, value.newKey, value.presence, value.prop);
  637. case 'custom':
  638. return ifCustom(value.newKey, value.instantiator);
  639. }
  640. };
  641. var keys = Object.keys;
  642. var hasOwnProperty = Object.hasOwnProperty;
  643. var each = function (obj, f) {
  644. var props = keys(obj);
  645. for (var k = 0, len = props.length; k < len; k++) {
  646. var i = props[k];
  647. var x = obj[i];
  648. f(x, i);
  649. }
  650. };
  651. var map = function (obj, f) {
  652. return tupleMap(obj, function (x, i) {
  653. return {
  654. k: i,
  655. v: f(x, i)
  656. };
  657. });
  658. };
  659. var tupleMap = function (obj, f) {
  660. var r = {};
  661. each(obj, function (x, i) {
  662. var tuple = f(x, i);
  663. r[tuple.k] = tuple.v;
  664. });
  665. return r;
  666. };
  667. var objAcc = function (r) {
  668. return function (x, i) {
  669. r[i] = x;
  670. };
  671. };
  672. var internalFilter = function (obj, pred, onTrue, onFalse) {
  673. var r = {};
  674. each(obj, function (x, i) {
  675. (pred(x, i) ? onTrue : onFalse)(x, i);
  676. });
  677. return r;
  678. };
  679. var filter$1 = function (obj, pred) {
  680. var t = {};
  681. internalFilter(obj, pred, objAcc(t), noop);
  682. return t;
  683. };
  684. var mapToArray = function (obj, f) {
  685. var r = [];
  686. each(obj, function (value, name) {
  687. r.push(f(value, name));
  688. });
  689. return r;
  690. };
  691. var find$4 = function (obj, pred) {
  692. var props = keys(obj);
  693. for (var k = 0, len = props.length; k < len; k++) {
  694. var i = props[k];
  695. var x = obj[i];
  696. if (pred(x, i, obj)) {
  697. return Optional.some(x);
  698. }
  699. }
  700. return Optional.none();
  701. };
  702. var values = function (obj) {
  703. return mapToArray(obj, identity$1);
  704. };
  705. var get$e = function (obj, key) {
  706. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  707. };
  708. var has$2 = function (obj, key) {
  709. return hasOwnProperty.call(obj, key);
  710. };
  711. var hasNonNullableKey = function (obj, key) {
  712. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  713. };
  714. var shallow$1 = function (old, nu) {
  715. return nu;
  716. };
  717. var deep = function (old, nu) {
  718. var bothObjects = isObject(old) && isObject(nu);
  719. return bothObjects ? deepMerge(old, nu) : nu;
  720. };
  721. var baseMerge = function (merger) {
  722. return function () {
  723. var objects = [];
  724. for (var _i = 0; _i < arguments.length; _i++) {
  725. objects[_i] = arguments[_i];
  726. }
  727. if (objects.length === 0) {
  728. throw new Error('Can\'t merge zero objects');
  729. }
  730. var ret = {};
  731. for (var j = 0; j < objects.length; j++) {
  732. var curObject = objects[j];
  733. for (var key in curObject) {
  734. if (has$2(curObject, key)) {
  735. ret[key] = merger(ret[key], curObject[key]);
  736. }
  737. }
  738. }
  739. return ret;
  740. };
  741. };
  742. var deepMerge = baseMerge(deep);
  743. var merge$1 = baseMerge(shallow$1);
  744. var cached = function (f) {
  745. var called = false;
  746. var r;
  747. return function () {
  748. var args = [];
  749. for (var _i = 0; _i < arguments.length; _i++) {
  750. args[_i] = arguments[_i];
  751. }
  752. if (!called) {
  753. called = true;
  754. r = f.apply(null, args);
  755. }
  756. return r;
  757. };
  758. };
  759. var required$2 = function () {
  760. return {
  761. tag: 'required',
  762. process: {}
  763. };
  764. };
  765. var defaultedThunk = function (fallbackThunk) {
  766. return {
  767. tag: 'defaultedThunk',
  768. process: fallbackThunk
  769. };
  770. };
  771. var defaulted$1 = function (fallback) {
  772. return defaultedThunk(constant$1(fallback));
  773. };
  774. var asOption = function () {
  775. return {
  776. tag: 'option',
  777. process: {}
  778. };
  779. };
  780. var mergeWithThunk = function (baseThunk) {
  781. return {
  782. tag: 'mergeWithThunk',
  783. process: baseThunk
  784. };
  785. };
  786. var mergeWith = function (base) {
  787. return mergeWithThunk(constant$1(base));
  788. };
  789. var mergeValues$1 = function (values, base) {
  790. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  791. };
  792. var mergeErrors$1 = function (errors) {
  793. return compose(SimpleResult.serror, flatten)(errors);
  794. };
  795. var consolidateObj = function (objects, base) {
  796. var partition = SimpleResult.partition(objects);
  797. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  798. };
  799. var consolidateArr = function (objects) {
  800. var partitions = SimpleResult.partition(objects);
  801. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  802. };
  803. var ResultCombine = {
  804. consolidateObj: consolidateObj,
  805. consolidateArr: consolidateArr
  806. };
  807. var formatObj = function (input) {
  808. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  809. };
  810. var formatErrors = function (errors) {
  811. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  812. path: [],
  813. getErrorInfo: constant$1('... (only showing first ten failures)')
  814. }]) : errors;
  815. return map$2(es, function (e) {
  816. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  817. });
  818. };
  819. var nu$d = function (path, getErrorInfo) {
  820. return SimpleResult.serror([{
  821. path: path,
  822. getErrorInfo: getErrorInfo
  823. }]);
  824. };
  825. var missingRequired = function (path, key, obj) {
  826. return nu$d(path, function () {
  827. return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  828. });
  829. };
  830. var missingKey = function (path, key) {
  831. return nu$d(path, function () {
  832. return 'Choice schema did not contain choice key: "' + key + '"';
  833. });
  834. };
  835. var missingBranch = function (path, branches, branch) {
  836. return nu$d(path, function () {
  837. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  838. });
  839. };
  840. var unsupportedFields = function (path, unsupported) {
  841. return nu$d(path, function () {
  842. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  843. });
  844. };
  845. var custom = function (path, err) {
  846. return nu$d(path, constant$1(err));
  847. };
  848. var value$2 = function (validator) {
  849. var extract = function (path, val) {
  850. return SimpleResult.bindError(validator(val), function (err) {
  851. return custom(path, err);
  852. });
  853. };
  854. var toString = constant$1('val');
  855. return {
  856. extract: extract,
  857. toString: toString
  858. };
  859. };
  860. var anyValue$1 = value$2(SimpleResult.svalue);
  861. var requiredAccess = function (path, obj, key, bundle) {
  862. return get$e(obj, key).fold(function () {
  863. return missingRequired(path, key, obj);
  864. }, bundle);
  865. };
  866. var fallbackAccess = function (obj, key, fallback, bundle) {
  867. var v = get$e(obj, key).getOrThunk(function () {
  868. return fallback(obj);
  869. });
  870. return bundle(v);
  871. };
  872. var optionAccess = function (obj, key, bundle) {
  873. return bundle(get$e(obj, key));
  874. };
  875. var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  876. var opt = get$e(obj, key).map(function (val) {
  877. return val === true ? fallback(obj) : val;
  878. });
  879. return bundle(opt);
  880. };
  881. var extractField = function (field, path, obj, key, prop) {
  882. var bundle = function (av) {
  883. return prop.extract(path.concat([key]), av);
  884. };
  885. var bundleAsOption = function (optValue) {
  886. return optValue.fold(function () {
  887. return SimpleResult.svalue(Optional.none());
  888. }, function (ov) {
  889. var result = prop.extract(path.concat([key]), ov);
  890. return SimpleResult.map(result, Optional.some);
  891. });
  892. };
  893. switch (field.tag) {
  894. case 'required':
  895. return requiredAccess(path, obj, key, bundle);
  896. case 'defaultedThunk':
  897. return fallbackAccess(obj, key, field.process, bundle);
  898. case 'option':
  899. return optionAccess(obj, key, bundleAsOption);
  900. case 'defaultedOptionThunk':
  901. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  902. case 'mergeWithThunk': {
  903. return fallbackAccess(obj, key, constant$1({}), function (v) {
  904. var result = deepMerge(field.process(obj), v);
  905. return bundle(result);
  906. });
  907. }
  908. }
  909. };
  910. var extractFields = function (path, obj, fields) {
  911. var success = {};
  912. var errors = [];
  913. for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  914. var field = fields_1[_i];
  915. fold(field, function (key, newKey, presence, prop) {
  916. var result = extractField(presence, path, obj, key, prop);
  917. SimpleResult.fold(result, function (err) {
  918. errors.push.apply(errors, err);
  919. }, function (res) {
  920. success[newKey] = res;
  921. });
  922. }, function (newKey, instantiator) {
  923. success[newKey] = instantiator(obj);
  924. });
  925. }
  926. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  927. };
  928. var valueThunk = function (getDelegate) {
  929. var extract = function (path, val) {
  930. return getDelegate().extract(path, val);
  931. };
  932. var toString = function () {
  933. return getDelegate().toString();
  934. };
  935. return {
  936. extract: extract,
  937. toString: toString
  938. };
  939. };
  940. var getSetKeys = function (obj) {
  941. return keys(filter$1(obj, isNonNullable));
  942. };
  943. var objOfOnly = function (fields) {
  944. var delegate = objOf(fields);
  945. var fieldNames = foldr(fields, function (acc, value) {
  946. return fold(value, function (key) {
  947. var _a;
  948. return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  949. }, constant$1(acc));
  950. }, {});
  951. var extract = function (path, o) {
  952. var keys = isBoolean(o) ? [] : getSetKeys(o);
  953. var extra = filter$2(keys, function (k) {
  954. return !hasNonNullableKey(fieldNames, k);
  955. });
  956. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  957. };
  958. return {
  959. extract: extract,
  960. toString: delegate.toString
  961. };
  962. };
  963. var objOf = function (values) {
  964. var extract = function (path, o) {
  965. return extractFields(path, o, values);
  966. };
  967. var toString = function () {
  968. var fieldStrings = map$2(values, function (value) {
  969. return fold(value, function (key, _okey, _presence, prop) {
  970. return key + ' -> ' + prop.toString();
  971. }, function (newKey, _instantiator) {
  972. return 'state(' + newKey + ')';
  973. });
  974. });
  975. return 'obj{\n' + fieldStrings.join('\n') + '}';
  976. };
  977. return {
  978. extract: extract,
  979. toString: toString
  980. };
  981. };
  982. var arrOf = function (prop) {
  983. var extract = function (path, array) {
  984. var results = map$2(array, function (a, i) {
  985. return prop.extract(path.concat(['[' + i + ']']), a);
  986. });
  987. return ResultCombine.consolidateArr(results);
  988. };
  989. var toString = function () {
  990. return 'array(' + prop.toString() + ')';
  991. };
  992. return {
  993. extract: extract,
  994. toString: toString
  995. };
  996. };
  997. var oneOf = function (props) {
  998. var extract = function (path, val) {
  999. var errors = [];
  1000. for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  1001. var prop = props_1[_i];
  1002. var res = prop.extract(path, val);
  1003. if (res.stype === SimpleResultType.Value) {
  1004. return res;
  1005. }
  1006. errors.push(res);
  1007. }
  1008. return ResultCombine.consolidateArr(errors);
  1009. };
  1010. var toString = function () {
  1011. return 'oneOf(' + map$2(props, function (prop) {
  1012. return prop.toString();
  1013. }).join(', ') + ')';
  1014. };
  1015. return {
  1016. extract: extract,
  1017. toString: toString
  1018. };
  1019. };
  1020. var setOf$1 = function (validator, prop) {
  1021. var validateKeys = function (path, keys) {
  1022. return arrOf(value$2(validator)).extract(path, keys);
  1023. };
  1024. var extract = function (path, o) {
  1025. var keys$1 = keys(o);
  1026. var validatedKeys = validateKeys(path, keys$1);
  1027. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1028. var schema = map$2(validKeys, function (vk) {
  1029. return field$2(vk, vk, required$2(), prop);
  1030. });
  1031. return objOf(schema).extract(path, o);
  1032. });
  1033. };
  1034. var toString = function () {
  1035. return 'setOf(' + prop.toString() + ')';
  1036. };
  1037. return {
  1038. extract: extract,
  1039. toString: toString
  1040. };
  1041. };
  1042. var thunk = function (_desc, processor) {
  1043. var getP = cached(processor);
  1044. var extract = function (path, val) {
  1045. return getP().extract(path, val);
  1046. };
  1047. var toString = function () {
  1048. return getP().toString();
  1049. };
  1050. return {
  1051. extract: extract,
  1052. toString: toString
  1053. };
  1054. };
  1055. var arrOfObj = compose(arrOf, objOf);
  1056. var anyValue = constant$1(anyValue$1);
  1057. var typedValue = function (validator, expectedType) {
  1058. return value$2(function (a) {
  1059. var actualType = typeof a;
  1060. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1061. });
  1062. };
  1063. var number = typedValue(isNumber, 'number');
  1064. var string = typedValue(isString, 'string');
  1065. var boolean = typedValue(isBoolean, 'boolean');
  1066. var functionProcessor = typedValue(isFunction, 'function');
  1067. var isPostMessageable = function (val) {
  1068. if (Object(val) !== val) {
  1069. return true;
  1070. }
  1071. switch ({}.toString.call(val).slice(8, -1)) {
  1072. case 'Boolean':
  1073. case 'Number':
  1074. case 'String':
  1075. case 'Date':
  1076. case 'RegExp':
  1077. case 'Blob':
  1078. case 'FileList':
  1079. case 'ImageData':
  1080. case 'ImageBitmap':
  1081. case 'ArrayBuffer':
  1082. return true;
  1083. case 'Array':
  1084. case 'Object':
  1085. return Object.keys(val).every(function (prop) {
  1086. return isPostMessageable(val[prop]);
  1087. });
  1088. default:
  1089. return false;
  1090. }
  1091. };
  1092. var postMessageable = value$2(function (a) {
  1093. if (isPostMessageable(a)) {
  1094. return SimpleResult.svalue(a);
  1095. } else {
  1096. return SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1097. }
  1098. });
  1099. var chooseFrom = function (path, input, branches, ch) {
  1100. var fields = get$e(branches, ch);
  1101. return fields.fold(function () {
  1102. return missingBranch(path, branches, ch);
  1103. }, function (vp) {
  1104. return vp.extract(path.concat(['branch: ' + ch]), input);
  1105. });
  1106. };
  1107. var choose$2 = function (key, branches) {
  1108. var extract = function (path, input) {
  1109. var choice = get$e(input, key);
  1110. return choice.fold(function () {
  1111. return missingKey(path, key);
  1112. }, function (chosen) {
  1113. return chooseFrom(path, input, branches, chosen);
  1114. });
  1115. };
  1116. var toString = function () {
  1117. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1118. };
  1119. return {
  1120. extract: extract,
  1121. toString: toString
  1122. };
  1123. };
  1124. var arrOfVal = function () {
  1125. return arrOf(anyValue$1);
  1126. };
  1127. var valueOf = function (validator) {
  1128. return value$2(function (v) {
  1129. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1130. });
  1131. };
  1132. var setOf = function (validator, prop) {
  1133. return setOf$1(function (v) {
  1134. return SimpleResult.fromResult(validator(v));
  1135. }, prop);
  1136. };
  1137. var extractValue = function (label, prop, obj) {
  1138. var res = prop.extract([label], obj);
  1139. return SimpleResult.mapError(res, function (errs) {
  1140. return {
  1141. input: obj,
  1142. errors: errs
  1143. };
  1144. });
  1145. };
  1146. var asRaw = function (label, prop, obj) {
  1147. return SimpleResult.toResult(extractValue(label, prop, obj));
  1148. };
  1149. var getOrDie = function (extraction) {
  1150. return extraction.fold(function (errInfo) {
  1151. throw new Error(formatError(errInfo));
  1152. }, identity$1);
  1153. };
  1154. var asRawOrDie$1 = function (label, prop, obj) {
  1155. return getOrDie(asRaw(label, prop, obj));
  1156. };
  1157. var formatError = function (errInfo) {
  1158. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1159. };
  1160. var choose$1 = function (key, branches) {
  1161. return choose$2(key, map(branches, objOf));
  1162. };
  1163. var thunkOf = function (desc, schema) {
  1164. return thunk(desc, schema);
  1165. };
  1166. var field$1 = field$2;
  1167. var customField = customField$1;
  1168. var validateEnum = function (values) {
  1169. return valueOf(function (value) {
  1170. return contains$2(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  1171. });
  1172. };
  1173. var required$1 = function (key) {
  1174. return field$1(key, key, required$2(), anyValue());
  1175. };
  1176. var requiredOf = function (key, schema) {
  1177. return field$1(key, key, required$2(), schema);
  1178. };
  1179. var requiredNumber = function (key) {
  1180. return requiredOf(key, number);
  1181. };
  1182. var requiredString = function (key) {
  1183. return requiredOf(key, string);
  1184. };
  1185. var requiredStringEnum = function (key, values) {
  1186. return field$1(key, key, required$2(), validateEnum(values));
  1187. };
  1188. var requiredBoolean = function (key) {
  1189. return requiredOf(key, boolean);
  1190. };
  1191. var requiredFunction = function (key) {
  1192. return requiredOf(key, functionProcessor);
  1193. };
  1194. var forbid = function (key, message) {
  1195. return field$1(key, key, asOption(), value$2(function (_v) {
  1196. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1197. }));
  1198. };
  1199. var requiredObjOf = function (key, objSchema) {
  1200. return field$1(key, key, required$2(), objOf(objSchema));
  1201. };
  1202. var requiredArrayOfObj = function (key, objFields) {
  1203. return field$1(key, key, required$2(), arrOfObj(objFields));
  1204. };
  1205. var requiredArrayOf = function (key, schema) {
  1206. return field$1(key, key, required$2(), arrOf(schema));
  1207. };
  1208. var option = function (key) {
  1209. return field$1(key, key, asOption(), anyValue());
  1210. };
  1211. var optionOf = function (key, schema) {
  1212. return field$1(key, key, asOption(), schema);
  1213. };
  1214. var optionNumber = function (key) {
  1215. return optionOf(key, number);
  1216. };
  1217. var optionString = function (key) {
  1218. return optionOf(key, string);
  1219. };
  1220. var optionFunction = function (key) {
  1221. return optionOf(key, functionProcessor);
  1222. };
  1223. var optionArrayOf = function (key, schema) {
  1224. return optionOf(key, arrOf(schema));
  1225. };
  1226. var optionObjOf = function (key, objSchema) {
  1227. return optionOf(key, objOf(objSchema));
  1228. };
  1229. var optionObjOfOnly = function (key, objSchema) {
  1230. return optionOf(key, objOfOnly(objSchema));
  1231. };
  1232. var defaulted = function (key, fallback) {
  1233. return field$1(key, key, defaulted$1(fallback), anyValue());
  1234. };
  1235. var defaultedOf = function (key, fallback, schema) {
  1236. return field$1(key, key, defaulted$1(fallback), schema);
  1237. };
  1238. var defaultedNumber = function (key, fallback) {
  1239. return defaultedOf(key, fallback, number);
  1240. };
  1241. var defaultedString = function (key, fallback) {
  1242. return defaultedOf(key, fallback, string);
  1243. };
  1244. var defaultedStringEnum = function (key, fallback, values) {
  1245. return defaultedOf(key, fallback, validateEnum(values));
  1246. };
  1247. var defaultedBoolean = function (key, fallback) {
  1248. return defaultedOf(key, fallback, boolean);
  1249. };
  1250. var defaultedFunction = function (key, fallback) {
  1251. return defaultedOf(key, fallback, functionProcessor);
  1252. };
  1253. var defaultedPostMsg = function (key, fallback) {
  1254. return defaultedOf(key, fallback, postMessageable);
  1255. };
  1256. var defaultedArrayOf = function (key, fallback, schema) {
  1257. return defaultedOf(key, fallback, arrOf(schema));
  1258. };
  1259. var defaultedObjOf = function (key, fallback, objSchema) {
  1260. return defaultedOf(key, fallback, objOf(objSchema));
  1261. };
  1262. var Cell = function (initial) {
  1263. var value = initial;
  1264. var get = function () {
  1265. return value;
  1266. };
  1267. var set = function (v) {
  1268. value = v;
  1269. };
  1270. return {
  1271. get: get,
  1272. set: set
  1273. };
  1274. };
  1275. var fromHtml$2 = function (html, scope) {
  1276. var doc = scope || document;
  1277. var div = doc.createElement('div');
  1278. div.innerHTML = html;
  1279. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1280. console.error('HTML does not have a single root node', html);
  1281. throw new Error('HTML must have a single root node');
  1282. }
  1283. return fromDom(div.childNodes[0]);
  1284. };
  1285. var fromTag = function (tag, scope) {
  1286. var doc = scope || document;
  1287. var node = doc.createElement(tag);
  1288. return fromDom(node);
  1289. };
  1290. var fromText = function (text, scope) {
  1291. var doc = scope || document;
  1292. var node = doc.createTextNode(text);
  1293. return fromDom(node);
  1294. };
  1295. var fromDom = function (node) {
  1296. if (node === null || node === undefined) {
  1297. throw new Error('Node cannot be null or undefined');
  1298. }
  1299. return { dom: node };
  1300. };
  1301. var fromPoint = function (docElm, x, y) {
  1302. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  1303. };
  1304. var SugarElement = {
  1305. fromHtml: fromHtml$2,
  1306. fromTag: fromTag,
  1307. fromText: fromText,
  1308. fromDom: fromDom,
  1309. fromPoint: fromPoint
  1310. };
  1311. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  1312. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  1313. var isiPhone = os.isiOS() && !isiPad;
  1314. var isMobile = os.isiOS() || os.isAndroid();
  1315. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  1316. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  1317. var isPhone = isiPhone || isMobile && !isTablet;
  1318. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  1319. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  1320. return {
  1321. isiPad: constant$1(isiPad),
  1322. isiPhone: constant$1(isiPhone),
  1323. isTablet: constant$1(isTablet),
  1324. isPhone: constant$1(isPhone),
  1325. isTouch: constant$1(isTouch),
  1326. isAndroid: os.isAndroid,
  1327. isiOS: os.isiOS,
  1328. isWebView: constant$1(iOSwebview),
  1329. isDesktop: constant$1(isDesktop)
  1330. };
  1331. };
  1332. var firstMatch = function (regexes, s) {
  1333. for (var i = 0; i < regexes.length; i++) {
  1334. var x = regexes[i];
  1335. if (x.test(s)) {
  1336. return x;
  1337. }
  1338. }
  1339. return undefined;
  1340. };
  1341. var find$3 = function (regexes, agent) {
  1342. var r = firstMatch(regexes, agent);
  1343. if (!r) {
  1344. return {
  1345. major: 0,
  1346. minor: 0
  1347. };
  1348. }
  1349. var group = function (i) {
  1350. return Number(agent.replace(r, '$' + i));
  1351. };
  1352. return nu$c(group(1), group(2));
  1353. };
  1354. var detect$4 = function (versionRegexes, agent) {
  1355. var cleanedAgent = String(agent).toLowerCase();
  1356. if (versionRegexes.length === 0) {
  1357. return unknown$3();
  1358. }
  1359. return find$3(versionRegexes, cleanedAgent);
  1360. };
  1361. var unknown$3 = function () {
  1362. return nu$c(0, 0);
  1363. };
  1364. var nu$c = function (major, minor) {
  1365. return {
  1366. major: major,
  1367. minor: minor
  1368. };
  1369. };
  1370. var Version = {
  1371. nu: nu$c,
  1372. detect: detect$4,
  1373. unknown: unknown$3
  1374. };
  1375. var detectBrowser$1 = function (browsers, userAgentData) {
  1376. return findMap(userAgentData.brands, function (uaBrand) {
  1377. var lcBrand = uaBrand.brand.toLowerCase();
  1378. return find$5(browsers, function (browser) {
  1379. var _a;
  1380. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  1381. }).map(function (info) {
  1382. return {
  1383. current: info.name,
  1384. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  1385. };
  1386. });
  1387. });
  1388. };
  1389. var detect$3 = function (candidates, userAgent) {
  1390. var agent = String(userAgent).toLowerCase();
  1391. return find$5(candidates, function (candidate) {
  1392. return candidate.search(agent);
  1393. });
  1394. };
  1395. var detectBrowser = function (browsers, userAgent) {
  1396. return detect$3(browsers, userAgent).map(function (browser) {
  1397. var version = Version.detect(browser.versionRegexes, userAgent);
  1398. return {
  1399. current: browser.name,
  1400. version: version
  1401. };
  1402. });
  1403. };
  1404. var detectOs = function (oses, userAgent) {
  1405. return detect$3(oses, userAgent).map(function (os) {
  1406. var version = Version.detect(os.versionRegexes, userAgent);
  1407. return {
  1408. current: os.name,
  1409. version: version
  1410. };
  1411. });
  1412. };
  1413. var addToEnd = function (str, suffix) {
  1414. return str + suffix;
  1415. };
  1416. var removeFromStart = function (str, numChars) {
  1417. return str.substring(numChars);
  1418. };
  1419. var checkRange = function (str, substr, start) {
  1420. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  1421. };
  1422. var removeLeading = function (str, prefix) {
  1423. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  1424. };
  1425. var ensureTrailing = function (str, suffix) {
  1426. return endsWith(str, suffix) ? str : addToEnd(str, suffix);
  1427. };
  1428. var contains$1 = function (str, substr) {
  1429. return str.indexOf(substr) !== -1;
  1430. };
  1431. var startsWith = function (str, prefix) {
  1432. return checkRange(str, prefix, 0);
  1433. };
  1434. var endsWith = function (str, suffix) {
  1435. return checkRange(str, suffix, str.length - suffix.length);
  1436. };
  1437. var blank = function (r) {
  1438. return function (s) {
  1439. return s.replace(r, '');
  1440. };
  1441. };
  1442. var trim$1 = blank(/^\s+|\s+$/g);
  1443. var isNotEmpty = function (s) {
  1444. return s.length > 0;
  1445. };
  1446. var isEmpty = function (s) {
  1447. return !isNotEmpty(s);
  1448. };
  1449. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1450. var checkContains = function (target) {
  1451. return function (uastring) {
  1452. return contains$1(uastring, target);
  1453. };
  1454. };
  1455. var browsers = [
  1456. {
  1457. name: 'Edge',
  1458. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1459. search: function (uastring) {
  1460. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1461. }
  1462. },
  1463. {
  1464. name: 'Chrome',
  1465. brand: 'Chromium',
  1466. versionRegexes: [
  1467. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1468. normalVersionRegex
  1469. ],
  1470. search: function (uastring) {
  1471. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1472. }
  1473. },
  1474. {
  1475. name: 'IE',
  1476. versionRegexes: [
  1477. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1478. /.*?rv:([0-9]+)\.([0-9]+).*/
  1479. ],
  1480. search: function (uastring) {
  1481. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1482. }
  1483. },
  1484. {
  1485. name: 'Opera',
  1486. versionRegexes: [
  1487. normalVersionRegex,
  1488. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1489. ],
  1490. search: checkContains('opera')
  1491. },
  1492. {
  1493. name: 'Firefox',
  1494. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1495. search: checkContains('firefox')
  1496. },
  1497. {
  1498. name: 'Safari',
  1499. versionRegexes: [
  1500. normalVersionRegex,
  1501. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1502. ],
  1503. search: function (uastring) {
  1504. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1505. }
  1506. }
  1507. ];
  1508. var oses = [
  1509. {
  1510. name: 'Windows',
  1511. search: checkContains('win'),
  1512. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1513. },
  1514. {
  1515. name: 'iOS',
  1516. search: function (uastring) {
  1517. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1518. },
  1519. versionRegexes: [
  1520. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1521. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1522. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1523. ]
  1524. },
  1525. {
  1526. name: 'Android',
  1527. search: checkContains('android'),
  1528. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1529. },
  1530. {
  1531. name: 'OSX',
  1532. search: checkContains('mac os x'),
  1533. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  1534. },
  1535. {
  1536. name: 'Linux',
  1537. search: checkContains('linux'),
  1538. versionRegexes: []
  1539. },
  1540. {
  1541. name: 'Solaris',
  1542. search: checkContains('sunos'),
  1543. versionRegexes: []
  1544. },
  1545. {
  1546. name: 'FreeBSD',
  1547. search: checkContains('freebsd'),
  1548. versionRegexes: []
  1549. },
  1550. {
  1551. name: 'ChromeOS',
  1552. search: checkContains('cros'),
  1553. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  1554. }
  1555. ];
  1556. var PlatformInfo = {
  1557. browsers: constant$1(browsers),
  1558. oses: constant$1(oses)
  1559. };
  1560. var edge = 'Edge';
  1561. var chrome = 'Chrome';
  1562. var ie = 'IE';
  1563. var opera = 'Opera';
  1564. var firefox = 'Firefox';
  1565. var safari = 'Safari';
  1566. var unknown$2 = function () {
  1567. return nu$b({
  1568. current: undefined,
  1569. version: Version.unknown()
  1570. });
  1571. };
  1572. var nu$b = function (info) {
  1573. var current = info.current;
  1574. var version = info.version;
  1575. var isBrowser = function (name) {
  1576. return function () {
  1577. return current === name;
  1578. };
  1579. };
  1580. return {
  1581. current: current,
  1582. version: version,
  1583. isEdge: isBrowser(edge),
  1584. isChrome: isBrowser(chrome),
  1585. isIE: isBrowser(ie),
  1586. isOpera: isBrowser(opera),
  1587. isFirefox: isBrowser(firefox),
  1588. isSafari: isBrowser(safari)
  1589. };
  1590. };
  1591. var Browser = {
  1592. unknown: unknown$2,
  1593. nu: nu$b,
  1594. edge: constant$1(edge),
  1595. chrome: constant$1(chrome),
  1596. ie: constant$1(ie),
  1597. opera: constant$1(opera),
  1598. firefox: constant$1(firefox),
  1599. safari: constant$1(safari)
  1600. };
  1601. var windows = 'Windows';
  1602. var ios = 'iOS';
  1603. var android = 'Android';
  1604. var linux = 'Linux';
  1605. var osx = 'OSX';
  1606. var solaris = 'Solaris';
  1607. var freebsd = 'FreeBSD';
  1608. var chromeos = 'ChromeOS';
  1609. var unknown$1 = function () {
  1610. return nu$a({
  1611. current: undefined,
  1612. version: Version.unknown()
  1613. });
  1614. };
  1615. var nu$a = function (info) {
  1616. var current = info.current;
  1617. var version = info.version;
  1618. var isOS = function (name) {
  1619. return function () {
  1620. return current === name;
  1621. };
  1622. };
  1623. return {
  1624. current: current,
  1625. version: version,
  1626. isWindows: isOS(windows),
  1627. isiOS: isOS(ios),
  1628. isAndroid: isOS(android),
  1629. isOSX: isOS(osx),
  1630. isLinux: isOS(linux),
  1631. isSolaris: isOS(solaris),
  1632. isFreeBSD: isOS(freebsd),
  1633. isChromeOS: isOS(chromeos)
  1634. };
  1635. };
  1636. var OperatingSystem = {
  1637. unknown: unknown$1,
  1638. nu: nu$a,
  1639. windows: constant$1(windows),
  1640. ios: constant$1(ios),
  1641. android: constant$1(android),
  1642. linux: constant$1(linux),
  1643. osx: constant$1(osx),
  1644. solaris: constant$1(solaris),
  1645. freebsd: constant$1(freebsd),
  1646. chromeos: constant$1(chromeos)
  1647. };
  1648. var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  1649. var browsers = PlatformInfo.browsers();
  1650. var oses = PlatformInfo.oses();
  1651. var browser = userAgentDataOpt.bind(function (userAgentData) {
  1652. return detectBrowser$1(browsers, userAgentData);
  1653. }).orThunk(function () {
  1654. return detectBrowser(browsers, userAgent);
  1655. }).fold(Browser.unknown, Browser.nu);
  1656. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1657. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1658. return {
  1659. browser: browser,
  1660. os: os,
  1661. deviceType: deviceType
  1662. };
  1663. };
  1664. var PlatformDetection = { detect: detect$2 };
  1665. var mediaMatch = function (query) {
  1666. return window.matchMedia(query).matches;
  1667. };
  1668. var platform = cached(function () {
  1669. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  1670. });
  1671. var detect$1 = function () {
  1672. return platform();
  1673. };
  1674. var compareDocumentPosition = function (a, b, match) {
  1675. return (a.compareDocumentPosition(b) & match) !== 0;
  1676. };
  1677. var documentPositionContainedBy = function (a, b) {
  1678. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  1679. };
  1680. var DOCUMENT = 9;
  1681. var DOCUMENT_FRAGMENT = 11;
  1682. var ELEMENT = 1;
  1683. var TEXT = 3;
  1684. var is$1 = function (element, selector) {
  1685. var dom = element.dom;
  1686. if (dom.nodeType !== ELEMENT) {
  1687. return false;
  1688. } else {
  1689. var elem = dom;
  1690. if (elem.matches !== undefined) {
  1691. return elem.matches(selector);
  1692. } else if (elem.msMatchesSelector !== undefined) {
  1693. return elem.msMatchesSelector(selector);
  1694. } else if (elem.webkitMatchesSelector !== undefined) {
  1695. return elem.webkitMatchesSelector(selector);
  1696. } else if (elem.mozMatchesSelector !== undefined) {
  1697. return elem.mozMatchesSelector(selector);
  1698. } else {
  1699. throw new Error('Browser lacks native selectors');
  1700. }
  1701. }
  1702. };
  1703. var bypassSelector = function (dom) {
  1704. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1705. };
  1706. var all$3 = function (selector, scope) {
  1707. var base = scope === undefined ? document : scope.dom;
  1708. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  1709. };
  1710. var one = function (selector, scope) {
  1711. var base = scope === undefined ? document : scope.dom;
  1712. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1713. };
  1714. var eq = function (e1, e2) {
  1715. return e1.dom === e2.dom;
  1716. };
  1717. var regularContains = function (e1, e2) {
  1718. var d1 = e1.dom;
  1719. var d2 = e2.dom;
  1720. return d1 === d2 ? false : d1.contains(d2);
  1721. };
  1722. var ieContains = function (e1, e2) {
  1723. return documentPositionContainedBy(e1.dom, e2.dom);
  1724. };
  1725. var contains = function (e1, e2) {
  1726. return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1727. };
  1728. var generate$7 = function (cases) {
  1729. if (!isArray(cases)) {
  1730. throw new Error('cases must be an array');
  1731. }
  1732. if (cases.length === 0) {
  1733. throw new Error('there must be at least one case');
  1734. }
  1735. var constructors = [];
  1736. var adt = {};
  1737. each$1(cases, function (acase, count) {
  1738. var keys$1 = keys(acase);
  1739. if (keys$1.length !== 1) {
  1740. throw new Error('one and only one name per case');
  1741. }
  1742. var key = keys$1[0];
  1743. var value = acase[key];
  1744. if (adt[key] !== undefined) {
  1745. throw new Error('duplicate key detected:' + key);
  1746. } else if (key === 'cata') {
  1747. throw new Error('cannot have a case named cata (sorry)');
  1748. } else if (!isArray(value)) {
  1749. throw new Error('case arguments must be an array');
  1750. }
  1751. constructors.push(key);
  1752. adt[key] = function () {
  1753. var args = [];
  1754. for (var _i = 0; _i < arguments.length; _i++) {
  1755. args[_i] = arguments[_i];
  1756. }
  1757. var argLength = args.length;
  1758. if (argLength !== value.length) {
  1759. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1760. }
  1761. var match = function (branches) {
  1762. var branchKeys = keys(branches);
  1763. if (constructors.length !== branchKeys.length) {
  1764. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1765. }
  1766. var allReqd = forall(constructors, function (reqKey) {
  1767. return contains$2(branchKeys, reqKey);
  1768. });
  1769. if (!allReqd) {
  1770. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1771. }
  1772. return branches[key].apply(null, args);
  1773. };
  1774. return {
  1775. fold: function () {
  1776. var foldArgs = [];
  1777. for (var _i = 0; _i < arguments.length; _i++) {
  1778. foldArgs[_i] = arguments[_i];
  1779. }
  1780. if (foldArgs.length !== cases.length) {
  1781. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  1782. }
  1783. var target = foldArgs[count];
  1784. return target.apply(null, args);
  1785. },
  1786. match: match,
  1787. log: function (label) {
  1788. console.log(label, {
  1789. constructors: constructors,
  1790. constructor: key,
  1791. params: args
  1792. });
  1793. }
  1794. };
  1795. };
  1796. });
  1797. return adt;
  1798. };
  1799. var Adt = { generate: generate$7 };
  1800. Adt.generate([
  1801. {
  1802. bothErrors: [
  1803. 'error1',
  1804. 'error2'
  1805. ]
  1806. },
  1807. {
  1808. firstError: [
  1809. 'error1',
  1810. 'value2'
  1811. ]
  1812. },
  1813. {
  1814. secondError: [
  1815. 'value1',
  1816. 'error2'
  1817. ]
  1818. },
  1819. {
  1820. bothValues: [
  1821. 'value1',
  1822. 'value2'
  1823. ]
  1824. }
  1825. ]);
  1826. var partition$1 = function (results) {
  1827. var errors = [];
  1828. var values = [];
  1829. each$1(results, function (result) {
  1830. result.fold(function (err) {
  1831. errors.push(err);
  1832. }, function (value) {
  1833. values.push(value);
  1834. });
  1835. });
  1836. return {
  1837. errors: errors,
  1838. values: values
  1839. };
  1840. };
  1841. var exclude$1 = function (obj, fields) {
  1842. var r = {};
  1843. each(obj, function (v, k) {
  1844. if (!contains$2(fields, k)) {
  1845. r[k] = v;
  1846. }
  1847. });
  1848. return r;
  1849. };
  1850. var wrap$2 = function (key, value) {
  1851. var _a;
  1852. return _a = {}, _a[key] = value, _a;
  1853. };
  1854. var wrapAll$1 = function (keyvalues) {
  1855. var r = {};
  1856. each$1(keyvalues, function (kv) {
  1857. r[kv.key] = kv.value;
  1858. });
  1859. return r;
  1860. };
  1861. var exclude = function (obj, fields) {
  1862. return exclude$1(obj, fields);
  1863. };
  1864. var wrap$1 = function (key, value) {
  1865. return wrap$2(key, value);
  1866. };
  1867. var wrapAll = function (keyvalues) {
  1868. return wrapAll$1(keyvalues);
  1869. };
  1870. var mergeValues = function (values, base) {
  1871. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  1872. };
  1873. var mergeErrors = function (errors) {
  1874. return Result.error(flatten(errors));
  1875. };
  1876. var consolidate = function (objs, base) {
  1877. var partitions = partition$1(objs);
  1878. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  1879. };
  1880. var ensureIsRoot = function (isRoot) {
  1881. return isFunction(isRoot) ? isRoot : never;
  1882. };
  1883. var ancestor$2 = function (scope, transform, isRoot) {
  1884. var element = scope.dom;
  1885. var stop = ensureIsRoot(isRoot);
  1886. while (element.parentNode) {
  1887. element = element.parentNode;
  1888. var el = SugarElement.fromDom(element);
  1889. var transformed = transform(el);
  1890. if (transformed.isSome()) {
  1891. return transformed;
  1892. } else if (stop(el)) {
  1893. break;
  1894. }
  1895. }
  1896. return Optional.none();
  1897. };
  1898. var closest$4 = function (scope, transform, isRoot) {
  1899. var current = transform(scope);
  1900. var stop = ensureIsRoot(isRoot);
  1901. return current.orThunk(function () {
  1902. return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  1903. });
  1904. };
  1905. var isSource = function (component, simulatedEvent) {
  1906. return eq(component.element, simulatedEvent.event.target);
  1907. };
  1908. var defaultEventHandler = {
  1909. can: always,
  1910. abort: never,
  1911. run: noop
  1912. };
  1913. var nu$9 = function (parts) {
  1914. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  1915. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1916. }
  1917. return __assign(__assign({}, defaultEventHandler), parts);
  1918. };
  1919. var all$2 = function (handlers, f) {
  1920. return function () {
  1921. var args = [];
  1922. for (var _i = 0; _i < arguments.length; _i++) {
  1923. args[_i] = arguments[_i];
  1924. }
  1925. return foldl(handlers, function (acc, handler) {
  1926. return acc && f(handler).apply(undefined, args);
  1927. }, true);
  1928. };
  1929. };
  1930. var any = function (handlers, f) {
  1931. return function () {
  1932. var args = [];
  1933. for (var _i = 0; _i < arguments.length; _i++) {
  1934. args[_i] = arguments[_i];
  1935. }
  1936. return foldl(handlers, function (acc, handler) {
  1937. return acc || f(handler).apply(undefined, args);
  1938. }, false);
  1939. };
  1940. };
  1941. var read$2 = function (handler) {
  1942. return isFunction(handler) ? {
  1943. can: always,
  1944. abort: never,
  1945. run: handler
  1946. } : handler;
  1947. };
  1948. var fuse$1 = function (handlers) {
  1949. var can = all$2(handlers, function (handler) {
  1950. return handler.can;
  1951. });
  1952. var abort = any(handlers, function (handler) {
  1953. return handler.abort;
  1954. });
  1955. var run = function () {
  1956. var args = [];
  1957. for (var _i = 0; _i < arguments.length; _i++) {
  1958. args[_i] = arguments[_i];
  1959. }
  1960. each$1(handlers, function (handler) {
  1961. handler.run.apply(undefined, args);
  1962. });
  1963. };
  1964. return {
  1965. can: can,
  1966. abort: abort,
  1967. run: run
  1968. };
  1969. };
  1970. var constant = constant$1;
  1971. var touchstart = constant('touchstart');
  1972. var touchmove = constant('touchmove');
  1973. var touchend = constant('touchend');
  1974. var touchcancel = constant('touchcancel');
  1975. var mousedown = constant('mousedown');
  1976. var mousemove = constant('mousemove');
  1977. var mouseout = constant('mouseout');
  1978. var mouseup = constant('mouseup');
  1979. var mouseover = constant('mouseover');
  1980. var focusin = constant('focusin');
  1981. var focusout = constant('focusout');
  1982. var keydown = constant('keydown');
  1983. var keyup = constant('keyup');
  1984. var input = constant('input');
  1985. var change = constant('change');
  1986. var click = constant('click');
  1987. var transitioncancel = constant('transitioncancel');
  1988. var transitionend = constant('transitionend');
  1989. var transitionstart = constant('transitionstart');
  1990. var selectstart = constant('selectstart');
  1991. var prefixName = function (name) {
  1992. return constant$1('alloy.' + name);
  1993. };
  1994. var alloy = { tap: prefixName('tap') };
  1995. var focus$4 = prefixName('focus');
  1996. var postBlur = prefixName('blur.post');
  1997. var postPaste = prefixName('paste.post');
  1998. var receive = prefixName('receive');
  1999. var execute$5 = prefixName('execute');
  2000. var focusItem = prefixName('focus.item');
  2001. var tap = alloy.tap;
  2002. var longpress = prefixName('longpress');
  2003. var sandboxClose = prefixName('sandbox.close');
  2004. var typeaheadCancel = prefixName('typeahead.cancel');
  2005. var systemInit = prefixName('system.init');
  2006. var documentTouchmove = prefixName('system.touchmove');
  2007. var documentTouchend = prefixName('system.touchend');
  2008. var windowScroll = prefixName('system.scroll');
  2009. var windowResize = prefixName('system.resize');
  2010. var attachedToDom = prefixName('system.attached');
  2011. var detachedFromDom = prefixName('system.detached');
  2012. var dismissRequested = prefixName('system.dismissRequested');
  2013. var repositionRequested = prefixName('system.repositionRequested');
  2014. var focusShifted = prefixName('focusmanager.shifted');
  2015. var slotVisibility = prefixName('slotcontainer.visibility');
  2016. var changeTab = prefixName('change.tab');
  2017. var dismissTab = prefixName('dismiss.tab');
  2018. var highlight$1 = prefixName('highlight');
  2019. var dehighlight$1 = prefixName('dehighlight');
  2020. var emit = function (component, event) {
  2021. dispatchWith(component, component.element, event, {});
  2022. };
  2023. var emitWith = function (component, event, properties) {
  2024. dispatchWith(component, component.element, event, properties);
  2025. };
  2026. var emitExecute = function (component) {
  2027. emit(component, execute$5());
  2028. };
  2029. var dispatch = function (component, target, event) {
  2030. dispatchWith(component, target, event, {});
  2031. };
  2032. var dispatchWith = function (component, target, event, properties) {
  2033. var data = __assign({ target: target }, properties);
  2034. component.getSystem().triggerEvent(event, target, data);
  2035. };
  2036. var dispatchEvent = function (component, target, event, simulatedEvent) {
  2037. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  2038. };
  2039. var derive$2 = function (configs) {
  2040. return wrapAll(configs);
  2041. };
  2042. var abort = function (name, predicate) {
  2043. return {
  2044. key: name,
  2045. value: nu$9({ abort: predicate })
  2046. };
  2047. };
  2048. var can = function (name, predicate) {
  2049. return {
  2050. key: name,
  2051. value: nu$9({ can: predicate })
  2052. };
  2053. };
  2054. var preventDefault = function (name) {
  2055. return {
  2056. key: name,
  2057. value: nu$9({
  2058. run: function (component, simulatedEvent) {
  2059. simulatedEvent.event.prevent();
  2060. }
  2061. })
  2062. };
  2063. };
  2064. var run$1 = function (name, handler) {
  2065. return {
  2066. key: name,
  2067. value: nu$9({ run: handler })
  2068. };
  2069. };
  2070. var runActionExtra = function (name, action, extra) {
  2071. return {
  2072. key: name,
  2073. value: nu$9({
  2074. run: function (component, simulatedEvent) {
  2075. action.apply(undefined, [
  2076. component,
  2077. simulatedEvent
  2078. ].concat(extra));
  2079. }
  2080. })
  2081. };
  2082. };
  2083. var runOnName = function (name) {
  2084. return function (handler) {
  2085. return run$1(name, handler);
  2086. };
  2087. };
  2088. var runOnSourceName = function (name) {
  2089. return function (handler) {
  2090. return {
  2091. key: name,
  2092. value: nu$9({
  2093. run: function (component, simulatedEvent) {
  2094. if (isSource(component, simulatedEvent)) {
  2095. handler(component, simulatedEvent);
  2096. }
  2097. }
  2098. })
  2099. };
  2100. };
  2101. };
  2102. var redirectToUid = function (name, uid) {
  2103. return run$1(name, function (component, simulatedEvent) {
  2104. component.getSystem().getByUid(uid).each(function (redirectee) {
  2105. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2106. });
  2107. });
  2108. };
  2109. var redirectToPart = function (name, detail, partName) {
  2110. var uid = detail.partUids[partName];
  2111. return redirectToUid(name, uid);
  2112. };
  2113. var runWithTarget = function (name, f) {
  2114. return run$1(name, function (component, simulatedEvent) {
  2115. var ev = simulatedEvent.event;
  2116. var target = component.getSystem().getByDom(ev.target).getOrThunk(function () {
  2117. var closest = closest$4(ev.target, function (el) {
  2118. return component.getSystem().getByDom(el).toOptional();
  2119. }, never);
  2120. return closest.getOr(component);
  2121. });
  2122. f(component, target, simulatedEvent);
  2123. });
  2124. };
  2125. var cutter = function (name) {
  2126. return run$1(name, function (component, simulatedEvent) {
  2127. simulatedEvent.cut();
  2128. });
  2129. };
  2130. var stopper = function (name) {
  2131. return run$1(name, function (component, simulatedEvent) {
  2132. simulatedEvent.stop();
  2133. });
  2134. };
  2135. var runOnSource = function (name, f) {
  2136. return runOnSourceName(name)(f);
  2137. };
  2138. var runOnAttached = runOnSourceName(attachedToDom());
  2139. var runOnDetached = runOnSourceName(detachedFromDom());
  2140. var runOnInit = runOnSourceName(systemInit());
  2141. var runOnExecute$1 = runOnName(execute$5());
  2142. typeof window !== 'undefined' ? window : Function('return this;')();
  2143. var name$2 = function (element) {
  2144. var r = element.dom.nodeName;
  2145. return r.toLowerCase();
  2146. };
  2147. var type = function (element) {
  2148. return element.dom.nodeType;
  2149. };
  2150. var isType = function (t) {
  2151. return function (element) {
  2152. return type(element) === t;
  2153. };
  2154. };
  2155. var isElement$2 = isType(ELEMENT);
  2156. var isText$1 = isType(TEXT);
  2157. var isDocument = isType(DOCUMENT);
  2158. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  2159. var owner$4 = function (element) {
  2160. return SugarElement.fromDom(element.dom.ownerDocument);
  2161. };
  2162. var documentOrOwner = function (dos) {
  2163. return isDocument(dos) ? dos : owner$4(dos);
  2164. };
  2165. var documentElement = function (element) {
  2166. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  2167. };
  2168. var defaultView = function (element) {
  2169. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  2170. };
  2171. var parent = function (element) {
  2172. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  2173. };
  2174. var parentNode = function (element) {
  2175. return parent(element);
  2176. };
  2177. var offsetParent = function (element) {
  2178. return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  2179. };
  2180. var nextSibling = function (element) {
  2181. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  2182. };
  2183. var children = function (element) {
  2184. return map$2(element.dom.childNodes, SugarElement.fromDom);
  2185. };
  2186. var child$2 = function (element, index) {
  2187. var cs = element.dom.childNodes;
  2188. return Optional.from(cs[index]).map(SugarElement.fromDom);
  2189. };
  2190. var firstChild = function (element) {
  2191. return child$2(element, 0);
  2192. };
  2193. var spot = function (element, offset) {
  2194. return {
  2195. element: element,
  2196. offset: offset
  2197. };
  2198. };
  2199. var leaf = function (element, offset) {
  2200. var cs = children(element);
  2201. return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  2202. };
  2203. var isShadowRoot = function (dos) {
  2204. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  2205. };
  2206. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  2207. var isSupported$1 = constant$1(supported);
  2208. var getRootNode = supported ? function (e) {
  2209. return SugarElement.fromDom(e.dom.getRootNode());
  2210. } : documentOrOwner;
  2211. var getContentContainer = function (dos) {
  2212. return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  2213. };
  2214. var isInShadowRoot = function (e) {
  2215. return getShadowRoot(e).isSome();
  2216. };
  2217. var getShadowRoot = function (e) {
  2218. var r = getRootNode(e);
  2219. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  2220. };
  2221. var getShadowHost = function (e) {
  2222. return SugarElement.fromDom(e.dom.host);
  2223. };
  2224. var getOriginalEventTarget = function (event) {
  2225. if (isSupported$1() && isNonNullable(event.target)) {
  2226. var el = SugarElement.fromDom(event.target);
  2227. if (isElement$2(el) && isOpenShadowHost(el)) {
  2228. if (event.composed && event.composedPath) {
  2229. var composedPath = event.composedPath();
  2230. if (composedPath) {
  2231. return head(composedPath);
  2232. }
  2233. }
  2234. }
  2235. }
  2236. return Optional.from(event.target);
  2237. };
  2238. var isOpenShadowHost = function (element) {
  2239. return isNonNullable(element.dom.shadowRoot);
  2240. };
  2241. var before$2 = function (marker, element) {
  2242. var parent$1 = parent(marker);
  2243. parent$1.each(function (v) {
  2244. v.dom.insertBefore(element.dom, marker.dom);
  2245. });
  2246. };
  2247. var after$2 = function (marker, element) {
  2248. var sibling = nextSibling(marker);
  2249. sibling.fold(function () {
  2250. var parent$1 = parent(marker);
  2251. parent$1.each(function (v) {
  2252. append$2(v, element);
  2253. });
  2254. }, function (v) {
  2255. before$2(v, element);
  2256. });
  2257. };
  2258. var prepend$1 = function (parent, element) {
  2259. var firstChild$1 = firstChild(parent);
  2260. firstChild$1.fold(function () {
  2261. append$2(parent, element);
  2262. }, function (v) {
  2263. parent.dom.insertBefore(element.dom, v.dom);
  2264. });
  2265. };
  2266. var append$2 = function (parent, element) {
  2267. parent.dom.appendChild(element.dom);
  2268. };
  2269. var appendAt = function (parent, element, index) {
  2270. child$2(parent, index).fold(function () {
  2271. append$2(parent, element);
  2272. }, function (v) {
  2273. before$2(v, element);
  2274. });
  2275. };
  2276. var before$1 = function (marker, elements) {
  2277. each$1(elements, function (x) {
  2278. before$2(marker, x);
  2279. });
  2280. };
  2281. var append$1 = function (parent, elements) {
  2282. each$1(elements, function (x) {
  2283. append$2(parent, x);
  2284. });
  2285. };
  2286. var empty = function (element) {
  2287. element.dom.textContent = '';
  2288. each$1(children(element), function (rogue) {
  2289. remove$7(rogue);
  2290. });
  2291. };
  2292. var remove$7 = function (element) {
  2293. var dom = element.dom;
  2294. if (dom.parentNode !== null) {
  2295. dom.parentNode.removeChild(dom);
  2296. }
  2297. };
  2298. var unwrap = function (wrapper) {
  2299. var children$1 = children(wrapper);
  2300. if (children$1.length > 0) {
  2301. before$1(wrapper, children$1);
  2302. }
  2303. remove$7(wrapper);
  2304. };
  2305. var fromHtml$1 = function (html, scope) {
  2306. var doc = scope || document;
  2307. var div = doc.createElement('div');
  2308. div.innerHTML = html;
  2309. return children(SugarElement.fromDom(div));
  2310. };
  2311. var get$d = function (element) {
  2312. return element.dom.innerHTML;
  2313. };
  2314. var set$8 = function (element, content) {
  2315. var owner = owner$4(element);
  2316. var docDom = owner.dom;
  2317. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2318. var contentElements = fromHtml$1(content, docDom);
  2319. append$1(fragment, contentElements);
  2320. empty(element);
  2321. append$2(element, fragment);
  2322. };
  2323. var getOuter$2 = function (element) {
  2324. var container = SugarElement.fromTag('div');
  2325. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2326. append$2(container, clone);
  2327. return get$d(container);
  2328. };
  2329. var rawSet = function (dom, key, value) {
  2330. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2331. dom.setAttribute(key, value + '');
  2332. } else {
  2333. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2334. throw new Error('Attribute value was not simple');
  2335. }
  2336. };
  2337. var set$7 = function (element, key, value) {
  2338. rawSet(element.dom, key, value);
  2339. };
  2340. var setAll$1 = function (element, attrs) {
  2341. var dom = element.dom;
  2342. each(attrs, function (v, k) {
  2343. rawSet(dom, k, v);
  2344. });
  2345. };
  2346. var get$c = function (element, key) {
  2347. var v = element.dom.getAttribute(key);
  2348. return v === null ? undefined : v;
  2349. };
  2350. var getOpt = function (element, key) {
  2351. return Optional.from(get$c(element, key));
  2352. };
  2353. var has$1 = function (element, key) {
  2354. var dom = element.dom;
  2355. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2356. };
  2357. var remove$6 = function (element, key) {
  2358. element.dom.removeAttribute(key);
  2359. };
  2360. var clone$1 = function (original, isDeep) {
  2361. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2362. };
  2363. var shallow = function (original) {
  2364. return clone$1(original, false);
  2365. };
  2366. var getHtml = function (element) {
  2367. if (isShadowRoot(element)) {
  2368. return '#shadow-root';
  2369. } else {
  2370. var clone = shallow(element);
  2371. return getOuter$2(clone);
  2372. }
  2373. };
  2374. var element = function (elem) {
  2375. return getHtml(elem);
  2376. };
  2377. var isRecursive = function (component, originator, target) {
  2378. return eq(originator, component.element) && !eq(originator, target);
  2379. };
  2380. var events$i = derive$2([can(focus$4(), function (component, simulatedEvent) {
  2381. var event = simulatedEvent.event;
  2382. var originator = event.originator;
  2383. var target = event.target;
  2384. if (isRecursive(component, originator, target)) {
  2385. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  2386. return false;
  2387. } else {
  2388. return true;
  2389. }
  2390. })]);
  2391. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2392. __proto__: null,
  2393. events: events$i
  2394. });
  2395. var unique = 0;
  2396. var generate$6 = function (prefix) {
  2397. var date = new Date();
  2398. var time = date.getTime();
  2399. var random = Math.floor(Math.random() * 1000000000);
  2400. unique++;
  2401. return prefix + '_' + random + unique + String(time);
  2402. };
  2403. var prefix$1 = constant$1('alloy-id-');
  2404. var idAttr$1 = constant$1('data-alloy-id');
  2405. var prefix = prefix$1();
  2406. var idAttr = idAttr$1();
  2407. var write = function (label, elem) {
  2408. var id = generate$6(prefix + label);
  2409. writeOnly(elem, id);
  2410. return id;
  2411. };
  2412. var writeOnly = function (elem, uid) {
  2413. Object.defineProperty(elem.dom, idAttr, {
  2414. value: uid,
  2415. writable: true
  2416. });
  2417. };
  2418. var read$1 = function (elem) {
  2419. var id = isElement$2(elem) ? elem.dom[idAttr] : null;
  2420. return Optional.from(id);
  2421. };
  2422. var generate$5 = function (prefix) {
  2423. return generate$6(prefix);
  2424. };
  2425. var make$8 = identity$1;
  2426. var NoContextApi = function (getComp) {
  2427. var getMessage = function (event) {
  2428. return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  2429. };
  2430. var fail = function (event) {
  2431. return function () {
  2432. throw new Error(getMessage(event));
  2433. };
  2434. };
  2435. var warn = function (event) {
  2436. return function () {
  2437. console.warn(getMessage(event));
  2438. };
  2439. };
  2440. return {
  2441. debugInfo: constant$1('fake'),
  2442. triggerEvent: warn('triggerEvent'),
  2443. triggerFocus: warn('triggerFocus'),
  2444. triggerEscape: warn('triggerEscape'),
  2445. broadcast: warn('broadcast'),
  2446. broadcastOn: warn('broadcastOn'),
  2447. broadcastEvent: warn('broadcastEvent'),
  2448. build: fail('build'),
  2449. addToWorld: fail('addToWorld'),
  2450. removeFromWorld: fail('removeFromWorld'),
  2451. addToGui: fail('addToGui'),
  2452. removeFromGui: fail('removeFromGui'),
  2453. getByUid: fail('getByUid'),
  2454. getByDom: fail('getByDom'),
  2455. isConnected: never
  2456. };
  2457. };
  2458. var singleton$1 = NoContextApi();
  2459. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2460. var delegate = apiFunction.toString();
  2461. var endIndex = delegate.indexOf(')') + 1;
  2462. var openBracketIndex = delegate.indexOf('(');
  2463. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2464. f.toFunctionAnnotation = function () {
  2465. return {
  2466. name: apiName,
  2467. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2468. };
  2469. };
  2470. return f;
  2471. };
  2472. var cleanParameters = function (parameters) {
  2473. return map$2(parameters, function (p) {
  2474. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2475. });
  2476. };
  2477. var markAsExtraApi = function (f, extraName) {
  2478. var delegate = f.toString();
  2479. var endIndex = delegate.indexOf(')') + 1;
  2480. var openBracketIndex = delegate.indexOf('(');
  2481. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2482. f.toFunctionAnnotation = function () {
  2483. return {
  2484. name: extraName,
  2485. parameters: cleanParameters(parameters)
  2486. };
  2487. };
  2488. return f;
  2489. };
  2490. var markAsSketchApi = function (f, apiFunction) {
  2491. var delegate = apiFunction.toString();
  2492. var endIndex = delegate.indexOf(')') + 1;
  2493. var openBracketIndex = delegate.indexOf('(');
  2494. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2495. f.toFunctionAnnotation = function () {
  2496. return {
  2497. name: 'OVERRIDE',
  2498. parameters: cleanParameters(parameters.slice(1))
  2499. };
  2500. };
  2501. return f;
  2502. };
  2503. var premadeTag = generate$6('alloy-premade');
  2504. var premade$1 = function (comp) {
  2505. return wrap$1(premadeTag, comp);
  2506. };
  2507. var getPremade = function (spec) {
  2508. return get$e(spec, premadeTag);
  2509. };
  2510. var makeApi = function (f) {
  2511. return markAsSketchApi(function (component) {
  2512. var rest = [];
  2513. for (var _i = 1; _i < arguments.length; _i++) {
  2514. rest[_i - 1] = arguments[_i];
  2515. }
  2516. return f.apply(void 0, __spreadArray([
  2517. component.getApis(),
  2518. component
  2519. ], rest));
  2520. }, f);
  2521. };
  2522. var NoState = {
  2523. init: function () {
  2524. return nu$8({ readState: constant$1('No State required') });
  2525. }
  2526. };
  2527. var nu$8 = function (spec) {
  2528. return spec;
  2529. };
  2530. var generateFrom$1 = function (spec, all) {
  2531. var schema = map$2(all, function (a) {
  2532. return optionObjOf(a.name(), [
  2533. required$1('config'),
  2534. defaulted('state', NoState)
  2535. ]);
  2536. });
  2537. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2538. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2539. }, identity$1);
  2540. return {
  2541. list: all,
  2542. data: map(validated, function (optBlobThunk) {
  2543. var output = optBlobThunk.map(function (blob) {
  2544. return {
  2545. config: blob.config,
  2546. state: blob.state.init(blob.config)
  2547. };
  2548. });
  2549. return constant$1(output);
  2550. })
  2551. };
  2552. };
  2553. var getBehaviours$3 = function (bData) {
  2554. return bData.list;
  2555. };
  2556. var getData$2 = function (bData) {
  2557. return bData.data;
  2558. };
  2559. var byInnerKey = function (data, tuple) {
  2560. var r = {};
  2561. each(data, function (detail, key) {
  2562. each(detail, function (value, indexKey) {
  2563. var chain = get$e(r, indexKey).getOr([]);
  2564. r[indexKey] = chain.concat([tuple(key, value)]);
  2565. });
  2566. });
  2567. return r;
  2568. };
  2569. var nu$7 = function (s) {
  2570. return {
  2571. classes: isUndefined(s.classes) ? [] : s.classes,
  2572. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  2573. styles: isUndefined(s.styles) ? {} : s.styles
  2574. };
  2575. };
  2576. var merge = function (defnA, mod) {
  2577. return __assign(__assign({}, defnA), {
  2578. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2579. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2580. classes: defnA.classes.concat(mod.classes)
  2581. });
  2582. };
  2583. var combine$2 = function (info, baseMod, behaviours, base) {
  2584. var modsByBehaviour = __assign({}, baseMod);
  2585. each$1(behaviours, function (behaviour) {
  2586. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2587. });
  2588. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  2589. return {
  2590. name: name,
  2591. modification: modification
  2592. };
  2593. });
  2594. var combineObjects = function (objects) {
  2595. return foldr(objects, function (b, a) {
  2596. return __assign(__assign({}, a.modification), b);
  2597. }, {});
  2598. };
  2599. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  2600. return a.modification.concat(b);
  2601. }, []);
  2602. var combinedAttributes = combineObjects(byAspect.attributes);
  2603. var combinedStyles = combineObjects(byAspect.styles);
  2604. return nu$7({
  2605. classes: combinedClasses,
  2606. attributes: combinedAttributes,
  2607. styles: combinedStyles
  2608. });
  2609. };
  2610. var sortKeys = function (label, keyName, array, order) {
  2611. try {
  2612. var sorted = sort(array, function (a, b) {
  2613. var aKey = a[keyName];
  2614. var bKey = b[keyName];
  2615. var aIndex = order.indexOf(aKey);
  2616. var bIndex = order.indexOf(bKey);
  2617. if (aIndex === -1) {
  2618. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2619. }
  2620. if (bIndex === -1) {
  2621. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2622. }
  2623. if (aIndex < bIndex) {
  2624. return -1;
  2625. } else if (bIndex < aIndex) {
  2626. return 1;
  2627. } else {
  2628. return 0;
  2629. }
  2630. });
  2631. return Result.value(sorted);
  2632. } catch (err) {
  2633. return Result.error([err]);
  2634. }
  2635. };
  2636. var uncurried = function (handler, purpose) {
  2637. return {
  2638. handler: handler,
  2639. purpose: purpose
  2640. };
  2641. };
  2642. var curried = function (handler, purpose) {
  2643. return {
  2644. cHandler: handler,
  2645. purpose: purpose
  2646. };
  2647. };
  2648. var curryArgs = function (descHandler, extraArgs) {
  2649. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  2650. };
  2651. var getCurried = function (descHandler) {
  2652. return descHandler.cHandler;
  2653. };
  2654. var behaviourTuple = function (name, handler) {
  2655. return {
  2656. name: name,
  2657. handler: handler
  2658. };
  2659. };
  2660. var nameToHandlers = function (behaviours, info) {
  2661. var r = {};
  2662. each$1(behaviours, function (behaviour) {
  2663. r[behaviour.name()] = behaviour.handlers(info);
  2664. });
  2665. return r;
  2666. };
  2667. var groupByEvents = function (info, behaviours, base) {
  2668. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  2669. return byInnerKey(behaviourEvents, behaviourTuple);
  2670. };
  2671. var combine$1 = function (info, eventOrder, behaviours, base) {
  2672. var byEventName = groupByEvents(info, behaviours, base);
  2673. return combineGroups(byEventName, eventOrder);
  2674. };
  2675. var assemble = function (rawHandler) {
  2676. var handler = read$2(rawHandler);
  2677. return function (component, simulatedEvent) {
  2678. var rest = [];
  2679. for (var _i = 2; _i < arguments.length; _i++) {
  2680. rest[_i - 2] = arguments[_i];
  2681. }
  2682. var args = [
  2683. component,
  2684. simulatedEvent
  2685. ].concat(rest);
  2686. if (handler.abort.apply(undefined, args)) {
  2687. simulatedEvent.stop();
  2688. } else if (handler.can.apply(undefined, args)) {
  2689. handler.run.apply(undefined, args);
  2690. }
  2691. };
  2692. };
  2693. var missingOrderError = function (eventName, tuples) {
  2694. return Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map$2(tuples, function (c) {
  2695. return c.name;
  2696. }), null, 2)]);
  2697. };
  2698. var fuse = function (tuples, eventOrder, eventName) {
  2699. var order = eventOrder[eventName];
  2700. if (!order) {
  2701. return missingOrderError(eventName, tuples);
  2702. } else {
  2703. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  2704. var handlers = map$2(sortedTuples, function (tuple) {
  2705. return tuple.handler;
  2706. });
  2707. return fuse$1(handlers);
  2708. });
  2709. }
  2710. };
  2711. var combineGroups = function (byEventName, eventOrder) {
  2712. var r = mapToArray(byEventName, function (tuples, eventName) {
  2713. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  2714. return combined.map(function (handler) {
  2715. var assembled = assemble(handler);
  2716. var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  2717. return exists(tuples, function (t) {
  2718. return t.name === o;
  2719. });
  2720. }).join(' > ') : tuples[0].name;
  2721. return wrap$1(eventName, uncurried(assembled, purpose));
  2722. });
  2723. });
  2724. return consolidate(r, {});
  2725. };
  2726. var _a$2;
  2727. var baseBehaviour = 'alloy.base.behaviour';
  2728. var schema$z = objOf([
  2729. field$1('dom', 'dom', required$2(), objOf([
  2730. required$1('tag'),
  2731. defaulted('styles', {}),
  2732. defaulted('classes', []),
  2733. defaulted('attributes', {}),
  2734. option('value'),
  2735. option('innerHtml')
  2736. ])),
  2737. required$1('components'),
  2738. required$1('uid'),
  2739. defaulted('events', {}),
  2740. defaulted('apis', {}),
  2741. field$1('eventOrder', 'eventOrder', mergeWith((_a$2 = {}, _a$2[execute$5()] = [
  2742. 'disabling',
  2743. baseBehaviour,
  2744. 'toggling',
  2745. 'typeaheadevents'
  2746. ], _a$2[focus$4()] = [
  2747. baseBehaviour,
  2748. 'focusing',
  2749. 'keying'
  2750. ], _a$2[systemInit()] = [
  2751. baseBehaviour,
  2752. 'disabling',
  2753. 'toggling',
  2754. 'representing'
  2755. ], _a$2[input()] = [
  2756. baseBehaviour,
  2757. 'representing',
  2758. 'streaming',
  2759. 'invalidating'
  2760. ], _a$2[detachedFromDom()] = [
  2761. baseBehaviour,
  2762. 'representing',
  2763. 'item-events',
  2764. 'tooltipping'
  2765. ], _a$2[mousedown()] = [
  2766. 'focusing',
  2767. baseBehaviour,
  2768. 'item-type-events'
  2769. ], _a$2[touchstart()] = [
  2770. 'focusing',
  2771. baseBehaviour,
  2772. 'item-type-events'
  2773. ], _a$2[mouseover()] = [
  2774. 'item-type-events',
  2775. 'tooltipping'
  2776. ], _a$2[receive()] = [
  2777. 'receiving',
  2778. 'reflecting',
  2779. 'tooltipping'
  2780. ], _a$2)), anyValue()),
  2781. option('domModification')
  2782. ]);
  2783. var toInfo = function (spec) {
  2784. return asRaw('custom.definition', schema$z, spec);
  2785. };
  2786. var toDefinition = function (detail) {
  2787. return __assign(__assign({}, detail.dom), {
  2788. uid: detail.uid,
  2789. domChildren: map$2(detail.components, function (comp) {
  2790. return comp.element;
  2791. })
  2792. });
  2793. };
  2794. var toModification = function (detail) {
  2795. return detail.domModification.fold(function () {
  2796. return nu$7({});
  2797. }, nu$7);
  2798. };
  2799. var toEvents = function (info) {
  2800. return info.events;
  2801. };
  2802. var read = function (element, attr) {
  2803. var value = get$c(element, attr);
  2804. return value === undefined || value === '' ? [] : value.split(' ');
  2805. };
  2806. var add$4 = function (element, attr, id) {
  2807. var old = read(element, attr);
  2808. var nu = old.concat([id]);
  2809. set$7(element, attr, nu.join(' '));
  2810. return true;
  2811. };
  2812. var remove$5 = function (element, attr, id) {
  2813. var nu = filter$2(read(element, attr), function (v) {
  2814. return v !== id;
  2815. });
  2816. if (nu.length > 0) {
  2817. set$7(element, attr, nu.join(' '));
  2818. } else {
  2819. remove$6(element, attr);
  2820. }
  2821. return false;
  2822. };
  2823. var supports = function (element) {
  2824. return element.dom.classList !== undefined;
  2825. };
  2826. var get$b = function (element) {
  2827. return read(element, 'class');
  2828. };
  2829. var add$3 = function (element, clazz) {
  2830. return add$4(element, 'class', clazz);
  2831. };
  2832. var remove$4 = function (element, clazz) {
  2833. return remove$5(element, 'class', clazz);
  2834. };
  2835. var add$2 = function (element, clazz) {
  2836. if (supports(element)) {
  2837. element.dom.classList.add(clazz);
  2838. } else {
  2839. add$3(element, clazz);
  2840. }
  2841. };
  2842. var cleanClass = function (element) {
  2843. var classList = supports(element) ? element.dom.classList : get$b(element);
  2844. if (classList.length === 0) {
  2845. remove$6(element, 'class');
  2846. }
  2847. };
  2848. var remove$3 = function (element, clazz) {
  2849. if (supports(element)) {
  2850. var classList = element.dom.classList;
  2851. classList.remove(clazz);
  2852. } else {
  2853. remove$4(element, clazz);
  2854. }
  2855. cleanClass(element);
  2856. };
  2857. var has = function (element, clazz) {
  2858. return supports(element) && element.dom.classList.contains(clazz);
  2859. };
  2860. var add$1 = function (element, classes) {
  2861. each$1(classes, function (x) {
  2862. add$2(element, x);
  2863. });
  2864. };
  2865. var remove$2 = function (element, classes) {
  2866. each$1(classes, function (x) {
  2867. remove$3(element, x);
  2868. });
  2869. };
  2870. var hasAll = function (element, classes) {
  2871. return forall(classes, function (clazz) {
  2872. return has(element, clazz);
  2873. });
  2874. };
  2875. var is = function (lhs, rhs, comparator) {
  2876. if (comparator === void 0) {
  2877. comparator = tripleEquals;
  2878. }
  2879. return lhs.exists(function (left) {
  2880. return comparator(left, rhs);
  2881. });
  2882. };
  2883. var equals = function (lhs, rhs, comparator) {
  2884. if (comparator === void 0) {
  2885. comparator = tripleEquals;
  2886. }
  2887. return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
  2888. };
  2889. var cat = function (arr) {
  2890. var r = [];
  2891. var push = function (x) {
  2892. r.push(x);
  2893. };
  2894. for (var i = 0; i < arr.length; i++) {
  2895. arr[i].each(push);
  2896. }
  2897. return r;
  2898. };
  2899. var sequence = function (arr) {
  2900. var r = [];
  2901. for (var i = 0; i < arr.length; i++) {
  2902. var x = arr[i];
  2903. if (x.isSome()) {
  2904. r.push(x.getOrDie());
  2905. } else {
  2906. return Optional.none();
  2907. }
  2908. }
  2909. return Optional.some(r);
  2910. };
  2911. var lift2 = function (oa, ob, f) {
  2912. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  2913. };
  2914. var lift3 = function (oa, ob, oc, f) {
  2915. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  2916. };
  2917. var mapFrom = function (a, f) {
  2918. return a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none();
  2919. };
  2920. var someIf = function (b, a) {
  2921. return b ? Optional.some(a) : Optional.none();
  2922. };
  2923. var isSupported = function (dom) {
  2924. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2925. };
  2926. var inBody = function (element) {
  2927. var dom = isText$1(element) ? element.dom.parentNode : element.dom;
  2928. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  2929. return false;
  2930. }
  2931. var doc = dom.ownerDocument;
  2932. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  2933. return doc.body.contains(dom);
  2934. }, compose1(inBody, getShadowHost));
  2935. };
  2936. var body = function () {
  2937. return getBody(SugarElement.fromDom(document));
  2938. };
  2939. var getBody = function (doc) {
  2940. var b = doc.dom.body;
  2941. if (b === null || b === undefined) {
  2942. throw new Error('Body is not available yet');
  2943. }
  2944. return SugarElement.fromDom(b);
  2945. };
  2946. var internalSet = function (dom, property, value) {
  2947. if (!isString(value)) {
  2948. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2949. throw new Error('CSS value must be a string: ' + value);
  2950. }
  2951. if (isSupported(dom)) {
  2952. dom.style.setProperty(property, value);
  2953. }
  2954. };
  2955. var internalRemove = function (dom, property) {
  2956. if (isSupported(dom)) {
  2957. dom.style.removeProperty(property);
  2958. }
  2959. };
  2960. var set$6 = function (element, property, value) {
  2961. var dom = element.dom;
  2962. internalSet(dom, property, value);
  2963. };
  2964. var setAll = function (element, css) {
  2965. var dom = element.dom;
  2966. each(css, function (v, k) {
  2967. internalSet(dom, k, v);
  2968. });
  2969. };
  2970. var setOptions = function (element, css) {
  2971. var dom = element.dom;
  2972. each(css, function (v, k) {
  2973. v.fold(function () {
  2974. internalRemove(dom, k);
  2975. }, function (value) {
  2976. internalSet(dom, k, value);
  2977. });
  2978. });
  2979. };
  2980. var get$a = function (element, property) {
  2981. var dom = element.dom;
  2982. var styles = window.getComputedStyle(dom);
  2983. var r = styles.getPropertyValue(property);
  2984. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2985. };
  2986. var getUnsafeProperty = function (dom, property) {
  2987. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2988. };
  2989. var getRaw = function (element, property) {
  2990. var dom = element.dom;
  2991. var raw = getUnsafeProperty(dom, property);
  2992. return Optional.from(raw).filter(function (r) {
  2993. return r.length > 0;
  2994. });
  2995. };
  2996. var getAllRaw = function (element) {
  2997. var css = {};
  2998. var dom = element.dom;
  2999. if (isSupported(dom)) {
  3000. for (var i = 0; i < dom.style.length; i++) {
  3001. var ruleName = dom.style.item(i);
  3002. css[ruleName] = dom.style[ruleName];
  3003. }
  3004. }
  3005. return css;
  3006. };
  3007. var isValidValue = function (tag, property, value) {
  3008. var element = SugarElement.fromTag(tag);
  3009. set$6(element, property, value);
  3010. var style = getRaw(element, property);
  3011. return style.isSome();
  3012. };
  3013. var remove$1 = function (element, property) {
  3014. var dom = element.dom;
  3015. internalRemove(dom, property);
  3016. if (is(getOpt(element, 'style').map(trim$1), '')) {
  3017. remove$6(element, 'style');
  3018. }
  3019. };
  3020. var reflow = function (e) {
  3021. return e.dom.offsetWidth;
  3022. };
  3023. var get$9 = function (element) {
  3024. return element.dom.value;
  3025. };
  3026. var set$5 = function (element, value) {
  3027. if (value === undefined) {
  3028. throw new Error('Value.set was undefined');
  3029. }
  3030. element.dom.value = value;
  3031. };
  3032. var renderToDom = function (definition) {
  3033. var subject = SugarElement.fromTag(definition.tag);
  3034. setAll$1(subject, definition.attributes);
  3035. add$1(subject, definition.classes);
  3036. setAll(subject, definition.styles);
  3037. definition.innerHtml.each(function (html) {
  3038. return set$8(subject, html);
  3039. });
  3040. var children = definition.domChildren;
  3041. append$1(subject, children);
  3042. definition.value.each(function (value) {
  3043. set$5(subject, value);
  3044. });
  3045. if (!definition.uid) {
  3046. debugger;
  3047. }
  3048. writeOnly(subject, definition.uid);
  3049. return subject;
  3050. };
  3051. var getBehaviours$2 = function (spec) {
  3052. var behaviours = get$e(spec, 'behaviours').getOr({});
  3053. var keys$1 = filter$2(keys(behaviours), function (k) {
  3054. return behaviours[k] !== undefined;
  3055. });
  3056. return map$2(keys$1, function (k) {
  3057. return behaviours[k].me;
  3058. });
  3059. };
  3060. var generateFrom = function (spec, all) {
  3061. return generateFrom$1(spec, all);
  3062. };
  3063. var generate$4 = function (spec) {
  3064. var all = getBehaviours$2(spec);
  3065. return generateFrom(spec, all);
  3066. };
  3067. var getDomDefinition = function (info, bList, bData) {
  3068. var definition = toDefinition(info);
  3069. var infoModification = toModification(info);
  3070. var baseModification = { 'alloy.base.modification': infoModification };
  3071. var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
  3072. return merge(definition, modification);
  3073. };
  3074. var getEvents = function (info, bList, bData) {
  3075. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  3076. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  3077. };
  3078. var build$2 = function (spec) {
  3079. var getMe = function () {
  3080. return me;
  3081. };
  3082. var systemApi = Cell(singleton$1);
  3083. var info = getOrDie(toInfo(spec));
  3084. var bBlob = generate$4(spec);
  3085. var bList = getBehaviours$3(bBlob);
  3086. var bData = getData$2(bBlob);
  3087. var modDefinition = getDomDefinition(info, bList, bData);
  3088. var item = renderToDom(modDefinition);
  3089. var events = getEvents(info, bList, bData);
  3090. var subcomponents = Cell(info.components);
  3091. var connect = function (newApi) {
  3092. systemApi.set(newApi);
  3093. };
  3094. var disconnect = function () {
  3095. systemApi.set(NoContextApi(getMe));
  3096. };
  3097. var syncComponents = function () {
  3098. var children$1 = children(item);
  3099. var subs = bind$3(children$1, function (child) {
  3100. return systemApi.get().getByDom(child).fold(function () {
  3101. return [];
  3102. }, pure$2);
  3103. });
  3104. subcomponents.set(subs);
  3105. };
  3106. var config = function (behaviour) {
  3107. var b = bData;
  3108. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3109. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3110. };
  3111. return f();
  3112. };
  3113. var hasConfigured = function (behaviour) {
  3114. return isFunction(bData[behaviour.name()]);
  3115. };
  3116. var getApis = function () {
  3117. return info.apis;
  3118. };
  3119. var readState = function (behaviourName) {
  3120. return bData[behaviourName]().map(function (b) {
  3121. return b.state.readState();
  3122. }).getOr('not enabled');
  3123. };
  3124. var me = {
  3125. uid: spec.uid,
  3126. getSystem: systemApi.get,
  3127. config: config,
  3128. hasConfigured: hasConfigured,
  3129. spec: spec,
  3130. readState: readState,
  3131. getApis: getApis,
  3132. connect: connect,
  3133. disconnect: disconnect,
  3134. element: item,
  3135. syncComponents: syncComponents,
  3136. components: subcomponents.get,
  3137. events: events
  3138. };
  3139. return me;
  3140. };
  3141. var buildSubcomponents = function (spec) {
  3142. var components = get$e(spec, 'components').getOr([]);
  3143. return map$2(components, build$1);
  3144. };
  3145. var buildFromSpec = function (userSpec) {
  3146. var _a = make$8(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3147. var components = buildSubcomponents(spec);
  3148. var completeSpec = __assign(__assign({}, spec), {
  3149. events: __assign(__assign({}, DefaultEvents), specEvents),
  3150. components: components
  3151. });
  3152. return Result.value(build$2(completeSpec));
  3153. };
  3154. var text = function (textContent) {
  3155. var element = SugarElement.fromText(textContent);
  3156. return external$2({ element: element });
  3157. };
  3158. var external$2 = function (spec) {
  3159. var extSpec = asRawOrDie$1('external.component', objOfOnly([
  3160. required$1('element'),
  3161. option('uid')
  3162. ]), spec);
  3163. var systemApi = Cell(NoContextApi());
  3164. var connect = function (newApi) {
  3165. systemApi.set(newApi);
  3166. };
  3167. var disconnect = function () {
  3168. systemApi.set(NoContextApi(function () {
  3169. return me;
  3170. }));
  3171. };
  3172. var uid = extSpec.uid.getOrThunk(function () {
  3173. return generate$5('external');
  3174. });
  3175. writeOnly(extSpec.element, uid);
  3176. var me = {
  3177. uid: uid,
  3178. getSystem: systemApi.get,
  3179. config: Optional.none,
  3180. hasConfigured: never,
  3181. connect: connect,
  3182. disconnect: disconnect,
  3183. getApis: function () {
  3184. return {};
  3185. },
  3186. element: extSpec.element,
  3187. spec: spec,
  3188. readState: constant$1('No state'),
  3189. syncComponents: noop,
  3190. components: constant$1([]),
  3191. events: {}
  3192. };
  3193. return premade$1(me);
  3194. };
  3195. var uids = generate$5;
  3196. var isSketchSpec$1 = function (spec) {
  3197. return has$2(spec, 'uid');
  3198. };
  3199. var build$1 = function (spec) {
  3200. return getPremade(spec).getOrThunk(function () {
  3201. var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids('') }, spec);
  3202. return buildFromSpec(userSpecWithUid).getOrDie();
  3203. });
  3204. };
  3205. var premade = premade$1;
  3206. var Dimension = function (name, getOffset) {
  3207. var set = function (element, h) {
  3208. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3209. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3210. }
  3211. var dom = element.dom;
  3212. if (isSupported(dom)) {
  3213. dom.style[name] = h + 'px';
  3214. }
  3215. };
  3216. var get = function (element) {
  3217. var r = getOffset(element);
  3218. if (r <= 0 || r === null) {
  3219. var css = get$a(element, name);
  3220. return parseFloat(css) || 0;
  3221. }
  3222. return r;
  3223. };
  3224. var getOuter = get;
  3225. var aggregate = function (element, properties) {
  3226. return foldl(properties, function (acc, property) {
  3227. var val = get$a(element, property);
  3228. var value = val === undefined ? 0 : parseInt(val, 10);
  3229. return isNaN(value) ? acc : acc + value;
  3230. }, 0);
  3231. };
  3232. var max = function (element, value, properties) {
  3233. var cumulativeInclusions = aggregate(element, properties);
  3234. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3235. return absoluteMax;
  3236. };
  3237. return {
  3238. set: set,
  3239. get: get,
  3240. getOuter: getOuter,
  3241. aggregate: aggregate,
  3242. max: max
  3243. };
  3244. };
  3245. var api$2 = Dimension('height', function (element) {
  3246. var dom = element.dom;
  3247. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3248. });
  3249. var get$8 = function (element) {
  3250. return api$2.get(element);
  3251. };
  3252. var getOuter$1 = function (element) {
  3253. return api$2.getOuter(element);
  3254. };
  3255. var setMax$1 = function (element, value) {
  3256. var inclusions = [
  3257. 'margin-top',
  3258. 'border-top-width',
  3259. 'padding-top',
  3260. 'padding-bottom',
  3261. 'border-bottom-width',
  3262. 'margin-bottom'
  3263. ];
  3264. var absMax = api$2.max(element, value, inclusions);
  3265. set$6(element, 'max-height', absMax + 'px');
  3266. };
  3267. var r$1 = function (left, top) {
  3268. var translate = function (x, y) {
  3269. return r$1(left + x, top + y);
  3270. };
  3271. return {
  3272. left: left,
  3273. top: top,
  3274. translate: translate
  3275. };
  3276. };
  3277. var SugarPosition = r$1;
  3278. var boxPosition = function (dom) {
  3279. var box = dom.getBoundingClientRect();
  3280. return SugarPosition(box.left, box.top);
  3281. };
  3282. var firstDefinedOrZero = function (a, b) {
  3283. if (a !== undefined) {
  3284. return a;
  3285. } else {
  3286. return b !== undefined ? b : 0;
  3287. }
  3288. };
  3289. var absolute$3 = function (element) {
  3290. var doc = element.dom.ownerDocument;
  3291. var body = doc.body;
  3292. var win = doc.defaultView;
  3293. var html = doc.documentElement;
  3294. if (body === element.dom) {
  3295. return SugarPosition(body.offsetLeft, body.offsetTop);
  3296. }
  3297. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  3298. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  3299. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  3300. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  3301. return viewport$1(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  3302. };
  3303. var viewport$1 = function (element) {
  3304. var dom = element.dom;
  3305. var doc = dom.ownerDocument;
  3306. var body = doc.body;
  3307. if (body === dom) {
  3308. return SugarPosition(body.offsetLeft, body.offsetTop);
  3309. }
  3310. if (!inBody(element)) {
  3311. return SugarPosition(0, 0);
  3312. }
  3313. return boxPosition(dom);
  3314. };
  3315. var api$1 = Dimension('width', function (element) {
  3316. return element.dom.offsetWidth;
  3317. });
  3318. var set$4 = function (element, h) {
  3319. return api$1.set(element, h);
  3320. };
  3321. var get$7 = function (element) {
  3322. return api$1.get(element);
  3323. };
  3324. var getOuter = function (element) {
  3325. return api$1.getOuter(element);
  3326. };
  3327. var setMax = function (element, value) {
  3328. var inclusions = [
  3329. 'margin-left',
  3330. 'border-left-width',
  3331. 'padding-left',
  3332. 'padding-right',
  3333. 'border-right-width',
  3334. 'margin-right'
  3335. ];
  3336. var absMax = api$1.max(element, value, inclusions);
  3337. set$6(element, 'max-width', absMax + 'px');
  3338. };
  3339. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  3340. return {
  3341. target: target,
  3342. x: x,
  3343. y: y,
  3344. stop: stop,
  3345. prevent: prevent,
  3346. kill: kill,
  3347. raw: raw
  3348. };
  3349. };
  3350. var fromRawEvent$1 = function (rawEvent) {
  3351. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  3352. var stop = function () {
  3353. return rawEvent.stopPropagation();
  3354. };
  3355. var prevent = function () {
  3356. return rawEvent.preventDefault();
  3357. };
  3358. var kill = compose(prevent, stop);
  3359. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  3360. };
  3361. var handle = function (filter, handler) {
  3362. return function (rawEvent) {
  3363. if (filter(rawEvent)) {
  3364. handler(fromRawEvent$1(rawEvent));
  3365. }
  3366. };
  3367. };
  3368. var binder = function (element, event, filter, handler, useCapture) {
  3369. var wrapped = handle(filter, handler);
  3370. element.dom.addEventListener(event, wrapped, useCapture);
  3371. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  3372. };
  3373. var bind$1 = function (element, event, filter, handler) {
  3374. return binder(element, event, filter, handler, false);
  3375. };
  3376. var capture$1 = function (element, event, filter, handler) {
  3377. return binder(element, event, filter, handler, true);
  3378. };
  3379. var unbind = function (element, event, handler, useCapture) {
  3380. element.dom.removeEventListener(event, handler, useCapture);
  3381. };
  3382. var get$6 = function (_DOC) {
  3383. var doc = _DOC !== undefined ? _DOC.dom : document;
  3384. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  3385. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  3386. return SugarPosition(x, y);
  3387. };
  3388. var to = function (x, y, _DOC) {
  3389. var doc = _DOC !== undefined ? _DOC.dom : document;
  3390. var win = doc.defaultView;
  3391. if (win) {
  3392. win.scrollTo(x, y);
  3393. }
  3394. };
  3395. var get$5 = function (_win) {
  3396. var win = _win === undefined ? window : _win;
  3397. return Optional.from(win['visualViewport']);
  3398. };
  3399. var bounds$1 = function (x, y, width, height) {
  3400. return {
  3401. x: x,
  3402. y: y,
  3403. width: width,
  3404. height: height,
  3405. right: x + width,
  3406. bottom: y + height
  3407. };
  3408. };
  3409. var getBounds$3 = function (_win) {
  3410. var win = _win === undefined ? window : _win;
  3411. var doc = win.document;
  3412. var scroll = get$6(SugarElement.fromDom(doc));
  3413. return get$5(win).fold(function () {
  3414. var html = win.document.documentElement;
  3415. var width = html.clientWidth;
  3416. var height = html.clientHeight;
  3417. return bounds$1(scroll.left, scroll.top, width, height);
  3418. }, function (visualViewport) {
  3419. return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  3420. });
  3421. };
  3422. var walkUp = function (navigation, doc) {
  3423. var frame = navigation.view(doc);
  3424. return frame.fold(constant$1([]), function (f) {
  3425. var parent = navigation.owner(f);
  3426. var rest = walkUp(navigation, parent);
  3427. return [f].concat(rest);
  3428. });
  3429. };
  3430. var pathTo = function (element, navigation) {
  3431. var d = navigation.owner(element);
  3432. var paths = walkUp(navigation, d);
  3433. return Optional.some(paths);
  3434. };
  3435. var view = function (doc) {
  3436. var _a;
  3437. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  3438. return element.map(SugarElement.fromDom);
  3439. };
  3440. var owner$3 = function (element) {
  3441. return owner$4(element);
  3442. };
  3443. var Navigation = /*#__PURE__*/Object.freeze({
  3444. __proto__: null,
  3445. view: view,
  3446. owner: owner$3
  3447. });
  3448. var find$2 = function (element) {
  3449. var doc = SugarElement.fromDom(document);
  3450. var scroll = get$6(doc);
  3451. var path = pathTo(element, Navigation);
  3452. return path.fold(curry(absolute$3, element), function (frames) {
  3453. var offset = viewport$1(element);
  3454. var r = foldr(frames, function (b, a) {
  3455. var loc = viewport$1(a);
  3456. return {
  3457. left: b.left + loc.left,
  3458. top: b.top + loc.top
  3459. };
  3460. }, {
  3461. left: 0,
  3462. top: 0
  3463. });
  3464. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  3465. });
  3466. };
  3467. var pointed = function (point, width, height) {
  3468. return {
  3469. point: point,
  3470. width: width,
  3471. height: height
  3472. };
  3473. };
  3474. var rect = function (x, y, width, height) {
  3475. return {
  3476. x: x,
  3477. y: y,
  3478. width: width,
  3479. height: height
  3480. };
  3481. };
  3482. var bounds = function (x, y, width, height) {
  3483. return {
  3484. x: x,
  3485. y: y,
  3486. width: width,
  3487. height: height,
  3488. right: x + width,
  3489. bottom: y + height
  3490. };
  3491. };
  3492. var box$1 = function (element) {
  3493. var xy = absolute$3(element);
  3494. var w = getOuter(element);
  3495. var h = getOuter$1(element);
  3496. return bounds(xy.left, xy.top, w, h);
  3497. };
  3498. var absolute$2 = function (element) {
  3499. var position = find$2(element);
  3500. var width = getOuter(element);
  3501. var height = getOuter$1(element);
  3502. return bounds(position.left, position.top, width, height);
  3503. };
  3504. var win = function () {
  3505. return getBounds$3(window);
  3506. };
  3507. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3508. if (is(scope, a)) {
  3509. return Optional.some(scope);
  3510. } else if (isFunction(isRoot) && isRoot(scope)) {
  3511. return Optional.none();
  3512. } else {
  3513. return ancestor(scope, a, isRoot);
  3514. }
  3515. }
  3516. var ancestor$1 = function (scope, predicate, isRoot) {
  3517. var element = scope.dom;
  3518. var stop = isFunction(isRoot) ? isRoot : never;
  3519. while (element.parentNode) {
  3520. element = element.parentNode;
  3521. var el = SugarElement.fromDom(element);
  3522. if (predicate(el)) {
  3523. return Optional.some(el);
  3524. } else if (stop(el)) {
  3525. break;
  3526. }
  3527. }
  3528. return Optional.none();
  3529. };
  3530. var closest$3 = function (scope, predicate, isRoot) {
  3531. var is = function (s, test) {
  3532. return test(s);
  3533. };
  3534. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3535. };
  3536. var child$1 = function (scope, predicate) {
  3537. var pred = function (node) {
  3538. return predicate(SugarElement.fromDom(node));
  3539. };
  3540. var result = find$5(scope.dom.childNodes, pred);
  3541. return result.map(SugarElement.fromDom);
  3542. };
  3543. var descendant$1 = function (scope, predicate) {
  3544. var descend = function (node) {
  3545. for (var i = 0; i < node.childNodes.length; i++) {
  3546. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3547. if (predicate(child_1)) {
  3548. return Optional.some(child_1);
  3549. }
  3550. var res = descend(node.childNodes[i]);
  3551. if (res.isSome()) {
  3552. return res;
  3553. }
  3554. }
  3555. return Optional.none();
  3556. };
  3557. return descend(scope.dom);
  3558. };
  3559. var closest$2 = function (scope, predicate, isRoot) {
  3560. return closest$3(scope, predicate, isRoot).isSome();
  3561. };
  3562. var ancestor = function (scope, selector, isRoot) {
  3563. return ancestor$1(scope, function (e) {
  3564. return is$1(e, selector);
  3565. }, isRoot);
  3566. };
  3567. var child = function (scope, selector) {
  3568. return child$1(scope, function (e) {
  3569. return is$1(e, selector);
  3570. });
  3571. };
  3572. var descendant = function (scope, selector) {
  3573. return one(selector, scope);
  3574. };
  3575. var closest$1 = function (scope, selector, isRoot) {
  3576. var is = function (element, selector) {
  3577. return is$1(element, selector);
  3578. };
  3579. return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
  3580. };
  3581. var find$1 = function (queryElem) {
  3582. var dependent = closest$3(queryElem, function (elem) {
  3583. if (!isElement$2(elem)) {
  3584. return false;
  3585. }
  3586. var id = get$c(elem, 'id');
  3587. return id !== undefined && id.indexOf('aria-owns') > -1;
  3588. });
  3589. return dependent.bind(function (dep) {
  3590. var id = get$c(dep, 'id');
  3591. var dos = getRootNode(dep);
  3592. return descendant(dos, '[aria-owns="' + id + '"]');
  3593. });
  3594. };
  3595. var manager = function () {
  3596. var ariaId = generate$6('aria-owns');
  3597. var link = function (elem) {
  3598. set$7(elem, 'aria-owns', ariaId);
  3599. };
  3600. var unlink = function (elem) {
  3601. remove$6(elem, 'aria-owns');
  3602. };
  3603. return {
  3604. id: ariaId,
  3605. link: link,
  3606. unlink: unlink
  3607. };
  3608. };
  3609. var isAriaPartOf = function (component, queryElem) {
  3610. return find$1(queryElem).exists(function (owner) {
  3611. return isPartOf$1(component, owner);
  3612. });
  3613. };
  3614. var isPartOf$1 = function (component, queryElem) {
  3615. return closest$2(queryElem, function (el) {
  3616. return eq(el, component.element);
  3617. }, never) || isAriaPartOf(component, queryElem);
  3618. };
  3619. var unknown = 'unknown';
  3620. var EventConfiguration;
  3621. (function (EventConfiguration) {
  3622. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3623. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3624. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3625. }(EventConfiguration || (EventConfiguration = {})));
  3626. var eventConfig = Cell({});
  3627. var makeEventLogger = function (eventName, initialTarget) {
  3628. var sequence = [];
  3629. var startTime = new Date().getTime();
  3630. return {
  3631. logEventCut: function (_name, target, purpose) {
  3632. sequence.push({
  3633. outcome: 'cut',
  3634. target: target,
  3635. purpose: purpose
  3636. });
  3637. },
  3638. logEventStopped: function (_name, target, purpose) {
  3639. sequence.push({
  3640. outcome: 'stopped',
  3641. target: target,
  3642. purpose: purpose
  3643. });
  3644. },
  3645. logNoParent: function (_name, target, purpose) {
  3646. sequence.push({
  3647. outcome: 'no-parent',
  3648. target: target,
  3649. purpose: purpose
  3650. });
  3651. },
  3652. logEventNoHandlers: function (_name, target) {
  3653. sequence.push({
  3654. outcome: 'no-handlers-left',
  3655. target: target
  3656. });
  3657. },
  3658. logEventResponse: function (_name, target, purpose) {
  3659. sequence.push({
  3660. outcome: 'response',
  3661. purpose: purpose,
  3662. target: target
  3663. });
  3664. },
  3665. write: function () {
  3666. var finishTime = new Date().getTime();
  3667. if (contains$2([
  3668. 'mousemove',
  3669. 'mouseover',
  3670. 'mouseout',
  3671. systemInit()
  3672. ], eventName)) {
  3673. return;
  3674. }
  3675. console.log(eventName, {
  3676. event: eventName,
  3677. time: finishTime - startTime,
  3678. target: initialTarget.dom,
  3679. sequence: map$2(sequence, function (s) {
  3680. if (!contains$2([
  3681. 'cut',
  3682. 'stopped',
  3683. 'response'
  3684. ], s.outcome)) {
  3685. return s.outcome;
  3686. } else {
  3687. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3688. }
  3689. })
  3690. });
  3691. }
  3692. };
  3693. };
  3694. var processEvent = function (eventName, initialTarget, f) {
  3695. var status = get$e(eventConfig.get(), eventName).orThunk(function () {
  3696. var patterns = keys(eventConfig.get());
  3697. return findMap(patterns, function (p) {
  3698. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  3699. });
  3700. }).getOr(EventConfiguration.NORMAL);
  3701. switch (status) {
  3702. case EventConfiguration.NORMAL:
  3703. return f(noLogger());
  3704. case EventConfiguration.LOGGING: {
  3705. var logger = makeEventLogger(eventName, initialTarget);
  3706. var output = f(logger);
  3707. logger.write();
  3708. return output;
  3709. }
  3710. case EventConfiguration.STOP:
  3711. return true;
  3712. }
  3713. };
  3714. var path = [
  3715. 'alloy/data/Fields',
  3716. 'alloy/debugging/Debugging'
  3717. ];
  3718. var getTrace = function () {
  3719. var err = new Error();
  3720. if (err.stack !== undefined) {
  3721. var lines = err.stack.split('\n');
  3722. return find$5(lines, function (line) {
  3723. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3724. return line.indexOf(p) > -1;
  3725. });
  3726. }).getOr(unknown);
  3727. } else {
  3728. return unknown;
  3729. }
  3730. };
  3731. var ignoreEvent = {
  3732. logEventCut: noop,
  3733. logEventStopped: noop,
  3734. logNoParent: noop,
  3735. logEventNoHandlers: noop,
  3736. logEventResponse: noop,
  3737. write: noop
  3738. };
  3739. var monitorEvent = function (eventName, initialTarget, f) {
  3740. return processEvent(eventName, initialTarget, f);
  3741. };
  3742. var noLogger = constant$1(ignoreEvent);
  3743. var menuFields = constant$1([
  3744. required$1('menu'),
  3745. required$1('selectedMenu')
  3746. ]);
  3747. var itemFields = constant$1([
  3748. required$1('item'),
  3749. required$1('selectedItem')
  3750. ]);
  3751. constant$1(objOf(itemFields().concat(menuFields())));
  3752. var itemSchema$3 = constant$1(objOf(itemFields()));
  3753. var _initSize = requiredObjOf('initSize', [
  3754. required$1('numColumns'),
  3755. required$1('numRows')
  3756. ]);
  3757. var itemMarkers = function () {
  3758. return requiredOf('markers', itemSchema$3());
  3759. };
  3760. var tieredMenuMarkers = function () {
  3761. return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3762. };
  3763. var markers$1 = function (required) {
  3764. return requiredObjOf('markers', map$2(required, required$1));
  3765. };
  3766. var onPresenceHandler = function (label, fieldName, presence) {
  3767. getTrace();
  3768. return field$1(fieldName, fieldName, presence, valueOf(function (f) {
  3769. return Result.value(function () {
  3770. var args = [];
  3771. for (var _i = 0; _i < arguments.length; _i++) {
  3772. args[_i] = arguments[_i];
  3773. }
  3774. return f.apply(undefined, args);
  3775. });
  3776. }));
  3777. };
  3778. var onHandler = function (fieldName) {
  3779. return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  3780. };
  3781. var onKeyboardHandler = function (fieldName) {
  3782. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  3783. };
  3784. var onStrictHandler = function (fieldName) {
  3785. return onPresenceHandler('onHandler', fieldName, required$2());
  3786. };
  3787. var onStrictKeyboardHandler = function (fieldName) {
  3788. return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  3789. };
  3790. var output$1 = function (name, value) {
  3791. return customField(name, constant$1(value));
  3792. };
  3793. var snapshot = function (name) {
  3794. return customField(name, identity$1);
  3795. };
  3796. var initSize = constant$1(_initSize);
  3797. var nu$6 = function (x, y, bubble, direction, placement, boundsRestriction, labelPrefix, alwaysFit) {
  3798. if (alwaysFit === void 0) {
  3799. alwaysFit = false;
  3800. }
  3801. return {
  3802. x: x,
  3803. y: y,
  3804. bubble: bubble,
  3805. direction: direction,
  3806. placement: placement,
  3807. restriction: boundsRestriction,
  3808. label: labelPrefix + '-' + placement,
  3809. alwaysFit: alwaysFit
  3810. };
  3811. };
  3812. var adt$a = Adt.generate([
  3813. { southeast: [] },
  3814. { southwest: [] },
  3815. { northeast: [] },
  3816. { northwest: [] },
  3817. { south: [] },
  3818. { north: [] },
  3819. { east: [] },
  3820. { west: [] }
  3821. ]);
  3822. var cata$2 = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3823. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3824. };
  3825. var cataVertical = function (subject, south, middle, north) {
  3826. return subject.fold(south, south, north, north, south, north, middle, middle);
  3827. };
  3828. var cataHorizontal = function (subject, east, middle, west) {
  3829. return subject.fold(east, west, east, west, middle, middle, east, west);
  3830. };
  3831. var southeast$3 = adt$a.southeast;
  3832. var southwest$3 = adt$a.southwest;
  3833. var northeast$3 = adt$a.northeast;
  3834. var northwest$3 = adt$a.northwest;
  3835. var south$3 = adt$a.south;
  3836. var north$3 = adt$a.north;
  3837. var east$3 = adt$a.east;
  3838. var west$3 = adt$a.west;
  3839. var cycleBy = function (value, delta, min, max) {
  3840. var r = value + delta;
  3841. if (r > max) {
  3842. return min;
  3843. } else if (r < min) {
  3844. return max;
  3845. } else {
  3846. return r;
  3847. }
  3848. };
  3849. var clamp$1 = function (value, min, max) {
  3850. return Math.min(Math.max(value, min), max);
  3851. };
  3852. var getRestriction = function (anchor, restriction) {
  3853. switch (restriction) {
  3854. case 1:
  3855. return anchor.x;
  3856. case 0:
  3857. return anchor.x + anchor.width;
  3858. case 2:
  3859. return anchor.y;
  3860. case 3:
  3861. return anchor.y + anchor.height;
  3862. }
  3863. };
  3864. var boundsRestriction = function (anchor, restrictions) {
  3865. return mapToObject([
  3866. 'left',
  3867. 'right',
  3868. 'top',
  3869. 'bottom'
  3870. ], function (dir) {
  3871. return get$e(restrictions, dir).map(function (restriction) {
  3872. return getRestriction(anchor, restriction);
  3873. });
  3874. });
  3875. };
  3876. var adjustBounds = function (bounds$1, restriction, bubbleOffset) {
  3877. var applyRestriction = function (dir, current) {
  3878. return restriction[dir].map(function (pos) {
  3879. var isVerticalAxis = dir === 'top' || dir === 'bottom';
  3880. var offset = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
  3881. var comparator = dir === 'left' || dir === 'top' ? Math.max : Math.min;
  3882. var newPos = comparator(pos, current) + offset;
  3883. return isVerticalAxis ? clamp$1(newPos, bounds$1.y, bounds$1.bottom) : clamp$1(newPos, bounds$1.x, bounds$1.right);
  3884. }).getOr(current);
  3885. };
  3886. var adjustedLeft = applyRestriction('left', bounds$1.x);
  3887. var adjustedTop = applyRestriction('top', bounds$1.y);
  3888. var adjustedRight = applyRestriction('right', bounds$1.right);
  3889. var adjustedBottom = applyRestriction('bottom', bounds$1.bottom);
  3890. return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  3891. };
  3892. var labelPrefix$2 = 'layout';
  3893. var eastX$1 = function (anchor) {
  3894. return anchor.x;
  3895. };
  3896. var middleX$1 = function (anchor, element) {
  3897. return anchor.x + anchor.width / 2 - element.width / 2;
  3898. };
  3899. var westX$1 = function (anchor, element) {
  3900. return anchor.x + anchor.width - element.width;
  3901. };
  3902. var northY$2 = function (anchor, element) {
  3903. return anchor.y - element.height;
  3904. };
  3905. var southY$2 = function (anchor) {
  3906. return anchor.y + anchor.height;
  3907. };
  3908. var centreY$1 = function (anchor, element) {
  3909. return anchor.y + anchor.height / 2 - element.height / 2;
  3910. };
  3911. var eastEdgeX$1 = function (anchor) {
  3912. return anchor.x + anchor.width;
  3913. };
  3914. var westEdgeX$1 = function (anchor, element) {
  3915. return anchor.x - element.width;
  3916. };
  3917. var southeast$2 = function (anchor, element, bubbles) {
  3918. return nu$6(eastX$1(anchor), southY$2(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  3919. left: 1,
  3920. top: 3
  3921. }), labelPrefix$2);
  3922. };
  3923. var southwest$2 = function (anchor, element, bubbles) {
  3924. return nu$6(westX$1(anchor, element), southY$2(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  3925. right: 0,
  3926. top: 3
  3927. }), labelPrefix$2);
  3928. };
  3929. var northeast$2 = function (anchor, element, bubbles) {
  3930. return nu$6(eastX$1(anchor), northY$2(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  3931. left: 1,
  3932. bottom: 2
  3933. }), labelPrefix$2);
  3934. };
  3935. var northwest$2 = function (anchor, element, bubbles) {
  3936. return nu$6(westX$1(anchor, element), northY$2(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  3937. right: 0,
  3938. bottom: 2
  3939. }), labelPrefix$2);
  3940. };
  3941. var north$2 = function (anchor, element, bubbles) {
  3942. return nu$6(middleX$1(anchor, element), northY$2(anchor, element), bubbles.north(), north$3(), 'north', boundsRestriction(anchor, { bottom: 2 }), labelPrefix$2);
  3943. };
  3944. var south$2 = function (anchor, element, bubbles) {
  3945. return nu$6(middleX$1(anchor, element), southY$2(anchor), bubbles.south(), south$3(), 'south', boundsRestriction(anchor, { top: 3 }), labelPrefix$2);
  3946. };
  3947. var east$2 = function (anchor, element, bubbles) {
  3948. return nu$6(eastEdgeX$1(anchor), centreY$1(anchor, element), bubbles.east(), east$3(), 'east', boundsRestriction(anchor, { left: 0 }), labelPrefix$2);
  3949. };
  3950. var west$2 = function (anchor, element, bubbles) {
  3951. return nu$6(westEdgeX$1(anchor, element), centreY$1(anchor, element), bubbles.west(), west$3(), 'west', boundsRestriction(anchor, { right: 1 }), labelPrefix$2);
  3952. };
  3953. var all$1 = function () {
  3954. return [
  3955. southeast$2,
  3956. southwest$2,
  3957. northeast$2,
  3958. northwest$2,
  3959. south$2,
  3960. north$2,
  3961. east$2,
  3962. west$2
  3963. ];
  3964. };
  3965. var allRtl$1 = function () {
  3966. return [
  3967. southwest$2,
  3968. southeast$2,
  3969. northwest$2,
  3970. northeast$2,
  3971. south$2,
  3972. north$2,
  3973. east$2,
  3974. west$2
  3975. ];
  3976. };
  3977. var aboveOrBelow = function () {
  3978. return [
  3979. northeast$2,
  3980. northwest$2,
  3981. southeast$2,
  3982. southwest$2,
  3983. north$2,
  3984. south$2
  3985. ];
  3986. };
  3987. var aboveOrBelowRtl = function () {
  3988. return [
  3989. northwest$2,
  3990. northeast$2,
  3991. southwest$2,
  3992. southeast$2,
  3993. north$2,
  3994. south$2
  3995. ];
  3996. };
  3997. var belowOrAbove = function () {
  3998. return [
  3999. southeast$2,
  4000. southwest$2,
  4001. northeast$2,
  4002. northwest$2,
  4003. south$2,
  4004. north$2
  4005. ];
  4006. };
  4007. var belowOrAboveRtl = function () {
  4008. return [
  4009. southwest$2,
  4010. southeast$2,
  4011. northwest$2,
  4012. northeast$2,
  4013. south$2,
  4014. north$2
  4015. ];
  4016. };
  4017. var chooseChannels = function (channels, message) {
  4018. return message.universal ? channels : filter$2(channels, function (ch) {
  4019. return contains$2(message.channels, ch);
  4020. });
  4021. };
  4022. var events$h = function (receiveConfig) {
  4023. return derive$2([run$1(receive(), function (component, message) {
  4024. var channelMap = receiveConfig.channels;
  4025. var channels = keys(channelMap);
  4026. var receivingData = message;
  4027. var targetChannels = chooseChannels(channels, receivingData);
  4028. each$1(targetChannels, function (ch) {
  4029. var channelInfo = channelMap[ch];
  4030. var channelSchema = channelInfo.schema;
  4031. var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  4032. channelInfo.onReceive(component, data);
  4033. });
  4034. })]);
  4035. };
  4036. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  4037. __proto__: null,
  4038. events: events$h
  4039. });
  4040. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  4041. onStrictHandler('onReceive'),
  4042. defaulted('schema', anyValue())
  4043. ])))];
  4044. var executeEvent = function (bConfig, bState, executor) {
  4045. return runOnExecute$1(function (component) {
  4046. executor(component, bConfig, bState);
  4047. });
  4048. };
  4049. var loadEvent = function (bConfig, bState, f) {
  4050. return runOnInit(function (component, _simulatedEvent) {
  4051. f(component, bConfig, bState);
  4052. });
  4053. };
  4054. var create$8 = function (schema, name, active, apis, extra, state) {
  4055. var configSchema = objOfOnly(schema);
  4056. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  4057. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4058. };
  4059. var createModes$1 = function (modes, name, active, apis, extra, state) {
  4060. var configSchema = modes;
  4061. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  4062. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4063. };
  4064. var wrapApi = function (bName, apiFunction, apiName) {
  4065. var f = function (component) {
  4066. var rest = [];
  4067. for (var _i = 1; _i < arguments.length; _i++) {
  4068. rest[_i - 1] = arguments[_i];
  4069. }
  4070. var args = [component].concat(rest);
  4071. return component.config({ name: constant$1(bName) }).fold(function () {
  4072. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  4073. }, function (info) {
  4074. var rest = Array.prototype.slice.call(args, 1);
  4075. return apiFunction.apply(undefined, [
  4076. component,
  4077. info.config,
  4078. info.state
  4079. ].concat(rest));
  4080. });
  4081. };
  4082. return markAsBehaviourApi(f, apiName, apiFunction);
  4083. };
  4084. var revokeBehaviour = function (name) {
  4085. return {
  4086. key: name,
  4087. value: undefined
  4088. };
  4089. };
  4090. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  4091. var getConfig = function (info) {
  4092. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  4093. };
  4094. var wrappedApis = map(apis, function (apiF, apiName) {
  4095. return wrapApi(name, apiF, apiName);
  4096. });
  4097. var wrappedExtra = map(extra, function (extraF, extraName) {
  4098. return markAsExtraApi(extraF, extraName);
  4099. });
  4100. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  4101. revoke: curry(revokeBehaviour, name),
  4102. config: function (spec) {
  4103. var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  4104. return {
  4105. key: name,
  4106. value: {
  4107. config: prepared,
  4108. me: me,
  4109. configAsRaw: cached(function () {
  4110. return asRawOrDie$1(name + '-config', configSchema, spec);
  4111. }),
  4112. initialConfig: spec,
  4113. state: state
  4114. }
  4115. };
  4116. },
  4117. schema: constant$1(schemaSchema),
  4118. exhibit: function (info, base) {
  4119. return lift2(getConfig(info), get$e(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  4120. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  4121. }).getOrThunk(function () {
  4122. return nu$7({});
  4123. });
  4124. },
  4125. name: constant$1(name),
  4126. handlers: function (info) {
  4127. return getConfig(info).map(function (behaviourInfo) {
  4128. var getEvents = get$e(active, 'events').getOr(function () {
  4129. return {};
  4130. });
  4131. return getEvents(behaviourInfo.config, behaviourInfo.state);
  4132. }).getOr({});
  4133. }
  4134. });
  4135. return me;
  4136. };
  4137. var derive$1 = function (capabilities) {
  4138. return wrapAll(capabilities);
  4139. };
  4140. var simpleSchema = objOfOnly([
  4141. required$1('fields'),
  4142. required$1('name'),
  4143. defaulted('active', {}),
  4144. defaulted('apis', {}),
  4145. defaulted('state', NoState),
  4146. defaulted('extra', {})
  4147. ]);
  4148. var create$7 = function (data) {
  4149. var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  4150. return create$8(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  4151. };
  4152. var modeSchema = objOfOnly([
  4153. required$1('branchKey'),
  4154. required$1('branches'),
  4155. required$1('name'),
  4156. defaulted('active', {}),
  4157. defaulted('apis', {}),
  4158. defaulted('state', NoState),
  4159. defaulted('extra', {})
  4160. ]);
  4161. var createModes = function (data) {
  4162. var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  4163. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  4164. };
  4165. var revoke = constant$1(undefined);
  4166. var Receiving = create$7({
  4167. fields: ReceivingSchema,
  4168. name: 'receiving',
  4169. active: ActiveReceiving
  4170. });
  4171. var exhibit$6 = function (base, posConfig) {
  4172. return nu$7({
  4173. classes: [],
  4174. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  4175. });
  4176. };
  4177. var ActivePosition = /*#__PURE__*/Object.freeze({
  4178. __proto__: null,
  4179. exhibit: exhibit$6
  4180. });
  4181. var getDocument = function () {
  4182. return SugarElement.fromDom(document);
  4183. };
  4184. var focus$3 = function (element) {
  4185. return element.dom.focus();
  4186. };
  4187. var blur$1 = function (element) {
  4188. return element.dom.blur();
  4189. };
  4190. var hasFocus = function (element) {
  4191. var root = getRootNode(element).dom;
  4192. return element.dom === root.activeElement;
  4193. };
  4194. var active = function (root) {
  4195. if (root === void 0) {
  4196. root = getDocument();
  4197. }
  4198. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  4199. };
  4200. var search = function (element) {
  4201. return active(getRootNode(element)).filter(function (e) {
  4202. return element.dom.contains(e.dom);
  4203. });
  4204. };
  4205. var preserve$1 = function (f, container) {
  4206. var dos = getRootNode(container);
  4207. var refocus = active(dos).bind(function (focused) {
  4208. var hasFocus = function (elem) {
  4209. return eq(focused, elem);
  4210. };
  4211. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  4212. });
  4213. var result = f(container);
  4214. refocus.each(function (oldFocus) {
  4215. active(dos).filter(function (newFocus) {
  4216. return eq(newFocus, oldFocus);
  4217. }).fold(function () {
  4218. focus$3(oldFocus);
  4219. }, noop);
  4220. });
  4221. return result;
  4222. };
  4223. var NuPositionCss = function (position, left, top, right, bottom) {
  4224. var toPx = function (num) {
  4225. return num + 'px';
  4226. };
  4227. return {
  4228. position: position,
  4229. left: left.map(toPx),
  4230. top: top.map(toPx),
  4231. right: right.map(toPx),
  4232. bottom: bottom.map(toPx)
  4233. };
  4234. };
  4235. var toOptions = function (position) {
  4236. return __assign(__assign({}, position), { position: Optional.some(position.position) });
  4237. };
  4238. var applyPositionCss = function (element, position) {
  4239. setOptions(element, toOptions(position));
  4240. };
  4241. var adt$9 = Adt.generate([
  4242. { none: [] },
  4243. {
  4244. relative: [
  4245. 'x',
  4246. 'y',
  4247. 'width',
  4248. 'height'
  4249. ]
  4250. },
  4251. {
  4252. fixed: [
  4253. 'x',
  4254. 'y',
  4255. 'width',
  4256. 'height'
  4257. ]
  4258. }
  4259. ]);
  4260. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4261. var decisionRect = decision.rect;
  4262. var decisionX = decisionRect.x - x;
  4263. var decisionY = decisionRect.y - y;
  4264. var decisionWidth = decisionRect.width;
  4265. var decisionHeight = decisionRect.height;
  4266. var decisionRight = width - (decisionX + decisionWidth);
  4267. var decisionBottom = height - (decisionY + decisionHeight);
  4268. var left = Optional.some(decisionX);
  4269. var top = Optional.some(decisionY);
  4270. var right = Optional.some(decisionRight);
  4271. var bottom = Optional.some(decisionBottom);
  4272. var none = Optional.none();
  4273. return cata$2(decision.direction, function () {
  4274. return NuPositionCss(posName, left, top, none, none);
  4275. }, function () {
  4276. return NuPositionCss(posName, none, top, right, none);
  4277. }, function () {
  4278. return NuPositionCss(posName, left, none, none, bottom);
  4279. }, function () {
  4280. return NuPositionCss(posName, none, none, right, bottom);
  4281. }, function () {
  4282. return NuPositionCss(posName, left, top, none, none);
  4283. }, function () {
  4284. return NuPositionCss(posName, left, none, none, bottom);
  4285. }, function () {
  4286. return NuPositionCss(posName, left, top, none, none);
  4287. }, function () {
  4288. return NuPositionCss(posName, none, top, right, none);
  4289. });
  4290. };
  4291. var reposition = function (origin, decision) {
  4292. return origin.fold(function () {
  4293. var decisionRect = decision.rect;
  4294. return NuPositionCss('absolute', Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
  4295. }, function (x, y, width, height) {
  4296. return positionWithDirection('absolute', decision, x, y, width, height);
  4297. }, function (x, y, width, height) {
  4298. return positionWithDirection('fixed', decision, x, y, width, height);
  4299. });
  4300. };
  4301. var toBox = function (origin, element) {
  4302. var rel = curry(find$2, element);
  4303. var position = origin.fold(rel, rel, function () {
  4304. var scroll = get$6();
  4305. return find$2(element).translate(-scroll.left, -scroll.top);
  4306. });
  4307. var width = getOuter(element);
  4308. var height = getOuter$1(element);
  4309. return bounds(position.left, position.top, width, height);
  4310. };
  4311. var viewport = function (origin, getBounds) {
  4312. return getBounds.fold(function () {
  4313. return origin.fold(win, win, bounds);
  4314. }, function (b) {
  4315. return origin.fold(b, b, function () {
  4316. var bounds$1 = b();
  4317. var pos = translate$2(origin, bounds$1.x, bounds$1.y);
  4318. return bounds(pos.left, pos.top, bounds$1.width, bounds$1.height);
  4319. });
  4320. });
  4321. };
  4322. var translate$2 = function (origin, x, y) {
  4323. var pos = SugarPosition(x, y);
  4324. var removeScroll = function () {
  4325. var outerScroll = get$6();
  4326. return pos.translate(-outerScroll.left, -outerScroll.top);
  4327. };
  4328. return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
  4329. };
  4330. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4331. return subject.fold(onNone, onRelative, onFixed);
  4332. };
  4333. adt$9.none;
  4334. var relative$1 = adt$9.relative;
  4335. var fixed$1 = adt$9.fixed;
  4336. var anchor = function (anchorBox, origin) {
  4337. return {
  4338. anchorBox: anchorBox,
  4339. origin: origin
  4340. };
  4341. };
  4342. var box = function (anchorBox, origin) {
  4343. return anchor(anchorBox, origin);
  4344. };
  4345. var placementAttribute = 'data-alloy-placement';
  4346. var setPlacement$1 = function (element, placement) {
  4347. set$7(element, placementAttribute, placement);
  4348. };
  4349. var getPlacement = function (element) {
  4350. return getOpt(element, placementAttribute);
  4351. };
  4352. var reset$2 = function (element) {
  4353. return remove$6(element, placementAttribute);
  4354. };
  4355. var adt$8 = Adt.generate([
  4356. { fit: ['reposition'] },
  4357. {
  4358. nofit: [
  4359. 'reposition',
  4360. 'visibleW',
  4361. 'visibleH',
  4362. 'isVisible'
  4363. ]
  4364. }
  4365. ]);
  4366. var determinePosition = function (box, bounds) {
  4367. var boundsX = bounds.x, boundsY = bounds.y, boundsRight = bounds.right, boundsBottom = bounds.bottom;
  4368. var x = box.x, y = box.y, right = box.right, bottom = box.bottom, width = box.width, height = box.height;
  4369. var xInBounds = x >= boundsX && x <= boundsRight;
  4370. var yInBounds = y >= boundsY && y <= boundsBottom;
  4371. var originInBounds = xInBounds && yInBounds;
  4372. var rightInBounds = right <= boundsRight && right >= boundsX;
  4373. var bottomInBounds = bottom <= boundsBottom && bottom >= boundsY;
  4374. var sizeInBounds = rightInBounds && bottomInBounds;
  4375. var visibleW = Math.min(width, x >= boundsX ? boundsRight - x : right - boundsX);
  4376. var visibleH = Math.min(height, y >= boundsY ? boundsBottom - y : bottom - boundsY);
  4377. return {
  4378. originInBounds: originInBounds,
  4379. sizeInBounds: sizeInBounds,
  4380. visibleW: visibleW,
  4381. visibleH: visibleH
  4382. };
  4383. };
  4384. var calcReposition = function (box, bounds$1) {
  4385. var boundsX = bounds$1.x, boundsY = bounds$1.y, boundsRight = bounds$1.right, boundsBottom = bounds$1.bottom;
  4386. var x = box.x, y = box.y, width = box.width, height = box.height;
  4387. var maxX = Math.max(boundsX, boundsRight - width);
  4388. var maxY = Math.max(boundsY, boundsBottom - height);
  4389. var restrictedX = clamp$1(x, boundsX, maxX);
  4390. var restrictedY = clamp$1(y, boundsY, maxY);
  4391. var restrictedWidth = Math.min(restrictedX + width, boundsRight) - restrictedX;
  4392. var restrictedHeight = Math.min(restrictedY + height, boundsBottom) - restrictedY;
  4393. return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
  4394. };
  4395. var calcMaxSizes = function (direction, box, bounds) {
  4396. var upAvailable = constant$1(box.bottom - bounds.y);
  4397. var downAvailable = constant$1(bounds.bottom - box.y);
  4398. var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
  4399. var westAvailable = constant$1(box.right - bounds.x);
  4400. var eastAvailable = constant$1(bounds.right - box.x);
  4401. var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
  4402. return {
  4403. maxWidth: maxWidth,
  4404. maxHeight: maxHeight
  4405. };
  4406. };
  4407. var attempt = function (candidate, width, height, bounds$1) {
  4408. var bubble = candidate.bubble;
  4409. var bubbleOffset = bubble.offset;
  4410. var adjustedBounds = adjustBounds(bounds$1, candidate.restriction, bubbleOffset);
  4411. var newX = candidate.x + bubbleOffset.left;
  4412. var newY = candidate.y + bubbleOffset.top;
  4413. var box = bounds(newX, newY, width, height);
  4414. var _a = determinePosition(box, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, visibleW = _a.visibleW, visibleH = _a.visibleH;
  4415. var fits = originInBounds && sizeInBounds;
  4416. var fittedBox = fits ? box : calcReposition(box, adjustedBounds);
  4417. var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
  4418. var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$1), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight;
  4419. var reposition = {
  4420. rect: fittedBox,
  4421. maxHeight: maxHeight,
  4422. maxWidth: maxWidth,
  4423. direction: candidate.direction,
  4424. placement: candidate.placement,
  4425. classes: {
  4426. on: bubble.classesOn,
  4427. off: bubble.classesOff
  4428. },
  4429. layout: candidate.label,
  4430. testY: newY
  4431. };
  4432. return fits || candidate.alwaysFit ? adt$8.fit(reposition) : adt$8.nofit(reposition, visibleW, visibleH, isPartlyVisible);
  4433. };
  4434. var attempts = function (element, candidates, anchorBox, elementBox, bubbles, bounds) {
  4435. var panelWidth = elementBox.width;
  4436. var panelHeight = elementBox.height;
  4437. var attemptBestFit = function (layout, reposition, visibleW, visibleH, isVisible) {
  4438. var next = layout(anchorBox, elementBox, bubbles, element, bounds);
  4439. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4440. return attemptLayout.fold(constant$1(attemptLayout), function (newReposition, newVisibleW, newVisibleH, newIsVisible) {
  4441. var improved = isVisible === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible && newIsVisible;
  4442. return improved ? attemptLayout : adt$8.nofit(reposition, visibleW, visibleH, isVisible);
  4443. });
  4444. };
  4445. var abc = foldl(candidates, function (b, a) {
  4446. var bestNext = curry(attemptBestFit, a);
  4447. return b.fold(constant$1(b), bestNext);
  4448. }, adt$8.nofit({
  4449. rect: anchorBox,
  4450. maxHeight: elementBox.height,
  4451. maxWidth: elementBox.width,
  4452. direction: southeast$3(),
  4453. placement: 'southeast',
  4454. classes: {
  4455. on: [],
  4456. off: []
  4457. },
  4458. layout: 'none',
  4459. testY: anchorBox.y
  4460. }, -1, -1, false));
  4461. return abc.fold(identity$1, identity$1);
  4462. };
  4463. var singleton = function (doRevoke) {
  4464. var subject = Cell(Optional.none());
  4465. var revoke = function () {
  4466. return subject.get().each(doRevoke);
  4467. };
  4468. var clear = function () {
  4469. revoke();
  4470. subject.set(Optional.none());
  4471. };
  4472. var isSet = function () {
  4473. return subject.get().isSome();
  4474. };
  4475. var get = function () {
  4476. return subject.get();
  4477. };
  4478. var set = function (s) {
  4479. revoke();
  4480. subject.set(Optional.some(s));
  4481. };
  4482. return {
  4483. clear: clear,
  4484. isSet: isSet,
  4485. get: get,
  4486. set: set
  4487. };
  4488. };
  4489. var destroyable = function () {
  4490. return singleton(function (s) {
  4491. return s.destroy();
  4492. });
  4493. };
  4494. var unbindable = function () {
  4495. return singleton(function (s) {
  4496. return s.unbind();
  4497. });
  4498. };
  4499. var value$1 = function () {
  4500. var subject = singleton(noop);
  4501. var on = function (f) {
  4502. return subject.get().each(f);
  4503. };
  4504. return __assign(__assign({}, subject), { on: on });
  4505. };
  4506. var filter = always;
  4507. var bind = function (element, event, handler) {
  4508. return bind$1(element, event, filter, handler);
  4509. };
  4510. var capture = function (element, event, handler) {
  4511. return capture$1(element, event, filter, handler);
  4512. };
  4513. var fromRawEvent = fromRawEvent$1;
  4514. var properties = [
  4515. 'top',
  4516. 'bottom',
  4517. 'right',
  4518. 'left'
  4519. ];
  4520. var timerAttr = 'data-alloy-transition-timer';
  4521. var isTransitioning$1 = function (element, transition) {
  4522. return hasAll(element, transition.classes);
  4523. };
  4524. var shouldApplyTransitionCss = function (transition, decision, lastPlacement) {
  4525. return lastPlacement.exists(function (placer) {
  4526. var mode = transition.mode;
  4527. return mode === 'all' ? true : placer[mode] !== decision[mode];
  4528. });
  4529. };
  4530. var hasChanges = function (position, intermediate) {
  4531. var round = function (value) {
  4532. return parseFloat(value).toPrecision(3);
  4533. };
  4534. return find$4(intermediate, function (value, key) {
  4535. var newValue = position[key].map(round);
  4536. var val = value.map(round);
  4537. return !equals(newValue, val);
  4538. }).isSome();
  4539. };
  4540. var getTransitionDuration = function (element) {
  4541. var get = function (name) {
  4542. var style = get$a(element, name);
  4543. var times = isString(style) ? style.split(/\s*,\s*/) : [];
  4544. return filter$2(times, isNotEmpty);
  4545. };
  4546. var parse = function (value) {
  4547. if (isString(value) && /^[\d.]+/.test(value)) {
  4548. var num = parseFloat(value);
  4549. return endsWith(value, 'ms') ? num : num * 1000;
  4550. } else {
  4551. return 0;
  4552. }
  4553. };
  4554. var delay = get('transition-delay');
  4555. var duration = get('transition-duration');
  4556. return foldl(duration, function (acc, dur, i) {
  4557. var time = parse(delay[i]) + parse(dur);
  4558. return Math.max(acc, time);
  4559. }, 0);
  4560. };
  4561. var setupTransitionListeners = function (element, transition) {
  4562. var transitionEnd = unbindable();
  4563. var transitionCancel = unbindable();
  4564. var timer;
  4565. var isSourceTransition = function (e) {
  4566. var _a;
  4567. var pseudoElement = (_a = e.raw.pseudoElement) !== null && _a !== void 0 ? _a : '';
  4568. return eq(e.target, element) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName);
  4569. };
  4570. var transitionDone = function (e) {
  4571. if (isNullable(e) || isSourceTransition(e)) {
  4572. transitionEnd.clear();
  4573. transitionCancel.clear();
  4574. var type = e === null || e === void 0 ? void 0 : e.raw.type;
  4575. if (isNullable(type) || type === transitionend()) {
  4576. clearTimeout(timer);
  4577. remove$6(element, timerAttr);
  4578. remove$2(element, transition.classes);
  4579. }
  4580. }
  4581. };
  4582. var transitionStarted = function () {
  4583. transitionEnd.set(bind(element, transitionend(), transitionDone));
  4584. transitionCancel.set(bind(element, transitioncancel(), transitionDone));
  4585. };
  4586. if ('ontransitionstart' in element.dom) {
  4587. var transitionStart_1 = bind(element, transitionstart(), function (e) {
  4588. if (isSourceTransition(e)) {
  4589. transitionStart_1.unbind();
  4590. transitionStarted();
  4591. }
  4592. });
  4593. } else {
  4594. transitionStarted();
  4595. }
  4596. var duration = getTransitionDuration(element);
  4597. requestAnimationFrame(function () {
  4598. timer = setTimeout(transitionDone, duration + 17);
  4599. set$7(element, timerAttr, timer);
  4600. });
  4601. };
  4602. var startTransitioning = function (element, transition) {
  4603. add$1(element, transition.classes);
  4604. getOpt(element, timerAttr).each(function (timerId) {
  4605. clearTimeout(parseInt(timerId, 10));
  4606. remove$6(element, timerAttr);
  4607. });
  4608. setupTransitionListeners(element, transition);
  4609. };
  4610. var applyTransitionCss = function (element, origin, position, transition, decision, lastPlacement) {
  4611. var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
  4612. if (shouldTransition || isTransitioning$1(element, transition)) {
  4613. set$6(element, 'position', position.position);
  4614. var rect = toBox(origin, element);
  4615. var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect }));
  4616. var intermediateCssOptions = mapToObject(properties, function (prop) {
  4617. return intermediatePosition_1[prop];
  4618. });
  4619. if (hasChanges(position, intermediateCssOptions)) {
  4620. setOptions(element, intermediateCssOptions);
  4621. if (shouldTransition) {
  4622. startTransitioning(element, transition);
  4623. }
  4624. reflow(element);
  4625. }
  4626. } else {
  4627. remove$2(element, transition.classes);
  4628. }
  4629. };
  4630. var elementSize = function (p) {
  4631. return {
  4632. width: getOuter(p),
  4633. height: getOuter$1(p)
  4634. };
  4635. };
  4636. var layout = function (anchorBox, element, bubbles, options) {
  4637. remove$1(element, 'max-height');
  4638. remove$1(element, 'max-width');
  4639. var elementBox = elementSize(element);
  4640. return attempts(element, options.preference, anchorBox, elementBox, bubbles, options.bounds);
  4641. };
  4642. var setClasses = function (element, decision) {
  4643. var classInfo = decision.classes;
  4644. remove$2(element, classInfo.off);
  4645. add$1(element, classInfo.on);
  4646. };
  4647. var setHeight = function (element, decision, options) {
  4648. var maxHeightFunction = options.maxHeightFunction;
  4649. maxHeightFunction(element, decision.maxHeight);
  4650. };
  4651. var setWidth = function (element, decision, options) {
  4652. var maxWidthFunction = options.maxWidthFunction;
  4653. maxWidthFunction(element, decision.maxWidth);
  4654. };
  4655. var position$2 = function (element, decision, options) {
  4656. var positionCss = reposition(options.origin, decision);
  4657. options.transition.each(function (transition) {
  4658. applyTransitionCss(element, options.origin, positionCss, transition, decision, options.lastPlacement);
  4659. });
  4660. applyPositionCss(element, positionCss);
  4661. };
  4662. var setPlacement = function (element, decision) {
  4663. setPlacement$1(element, decision.placement);
  4664. };
  4665. var setMaxHeight = function (element, maxHeight) {
  4666. setMax$1(element, Math.floor(maxHeight));
  4667. };
  4668. var anchored = constant$1(function (element, available) {
  4669. setMaxHeight(element, available);
  4670. setAll(element, {
  4671. 'overflow-x': 'hidden',
  4672. 'overflow-y': 'auto'
  4673. });
  4674. });
  4675. var expandable$1 = constant$1(function (element, available) {
  4676. setMaxHeight(element, available);
  4677. });
  4678. var defaultOr = function (options, key, dephault) {
  4679. return options[key] === undefined ? dephault : options[key];
  4680. };
  4681. var simple = function (anchor, element, bubble, layouts, lastPlacement, getBounds, overrideOptions, transition) {
  4682. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4683. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4684. var anchorBox = anchor.anchorBox;
  4685. var origin = anchor.origin;
  4686. var options = {
  4687. bounds: viewport(origin, getBounds),
  4688. origin: origin,
  4689. preference: layouts,
  4690. maxHeightFunction: maxHeightFunction,
  4691. maxWidthFunction: maxWidthFunction,
  4692. lastPlacement: lastPlacement,
  4693. transition: transition
  4694. };
  4695. return go(anchorBox, element, bubble, options);
  4696. };
  4697. var go = function (anchorBox, element, bubble, options) {
  4698. var decision = layout(anchorBox, element, bubble, options);
  4699. position$2(element, decision, options);
  4700. setPlacement(element, decision);
  4701. setClasses(element, decision);
  4702. setHeight(element, decision, options);
  4703. setWidth(element, decision, options);
  4704. return {
  4705. layout: decision.layout,
  4706. placement: decision.placement
  4707. };
  4708. };
  4709. var allAlignments = [
  4710. 'valignCentre',
  4711. 'alignLeft',
  4712. 'alignRight',
  4713. 'alignCentre',
  4714. 'top',
  4715. 'bottom',
  4716. 'left',
  4717. 'right',
  4718. 'inset'
  4719. ];
  4720. var nu$5 = function (xOffset, yOffset, classes, insetModifier) {
  4721. if (insetModifier === void 0) {
  4722. insetModifier = 1;
  4723. }
  4724. var insetXOffset = xOffset * insetModifier;
  4725. var insetYOffset = yOffset * insetModifier;
  4726. var getClasses = function (prop) {
  4727. return get$e(classes, prop).getOr([]);
  4728. };
  4729. var make = function (xDelta, yDelta, alignmentsOn) {
  4730. var alignmentsOff = difference(allAlignments, alignmentsOn);
  4731. return {
  4732. offset: SugarPosition(xDelta, yDelta),
  4733. classesOn: bind$3(alignmentsOn, getClasses),
  4734. classesOff: bind$3(alignmentsOff, getClasses)
  4735. };
  4736. };
  4737. return {
  4738. southeast: function () {
  4739. return make(-xOffset, yOffset, [
  4740. 'top',
  4741. 'alignLeft'
  4742. ]);
  4743. },
  4744. southwest: function () {
  4745. return make(xOffset, yOffset, [
  4746. 'top',
  4747. 'alignRight'
  4748. ]);
  4749. },
  4750. south: function () {
  4751. return make(-xOffset / 2, yOffset, [
  4752. 'top',
  4753. 'alignCentre'
  4754. ]);
  4755. },
  4756. northeast: function () {
  4757. return make(-xOffset, -yOffset, [
  4758. 'bottom',
  4759. 'alignLeft'
  4760. ]);
  4761. },
  4762. northwest: function () {
  4763. return make(xOffset, -yOffset, [
  4764. 'bottom',
  4765. 'alignRight'
  4766. ]);
  4767. },
  4768. north: function () {
  4769. return make(-xOffset / 2, -yOffset, [
  4770. 'bottom',
  4771. 'alignCentre'
  4772. ]);
  4773. },
  4774. east: function () {
  4775. return make(xOffset, -yOffset / 2, [
  4776. 'valignCentre',
  4777. 'left'
  4778. ]);
  4779. },
  4780. west: function () {
  4781. return make(-xOffset, -yOffset / 2, [
  4782. 'valignCentre',
  4783. 'right'
  4784. ]);
  4785. },
  4786. insetNortheast: function () {
  4787. return make(insetXOffset, insetYOffset, [
  4788. 'top',
  4789. 'alignLeft',
  4790. 'inset'
  4791. ]);
  4792. },
  4793. insetNorthwest: function () {
  4794. return make(-insetXOffset, insetYOffset, [
  4795. 'top',
  4796. 'alignRight',
  4797. 'inset'
  4798. ]);
  4799. },
  4800. insetNorth: function () {
  4801. return make(-insetXOffset / 2, insetYOffset, [
  4802. 'top',
  4803. 'alignCentre',
  4804. 'inset'
  4805. ]);
  4806. },
  4807. insetSoutheast: function () {
  4808. return make(insetXOffset, -insetYOffset, [
  4809. 'bottom',
  4810. 'alignLeft',
  4811. 'inset'
  4812. ]);
  4813. },
  4814. insetSouthwest: function () {
  4815. return make(-insetXOffset, -insetYOffset, [
  4816. 'bottom',
  4817. 'alignRight',
  4818. 'inset'
  4819. ]);
  4820. },
  4821. insetSouth: function () {
  4822. return make(-insetXOffset / 2, -insetYOffset, [
  4823. 'bottom',
  4824. 'alignCentre',
  4825. 'inset'
  4826. ]);
  4827. },
  4828. insetEast: function () {
  4829. return make(-insetXOffset, -insetYOffset / 2, [
  4830. 'valignCentre',
  4831. 'right',
  4832. 'inset'
  4833. ]);
  4834. },
  4835. insetWest: function () {
  4836. return make(insetXOffset, -insetYOffset / 2, [
  4837. 'valignCentre',
  4838. 'left',
  4839. 'inset'
  4840. ]);
  4841. }
  4842. };
  4843. };
  4844. var fallback = function () {
  4845. return nu$5(0, 0, {});
  4846. };
  4847. var nu$4 = identity$1;
  4848. var onDirection = function (isLtr, isRtl) {
  4849. return function (element) {
  4850. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4851. };
  4852. };
  4853. var getDirection = function (element) {
  4854. return get$a(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4855. };
  4856. var AttributeValue;
  4857. (function (AttributeValue) {
  4858. AttributeValue['TopToBottom'] = 'toptobottom';
  4859. AttributeValue['BottomToTop'] = 'bottomtotop';
  4860. }(AttributeValue || (AttributeValue = {})));
  4861. var Attribute = 'data-alloy-vertical-dir';
  4862. var isBottomToTopDir = function (el) {
  4863. return closest$2(el, function (current) {
  4864. return isElement$2(current) && get$c(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop;
  4865. });
  4866. };
  4867. var schema$y = function () {
  4868. return optionObjOf('layouts', [
  4869. required$1('onLtr'),
  4870. required$1('onRtl'),
  4871. option('onBottomLtr'),
  4872. option('onBottomRtl')
  4873. ]);
  4874. };
  4875. var get$4 = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  4876. var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4877. var customLtr = info.layouts.map(function (ls) {
  4878. return ls.onLtr(elem);
  4879. });
  4880. var customRtl = info.layouts.map(function (ls) {
  4881. return ls.onRtl(elem);
  4882. });
  4883. var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  4884. return ls.onBottomLtr.map(function (f) {
  4885. return f(elem);
  4886. });
  4887. }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4888. var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  4889. return ls.onBottomRtl.map(function (f) {
  4890. return f(elem);
  4891. });
  4892. }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4893. var f = onDirection(ltr, rtl);
  4894. return f(elem);
  4895. };
  4896. var placement$4 = function (component, anchorInfo, origin) {
  4897. var hotspot = anchorInfo.hotspot;
  4898. var anchorBox = toBox(origin, hotspot.element);
  4899. var layouts = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
  4900. return Optional.some(nu$4({
  4901. anchorBox: anchorBox,
  4902. bubble: anchorInfo.bubble.getOr(fallback()),
  4903. overrides: anchorInfo.overrides,
  4904. layouts: layouts,
  4905. placer: Optional.none()
  4906. }));
  4907. };
  4908. var HotspotAnchor = [
  4909. required$1('hotspot'),
  4910. option('bubble'),
  4911. defaulted('overrides', {}),
  4912. schema$y(),
  4913. output$1('placement', placement$4)
  4914. ];
  4915. var placement$3 = function (component, anchorInfo, origin) {
  4916. var pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
  4917. var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
  4918. var layouts = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
  4919. return Optional.some(nu$4({
  4920. anchorBox: anchorBox,
  4921. bubble: anchorInfo.bubble,
  4922. overrides: anchorInfo.overrides,
  4923. layouts: layouts,
  4924. placer: Optional.none()
  4925. }));
  4926. };
  4927. var MakeshiftAnchor = [
  4928. required$1('x'),
  4929. required$1('y'),
  4930. defaulted('height', 0),
  4931. defaulted('width', 0),
  4932. defaulted('bubble', fallback()),
  4933. defaulted('overrides', {}),
  4934. schema$y(),
  4935. output$1('placement', placement$3)
  4936. ];
  4937. var adt$7 = Adt.generate([
  4938. { screen: ['point'] },
  4939. {
  4940. absolute: [
  4941. 'point',
  4942. 'scrollLeft',
  4943. 'scrollTop'
  4944. ]
  4945. }
  4946. ]);
  4947. var toFixed = function (pos) {
  4948. return pos.fold(identity$1, function (point, scrollLeft, scrollTop) {
  4949. return point.translate(-scrollLeft, -scrollTop);
  4950. });
  4951. };
  4952. var toAbsolute = function (pos) {
  4953. return pos.fold(identity$1, identity$1);
  4954. };
  4955. var sum = function (points) {
  4956. return foldl(points, function (b, a) {
  4957. return b.translate(a.left, a.top);
  4958. }, SugarPosition(0, 0));
  4959. };
  4960. var sumAsFixed = function (positions) {
  4961. var points = map$2(positions, toFixed);
  4962. return sum(points);
  4963. };
  4964. var sumAsAbsolute = function (positions) {
  4965. var points = map$2(positions, toAbsolute);
  4966. return sum(points);
  4967. };
  4968. var screen = adt$7.screen;
  4969. var absolute$1 = adt$7.absolute;
  4970. var getOffset = function (component, origin, anchorInfo) {
  4971. var win = defaultView(anchorInfo.root).dom;
  4972. var hasSameOwner = function (frame) {
  4973. var frameOwner = owner$4(frame);
  4974. var compOwner = owner$4(component.element);
  4975. return eq(frameOwner, compOwner);
  4976. };
  4977. return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
  4978. };
  4979. var getRootPoint = function (component, origin, anchorInfo) {
  4980. var doc = owner$4(component.element);
  4981. var outerScroll = get$6(doc);
  4982. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4983. return absolute$1(offset, outerScroll.left, outerScroll.top);
  4984. };
  4985. var getBox = function (left, top, width, height) {
  4986. var point = screen(SugarPosition(left, top));
  4987. return Optional.some(pointed(point, width, height));
  4988. };
  4989. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  4990. return optBox.map(function (box) {
  4991. var points = [
  4992. rootPoint,
  4993. box.point
  4994. ];
  4995. var topLeft = cata$1(origin, function () {
  4996. return sumAsAbsolute(points);
  4997. }, function () {
  4998. return sumAsAbsolute(points);
  4999. }, function () {
  5000. return sumAsFixed(points);
  5001. });
  5002. var anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height);
  5003. var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  5004. var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
  5005. var layouts = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
  5006. return nu$4({
  5007. anchorBox: anchorBox,
  5008. bubble: anchorInfo.bubble.getOr(fallback()),
  5009. overrides: anchorInfo.overrides,
  5010. layouts: layouts,
  5011. placer: Optional.none()
  5012. });
  5013. });
  5014. };
  5015. var placement$2 = function (component, anchorInfo, origin) {
  5016. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5017. return anchorInfo.node.filter(inBody).bind(function (target) {
  5018. var rect = target.dom.getBoundingClientRect();
  5019. var nodeBox = getBox(rect.left, rect.top, rect.width, rect.height);
  5020. var elem = anchorInfo.node.getOr(component.element);
  5021. return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5022. });
  5023. };
  5024. var NodeAnchor = [
  5025. required$1('node'),
  5026. required$1('root'),
  5027. option('bubble'),
  5028. schema$y(),
  5029. defaulted('overrides', {}),
  5030. defaulted('showAbove', false),
  5031. output$1('placement', placement$2)
  5032. ];
  5033. var zeroWidth = '\uFEFF';
  5034. var nbsp = '\xA0';
  5035. var create$6 = function (start, soffset, finish, foffset) {
  5036. return {
  5037. start: start,
  5038. soffset: soffset,
  5039. finish: finish,
  5040. foffset: foffset
  5041. };
  5042. };
  5043. var SimRange = { create: create$6 };
  5044. var adt$6 = Adt.generate([
  5045. { before: ['element'] },
  5046. {
  5047. on: [
  5048. 'element',
  5049. 'offset'
  5050. ]
  5051. },
  5052. { after: ['element'] }
  5053. ]);
  5054. var cata = function (subject, onBefore, onOn, onAfter) {
  5055. return subject.fold(onBefore, onOn, onAfter);
  5056. };
  5057. var getStart$1 = function (situ) {
  5058. return situ.fold(identity$1, identity$1, identity$1);
  5059. };
  5060. var before = adt$6.before;
  5061. var on$1 = adt$6.on;
  5062. var after$1 = adt$6.after;
  5063. var Situ = {
  5064. before: before,
  5065. on: on$1,
  5066. after: after$1,
  5067. cata: cata,
  5068. getStart: getStart$1
  5069. };
  5070. var adt$5 = Adt.generate([
  5071. { domRange: ['rng'] },
  5072. {
  5073. relative: [
  5074. 'startSitu',
  5075. 'finishSitu'
  5076. ]
  5077. },
  5078. {
  5079. exact: [
  5080. 'start',
  5081. 'soffset',
  5082. 'finish',
  5083. 'foffset'
  5084. ]
  5085. }
  5086. ]);
  5087. var exactFromRange = function (simRange) {
  5088. return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  5089. };
  5090. var getStart = function (selection) {
  5091. return selection.match({
  5092. domRange: function (rng) {
  5093. return SugarElement.fromDom(rng.startContainer);
  5094. },
  5095. relative: function (startSitu, _finishSitu) {
  5096. return Situ.getStart(startSitu);
  5097. },
  5098. exact: function (start, _soffset, _finish, _foffset) {
  5099. return start;
  5100. }
  5101. });
  5102. };
  5103. var domRange = adt$5.domRange;
  5104. var relative = adt$5.relative;
  5105. var exact = adt$5.exact;
  5106. var getWin = function (selection) {
  5107. var start = getStart(selection);
  5108. return defaultView(start);
  5109. };
  5110. var range$1 = SimRange.create;
  5111. var SimSelection = {
  5112. domRange: domRange,
  5113. relative: relative,
  5114. exact: exact,
  5115. exactFromRange: exactFromRange,
  5116. getWin: getWin,
  5117. range: range$1
  5118. };
  5119. var setStart = function (rng, situ) {
  5120. situ.fold(function (e) {
  5121. rng.setStartBefore(e.dom);
  5122. }, function (e, o) {
  5123. rng.setStart(e.dom, o);
  5124. }, function (e) {
  5125. rng.setStartAfter(e.dom);
  5126. });
  5127. };
  5128. var setFinish = function (rng, situ) {
  5129. situ.fold(function (e) {
  5130. rng.setEndBefore(e.dom);
  5131. }, function (e, o) {
  5132. rng.setEnd(e.dom, o);
  5133. }, function (e) {
  5134. rng.setEndAfter(e.dom);
  5135. });
  5136. };
  5137. var relativeToNative = function (win, startSitu, finishSitu) {
  5138. var range = win.document.createRange();
  5139. setStart(range, startSitu);
  5140. setFinish(range, finishSitu);
  5141. return range;
  5142. };
  5143. var exactToNative = function (win, start, soffset, finish, foffset) {
  5144. var rng = win.document.createRange();
  5145. rng.setStart(start.dom, soffset);
  5146. rng.setEnd(finish.dom, foffset);
  5147. return rng;
  5148. };
  5149. var toRect = function (rect) {
  5150. return {
  5151. left: rect.left,
  5152. top: rect.top,
  5153. right: rect.right,
  5154. bottom: rect.bottom,
  5155. width: rect.width,
  5156. height: rect.height
  5157. };
  5158. };
  5159. var getFirstRect$1 = function (rng) {
  5160. var rects = rng.getClientRects();
  5161. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  5162. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5163. };
  5164. var getBounds$2 = function (rng) {
  5165. var rect = rng.getBoundingClientRect();
  5166. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5167. };
  5168. var adt$4 = Adt.generate([
  5169. {
  5170. ltr: [
  5171. 'start',
  5172. 'soffset',
  5173. 'finish',
  5174. 'foffset'
  5175. ]
  5176. },
  5177. {
  5178. rtl: [
  5179. 'start',
  5180. 'soffset',
  5181. 'finish',
  5182. 'foffset'
  5183. ]
  5184. }
  5185. ]);
  5186. var fromRange = function (win, type, range) {
  5187. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  5188. };
  5189. var getRanges = function (win, selection) {
  5190. return selection.match({
  5191. domRange: function (rng) {
  5192. return {
  5193. ltr: constant$1(rng),
  5194. rtl: Optional.none
  5195. };
  5196. },
  5197. relative: function (startSitu, finishSitu) {
  5198. return {
  5199. ltr: cached(function () {
  5200. return relativeToNative(win, startSitu, finishSitu);
  5201. }),
  5202. rtl: cached(function () {
  5203. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  5204. })
  5205. };
  5206. },
  5207. exact: function (start, soffset, finish, foffset) {
  5208. return {
  5209. ltr: cached(function () {
  5210. return exactToNative(win, start, soffset, finish, foffset);
  5211. }),
  5212. rtl: cached(function () {
  5213. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  5214. })
  5215. };
  5216. }
  5217. });
  5218. };
  5219. var doDiagnose = function (win, ranges) {
  5220. var rng = ranges.ltr();
  5221. if (rng.collapsed) {
  5222. var reversed = ranges.rtl().filter(function (rev) {
  5223. return rev.collapsed === false;
  5224. });
  5225. return reversed.map(function (rev) {
  5226. return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  5227. }).getOrThunk(function () {
  5228. return fromRange(win, adt$4.ltr, rng);
  5229. });
  5230. } else {
  5231. return fromRange(win, adt$4.ltr, rng);
  5232. }
  5233. };
  5234. var diagnose = function (win, selection) {
  5235. var ranges = getRanges(win, selection);
  5236. return doDiagnose(win, ranges);
  5237. };
  5238. var asLtrRange = function (win, selection) {
  5239. var diagnosis = diagnose(win, selection);
  5240. return diagnosis.match({
  5241. ltr: function (start, soffset, finish, foffset) {
  5242. var rng = win.document.createRange();
  5243. rng.setStart(start.dom, soffset);
  5244. rng.setEnd(finish.dom, foffset);
  5245. return rng;
  5246. },
  5247. rtl: function (start, soffset, finish, foffset) {
  5248. var rng = win.document.createRange();
  5249. rng.setStart(finish.dom, foffset);
  5250. rng.setEnd(start.dom, soffset);
  5251. return rng;
  5252. }
  5253. });
  5254. };
  5255. adt$4.ltr;
  5256. adt$4.rtl;
  5257. var NodeValue = function (is, name) {
  5258. var get = function (element) {
  5259. if (!is(element)) {
  5260. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  5261. }
  5262. return getOption(element).getOr('');
  5263. };
  5264. var getOption = function (element) {
  5265. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  5266. };
  5267. var set = function (element, value) {
  5268. if (!is(element)) {
  5269. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  5270. }
  5271. element.dom.nodeValue = value;
  5272. };
  5273. return {
  5274. get: get,
  5275. getOption: getOption,
  5276. set: set
  5277. };
  5278. };
  5279. var api = NodeValue(isText$1, 'text');
  5280. var get$3 = function (element) {
  5281. return api.get(element);
  5282. };
  5283. var getOption = function (element) {
  5284. return api.getOption(element);
  5285. };
  5286. var getEnd = function (element) {
  5287. return name$2(element) === 'img' ? 1 : getOption(element).fold(function () {
  5288. return children(element).length;
  5289. }, function (v) {
  5290. return v.length;
  5291. });
  5292. };
  5293. var isTextNodeWithCursorPosition = function (el) {
  5294. return getOption(el).filter(function (text) {
  5295. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  5296. }).isSome();
  5297. };
  5298. var elementsWithCursorPosition = [
  5299. 'img',
  5300. 'br'
  5301. ];
  5302. var isCursorPosition = function (elem) {
  5303. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  5304. return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem));
  5305. };
  5306. var last$1 = function (element) {
  5307. return descendantRtl(element, isCursorPosition);
  5308. };
  5309. var descendantRtl = function (scope, predicate) {
  5310. var descend = function (element) {
  5311. var children$1 = children(element);
  5312. for (var i = children$1.length - 1; i >= 0; i--) {
  5313. var child = children$1[i];
  5314. if (predicate(child)) {
  5315. return Optional.some(child);
  5316. }
  5317. var res = descend(child);
  5318. if (res.isSome()) {
  5319. return res;
  5320. }
  5321. }
  5322. return Optional.none();
  5323. };
  5324. return descend(scope);
  5325. };
  5326. var descendants = function (scope, selector) {
  5327. return all$3(selector, scope);
  5328. };
  5329. var makeRange = function (start, soffset, finish, foffset) {
  5330. var doc = owner$4(start);
  5331. var rng = doc.dom.createRange();
  5332. rng.setStart(start.dom, soffset);
  5333. rng.setEnd(finish.dom, foffset);
  5334. return rng;
  5335. };
  5336. var after = function (start, soffset, finish, foffset) {
  5337. var r = makeRange(start, soffset, finish, foffset);
  5338. var same = eq(start, finish) && soffset === foffset;
  5339. return r.collapsed && !same;
  5340. };
  5341. var getNativeSelection = function (win) {
  5342. return Optional.from(win.getSelection());
  5343. };
  5344. var readRange = function (selection) {
  5345. if (selection.rangeCount > 0) {
  5346. var firstRng = selection.getRangeAt(0);
  5347. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  5348. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  5349. } else {
  5350. return Optional.none();
  5351. }
  5352. };
  5353. var doGetExact = function (selection) {
  5354. if (selection.anchorNode === null || selection.focusNode === null) {
  5355. return readRange(selection);
  5356. } else {
  5357. var anchor = SugarElement.fromDom(selection.anchorNode);
  5358. var focus_1 = SugarElement.fromDom(selection.focusNode);
  5359. return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  5360. }
  5361. };
  5362. var getExact = function (win) {
  5363. return getNativeSelection(win).filter(function (sel) {
  5364. return sel.rangeCount > 0;
  5365. }).bind(doGetExact);
  5366. };
  5367. var getFirstRect = function (win, selection) {
  5368. var rng = asLtrRange(win, selection);
  5369. return getFirstRect$1(rng);
  5370. };
  5371. var getBounds$1 = function (win, selection) {
  5372. var rng = asLtrRange(win, selection);
  5373. return getBounds$2(rng);
  5374. };
  5375. var point$1 = function (element, offset) {
  5376. return {
  5377. element: element,
  5378. offset: offset
  5379. };
  5380. };
  5381. var descendOnce$1 = function (element, offset) {
  5382. var children$1 = children(element);
  5383. if (children$1.length === 0) {
  5384. return point$1(element, offset);
  5385. } else if (offset < children$1.length) {
  5386. return point$1(children$1[offset], 0);
  5387. } else {
  5388. var last = children$1[children$1.length - 1];
  5389. var len = isText$1(last) ? get$3(last).length : children(last).length;
  5390. return point$1(last, len);
  5391. }
  5392. };
  5393. var descendOnce = function (element, offset) {
  5394. return isText$1(element) ? point$1(element, offset) : descendOnce$1(element, offset);
  5395. };
  5396. var getAnchorSelection = function (win, anchorInfo) {
  5397. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  5398. return function () {
  5399. return getExact(win);
  5400. };
  5401. });
  5402. return getSelection().map(function (sel) {
  5403. var modStart = descendOnce(sel.start, sel.soffset);
  5404. var modFinish = descendOnce(sel.finish, sel.foffset);
  5405. return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  5406. });
  5407. };
  5408. var placement$1 = function (component, anchorInfo, origin) {
  5409. var win = defaultView(anchorInfo.root).dom;
  5410. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5411. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5412. var optRect = getBounds$1(win, SimSelection.exactFromRange(sel)).orThunk(function () {
  5413. var x = SugarElement.fromText(zeroWidth);
  5414. before$2(sel.start, x);
  5415. var rect = getFirstRect(win, SimSelection.exact(x, 0, x, 1));
  5416. remove$7(x);
  5417. return rect;
  5418. });
  5419. return optRect.bind(function (rawRect) {
  5420. return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
  5421. });
  5422. });
  5423. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5424. return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
  5425. });
  5426. var elem = targetElement.getOr(component.element);
  5427. return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  5428. };
  5429. var SelectionAnchor = [
  5430. option('getSelection'),
  5431. required$1('root'),
  5432. option('bubble'),
  5433. schema$y(),
  5434. defaulted('overrides', {}),
  5435. defaulted('showAbove', false),
  5436. output$1('placement', placement$1)
  5437. ];
  5438. var labelPrefix$1 = 'link-layout';
  5439. var eastX = function (anchor) {
  5440. return anchor.x + anchor.width;
  5441. };
  5442. var westX = function (anchor, element) {
  5443. return anchor.x - element.width;
  5444. };
  5445. var northY$1 = function (anchor, element) {
  5446. return anchor.y - element.height + anchor.height;
  5447. };
  5448. var southY$1 = function (anchor) {
  5449. return anchor.y;
  5450. };
  5451. var southeast$1 = function (anchor, element, bubbles) {
  5452. return nu$6(eastX(anchor), southY$1(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  5453. left: 0,
  5454. top: 2
  5455. }), labelPrefix$1);
  5456. };
  5457. var southwest$1 = function (anchor, element, bubbles) {
  5458. return nu$6(westX(anchor, element), southY$1(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  5459. right: 1,
  5460. top: 2
  5461. }), labelPrefix$1);
  5462. };
  5463. var northeast$1 = function (anchor, element, bubbles) {
  5464. return nu$6(eastX(anchor), northY$1(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  5465. left: 0,
  5466. bottom: 3
  5467. }), labelPrefix$1);
  5468. };
  5469. var northwest$1 = function (anchor, element, bubbles) {
  5470. return nu$6(westX(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  5471. right: 1,
  5472. bottom: 3
  5473. }), labelPrefix$1);
  5474. };
  5475. var all = function () {
  5476. return [
  5477. southeast$1,
  5478. southwest$1,
  5479. northeast$1,
  5480. northwest$1
  5481. ];
  5482. };
  5483. var allRtl = function () {
  5484. return [
  5485. southwest$1,
  5486. southeast$1,
  5487. northwest$1,
  5488. northeast$1
  5489. ];
  5490. };
  5491. var placement = function (component, submenuInfo, origin) {
  5492. var anchorBox = toBox(origin, submenuInfo.item.element);
  5493. var layouts = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
  5494. return Optional.some(nu$4({
  5495. anchorBox: anchorBox,
  5496. bubble: fallback(),
  5497. overrides: submenuInfo.overrides,
  5498. layouts: layouts,
  5499. placer: Optional.none()
  5500. }));
  5501. };
  5502. var SubmenuAnchor = [
  5503. required$1('item'),
  5504. schema$y(),
  5505. defaulted('overrides', {}),
  5506. output$1('placement', placement)
  5507. ];
  5508. var AnchorSchema = choose$1('type', {
  5509. selection: SelectionAnchor,
  5510. node: NodeAnchor,
  5511. hotspot: HotspotAnchor,
  5512. submenu: SubmenuAnchor,
  5513. makeshift: MakeshiftAnchor
  5514. });
  5515. var TransitionSchema = [
  5516. requiredArrayOf('classes', string),
  5517. defaultedStringEnum('mode', 'all', [
  5518. 'all',
  5519. 'layout',
  5520. 'placement'
  5521. ])
  5522. ];
  5523. var PositionSchema = [
  5524. defaulted('useFixed', never),
  5525. option('getBounds')
  5526. ];
  5527. var PlacementSchema = [
  5528. requiredOf('anchor', AnchorSchema),
  5529. optionObjOf('transition', TransitionSchema)
  5530. ];
  5531. var getFixedOrigin = function () {
  5532. var html = document.documentElement;
  5533. return fixed$1(0, 0, html.clientWidth, html.clientHeight);
  5534. };
  5535. var getRelativeOrigin = function (component) {
  5536. var position = absolute$3(component.element);
  5537. var bounds = component.element.dom.getBoundingClientRect();
  5538. return relative$1(position.left, position.top, bounds.width, bounds.height);
  5539. };
  5540. var place = function (component, origin, anchoring, getBounds, placee, lastPlace, transition) {
  5541. var anchor = box(anchoring.anchorBox, origin);
  5542. return simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds, anchoring.overrides, transition);
  5543. };
  5544. var position$1 = function (component, posConfig, posState, placee, placementSpec) {
  5545. positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
  5546. };
  5547. var positionWithin = function (component, posConfig, posState, placee, placementSpec, boxElement) {
  5548. var boundsBox = boxElement.map(box$1);
  5549. return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
  5550. };
  5551. var positionWithinBounds = function (component, posConfig, posState, placee, placementSpec, bounds) {
  5552. var placeeDetail = asRawOrDie$1('placement.info', objOf(PlacementSchema), placementSpec);
  5553. var anchorage = placeeDetail.anchor;
  5554. var element = placee.element;
  5555. var placeeState = posState.get(placee.uid);
  5556. preserve$1(function () {
  5557. set$6(element, 'position', 'fixed');
  5558. var oldVisibility = getRaw(element, 'visibility');
  5559. set$6(element, 'visibility', 'hidden');
  5560. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5561. var placer = anchorage.placement;
  5562. var getBounds = bounds.map(constant$1).or(posConfig.getBounds);
  5563. placer(component, anchorage, origin).each(function (anchoring) {
  5564. var doPlace = anchoring.placer.getOr(place);
  5565. var newState = doPlace(component, origin, anchoring, getBounds, placee, placeeState, placeeDetail.transition);
  5566. posState.set(placee.uid, newState);
  5567. });
  5568. oldVisibility.fold(function () {
  5569. remove$1(element, 'visibility');
  5570. }, function (vis) {
  5571. set$6(element, 'visibility', vis);
  5572. });
  5573. if (getRaw(element, 'left').isNone() && getRaw(element, 'top').isNone() && getRaw(element, 'right').isNone() && getRaw(element, 'bottom').isNone() && is(getRaw(element, 'position'), 'fixed')) {
  5574. remove$1(element, 'position');
  5575. }
  5576. }, element);
  5577. };
  5578. var getMode = function (component, pConfig, _pState) {
  5579. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5580. };
  5581. var reset$1 = function (component, pConfig, posState, placee) {
  5582. var element = placee.element;
  5583. each$1([
  5584. 'position',
  5585. 'left',
  5586. 'right',
  5587. 'top',
  5588. 'bottom'
  5589. ], function (prop) {
  5590. return remove$1(element, prop);
  5591. });
  5592. reset$2(element);
  5593. posState.clear(placee.uid);
  5594. };
  5595. var PositionApis = /*#__PURE__*/Object.freeze({
  5596. __proto__: null,
  5597. position: position$1,
  5598. positionWithin: positionWithin,
  5599. positionWithinBounds: positionWithinBounds,
  5600. getMode: getMode,
  5601. reset: reset$1
  5602. });
  5603. var init$g = function () {
  5604. var state = {};
  5605. var set = function (id, data) {
  5606. state[id] = data;
  5607. };
  5608. var get = function (id) {
  5609. return get$e(state, id);
  5610. };
  5611. var clear = function (id) {
  5612. if (isNonNullable(id)) {
  5613. delete state[id];
  5614. } else {
  5615. state = {};
  5616. }
  5617. };
  5618. return nu$8({
  5619. readState: function () {
  5620. return state;
  5621. },
  5622. clear: clear,
  5623. set: set,
  5624. get: get
  5625. });
  5626. };
  5627. var PositioningState = /*#__PURE__*/Object.freeze({
  5628. __proto__: null,
  5629. init: init$g
  5630. });
  5631. var Positioning = create$7({
  5632. fields: PositionSchema,
  5633. name: 'positioning',
  5634. active: ActivePosition,
  5635. apis: PositionApis,
  5636. state: PositioningState
  5637. });
  5638. var fireDetaching = function (component) {
  5639. emit(component, detachedFromDom());
  5640. var children = component.components();
  5641. each$1(children, fireDetaching);
  5642. };
  5643. var fireAttaching = function (component) {
  5644. var children = component.components();
  5645. each$1(children, fireAttaching);
  5646. emit(component, attachedToDom());
  5647. };
  5648. var attach$1 = function (parent, child) {
  5649. append$2(parent.element, child.element);
  5650. };
  5651. var detachChildren$1 = function (component) {
  5652. each$1(component.components(), function (childComp) {
  5653. return remove$7(childComp.element);
  5654. });
  5655. empty(component.element);
  5656. component.syncComponents();
  5657. };
  5658. var replaceChildren = function (component, newChildren) {
  5659. var subs = component.components();
  5660. detachChildren$1(component);
  5661. var deleted = difference(subs, newChildren);
  5662. each$1(deleted, function (comp) {
  5663. fireDetaching(comp);
  5664. component.getSystem().removeFromWorld(comp);
  5665. });
  5666. each$1(newChildren, function (childComp) {
  5667. if (!childComp.getSystem().isConnected()) {
  5668. component.getSystem().addToWorld(childComp);
  5669. attach$1(component, childComp);
  5670. if (inBody(component.element)) {
  5671. fireAttaching(childComp);
  5672. }
  5673. } else {
  5674. attach$1(component, childComp);
  5675. }
  5676. component.syncComponents();
  5677. });
  5678. };
  5679. var attach = function (parent, child) {
  5680. attachWith(parent, child, append$2);
  5681. };
  5682. var attachWith = function (parent, child, insertion) {
  5683. parent.getSystem().addToWorld(child);
  5684. insertion(parent.element, child.element);
  5685. if (inBody(parent.element)) {
  5686. fireAttaching(child);
  5687. }
  5688. parent.syncComponents();
  5689. };
  5690. var doDetach = function (component) {
  5691. fireDetaching(component);
  5692. remove$7(component.element);
  5693. component.getSystem().removeFromWorld(component);
  5694. };
  5695. var detach = function (component) {
  5696. var parent$1 = parent(component.element).bind(function (p) {
  5697. return component.getSystem().getByDom(p).toOptional();
  5698. });
  5699. doDetach(component);
  5700. parent$1.each(function (p) {
  5701. p.syncComponents();
  5702. });
  5703. };
  5704. var detachChildren = function (component) {
  5705. var subs = component.components();
  5706. each$1(subs, doDetach);
  5707. empty(component.element);
  5708. component.syncComponents();
  5709. };
  5710. var attachSystem = function (element, guiSystem) {
  5711. attachSystemWith(element, guiSystem, append$2);
  5712. };
  5713. var attachSystemAfter = function (element, guiSystem) {
  5714. attachSystemWith(element, guiSystem, after$2);
  5715. };
  5716. var attachSystemWith = function (element, guiSystem, inserter) {
  5717. inserter(element, guiSystem.element);
  5718. var children$1 = children(guiSystem.element);
  5719. each$1(children$1, function (child) {
  5720. guiSystem.getByDom(child).each(fireAttaching);
  5721. });
  5722. };
  5723. var detachSystem = function (guiSystem) {
  5724. var children$1 = children(guiSystem.element);
  5725. each$1(children$1, function (child) {
  5726. guiSystem.getByDom(child).each(fireDetaching);
  5727. });
  5728. remove$7(guiSystem.element);
  5729. };
  5730. var rebuild = function (sandbox, sConfig, sState, data) {
  5731. sState.get().each(function (_data) {
  5732. detachChildren(sandbox);
  5733. });
  5734. var point = sConfig.getAttachPoint(sandbox);
  5735. attach(point, sandbox);
  5736. var built = sandbox.getSystem().build(data);
  5737. attach(sandbox, built);
  5738. sState.set(built);
  5739. return built;
  5740. };
  5741. var open$1 = function (sandbox, sConfig, sState, data) {
  5742. var newState = rebuild(sandbox, sConfig, sState, data);
  5743. sConfig.onOpen(sandbox, newState);
  5744. return newState;
  5745. };
  5746. var setContent = function (sandbox, sConfig, sState, data) {
  5747. return sState.get().map(function () {
  5748. return rebuild(sandbox, sConfig, sState, data);
  5749. });
  5750. };
  5751. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5752. cloak(sandbox, sConfig);
  5753. open$1(sandbox, sConfig, sState, data);
  5754. transaction();
  5755. decloak(sandbox, sConfig);
  5756. };
  5757. var close$1 = function (sandbox, sConfig, sState) {
  5758. sState.get().each(function (data) {
  5759. detachChildren(sandbox);
  5760. detach(sandbox);
  5761. sConfig.onClose(sandbox, data);
  5762. sState.clear();
  5763. });
  5764. };
  5765. var isOpen$1 = function (_sandbox, _sConfig, sState) {
  5766. return sState.isOpen();
  5767. };
  5768. var isPartOf = function (sandbox, sConfig, sState, queryElem) {
  5769. return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5770. return sConfig.isPartOf(sandbox, data, queryElem);
  5771. });
  5772. };
  5773. var getState$2 = function (_sandbox, _sConfig, sState) {
  5774. return sState.get();
  5775. };
  5776. var store = function (sandbox, cssKey, attr, newValue) {
  5777. getRaw(sandbox.element, cssKey).fold(function () {
  5778. remove$6(sandbox.element, attr);
  5779. }, function (v) {
  5780. set$7(sandbox.element, attr, v);
  5781. });
  5782. set$6(sandbox.element, cssKey, newValue);
  5783. };
  5784. var restore = function (sandbox, cssKey, attr) {
  5785. getOpt(sandbox.element, attr).fold(function () {
  5786. return remove$1(sandbox.element, cssKey);
  5787. }, function (oldValue) {
  5788. return set$6(sandbox.element, cssKey, oldValue);
  5789. });
  5790. };
  5791. var cloak = function (sandbox, sConfig, _sState) {
  5792. var sink = sConfig.getAttachPoint(sandbox);
  5793. set$6(sandbox.element, 'position', Positioning.getMode(sink));
  5794. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5795. };
  5796. var hasPosition = function (element) {
  5797. return exists([
  5798. 'top',
  5799. 'left',
  5800. 'right',
  5801. 'bottom'
  5802. ], function (pos) {
  5803. return getRaw(element, pos).isSome();
  5804. });
  5805. };
  5806. var decloak = function (sandbox, sConfig, _sState) {
  5807. if (!hasPosition(sandbox.element)) {
  5808. remove$1(sandbox.element, 'position');
  5809. }
  5810. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5811. };
  5812. var SandboxApis = /*#__PURE__*/Object.freeze({
  5813. __proto__: null,
  5814. cloak: cloak,
  5815. decloak: decloak,
  5816. open: open$1,
  5817. openWhileCloaked: openWhileCloaked,
  5818. close: close$1,
  5819. isOpen: isOpen$1,
  5820. isPartOf: isPartOf,
  5821. getState: getState$2,
  5822. setContent: setContent
  5823. });
  5824. var events$g = function (sandboxConfig, sandboxState) {
  5825. return derive$2([run$1(sandboxClose(), function (sandbox, _simulatedEvent) {
  5826. close$1(sandbox, sandboxConfig, sandboxState);
  5827. })]);
  5828. };
  5829. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5830. __proto__: null,
  5831. events: events$g
  5832. });
  5833. var SandboxSchema = [
  5834. onHandler('onOpen'),
  5835. onHandler('onClose'),
  5836. required$1('isPartOf'),
  5837. required$1('getAttachPoint'),
  5838. defaulted('cloakVisibilityAttr', 'data-precloak-visibility')
  5839. ];
  5840. var init$f = function () {
  5841. var contents = value$1();
  5842. var readState = constant$1('not-implemented');
  5843. return nu$8({
  5844. readState: readState,
  5845. isOpen: contents.isSet,
  5846. clear: contents.clear,
  5847. set: contents.set,
  5848. get: contents.get
  5849. });
  5850. };
  5851. var SandboxState = /*#__PURE__*/Object.freeze({
  5852. __proto__: null,
  5853. init: init$f
  5854. });
  5855. var Sandboxing = create$7({
  5856. fields: SandboxSchema,
  5857. name: 'sandboxing',
  5858. active: ActiveSandbox,
  5859. apis: SandboxApis,
  5860. state: SandboxState
  5861. });
  5862. var dismissPopups = constant$1('dismiss.popups');
  5863. var repositionPopups = constant$1('reposition.popups');
  5864. var mouseReleased = constant$1('mouse.released');
  5865. var schema$x = objOfOnly([
  5866. defaulted('isExtraPart', never),
  5867. optionObjOf('fireEventInstead', [defaulted('event', dismissRequested())])
  5868. ]);
  5869. var receivingChannel$1 = function (rawSpec) {
  5870. var _a;
  5871. var detail = asRawOrDie$1('Dismissal', schema$x, rawSpec);
  5872. return _a = {}, _a[dismissPopups()] = {
  5873. schema: objOfOnly([required$1('target')]),
  5874. onReceive: function (sandbox, data) {
  5875. if (Sandboxing.isOpen(sandbox)) {
  5876. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5877. if (!isPart) {
  5878. detail.fireEventInstead.fold(function () {
  5879. return Sandboxing.close(sandbox);
  5880. }, function (fe) {
  5881. return emit(sandbox, fe.event);
  5882. });
  5883. }
  5884. }
  5885. }
  5886. }, _a;
  5887. };
  5888. var schema$w = objOfOnly([
  5889. optionObjOf('fireEventInstead', [defaulted('event', repositionRequested())]),
  5890. requiredFunction('doReposition')
  5891. ]);
  5892. var receivingChannel = function (rawSpec) {
  5893. var _a;
  5894. var detail = asRawOrDie$1('Reposition', schema$w, rawSpec);
  5895. return _a = {}, _a[repositionPopups()] = {
  5896. onReceive: function (sandbox) {
  5897. if (Sandboxing.isOpen(sandbox)) {
  5898. detail.fireEventInstead.fold(function () {
  5899. return detail.doReposition(sandbox);
  5900. }, function (fe) {
  5901. return emit(sandbox, fe.event);
  5902. });
  5903. }
  5904. }
  5905. }, _a;
  5906. };
  5907. var onLoad$5 = function (component, repConfig, repState) {
  5908. repConfig.store.manager.onLoad(component, repConfig, repState);
  5909. };
  5910. var onUnload$2 = function (component, repConfig, repState) {
  5911. repConfig.store.manager.onUnload(component, repConfig, repState);
  5912. };
  5913. var setValue$3 = function (component, repConfig, repState, data) {
  5914. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5915. };
  5916. var getValue$3 = function (component, repConfig, repState) {
  5917. return repConfig.store.manager.getValue(component, repConfig, repState);
  5918. };
  5919. var getState$1 = function (component, repConfig, repState) {
  5920. return repState;
  5921. };
  5922. var RepresentApis = /*#__PURE__*/Object.freeze({
  5923. __proto__: null,
  5924. onLoad: onLoad$5,
  5925. onUnload: onUnload$2,
  5926. setValue: setValue$3,
  5927. getValue: getValue$3,
  5928. getState: getState$1
  5929. });
  5930. var events$f = function (repConfig, repState) {
  5931. var es = repConfig.resetOnDom ? [
  5932. runOnAttached(function (comp, _se) {
  5933. onLoad$5(comp, repConfig, repState);
  5934. }),
  5935. runOnDetached(function (comp, _se) {
  5936. onUnload$2(comp, repConfig, repState);
  5937. })
  5938. ] : [loadEvent(repConfig, repState, onLoad$5)];
  5939. return derive$2(es);
  5940. };
  5941. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5942. __proto__: null,
  5943. events: events$f
  5944. });
  5945. var memory$1 = function () {
  5946. var data = Cell(null);
  5947. var readState = function () {
  5948. return {
  5949. mode: 'memory',
  5950. value: data.get()
  5951. };
  5952. };
  5953. var isNotSet = function () {
  5954. return data.get() === null;
  5955. };
  5956. var clear = function () {
  5957. data.set(null);
  5958. };
  5959. return nu$8({
  5960. set: data.set,
  5961. get: data.get,
  5962. isNotSet: isNotSet,
  5963. clear: clear,
  5964. readState: readState
  5965. });
  5966. };
  5967. var manual = function () {
  5968. var readState = noop;
  5969. return nu$8({ readState: readState });
  5970. };
  5971. var dataset = function () {
  5972. var dataByValue = Cell({});
  5973. var dataByText = Cell({});
  5974. var readState = function () {
  5975. return {
  5976. mode: 'dataset',
  5977. dataByValue: dataByValue.get(),
  5978. dataByText: dataByText.get()
  5979. };
  5980. };
  5981. var clear = function () {
  5982. dataByValue.set({});
  5983. dataByText.set({});
  5984. };
  5985. var lookup = function (itemString) {
  5986. return get$e(dataByValue.get(), itemString).orThunk(function () {
  5987. return get$e(dataByText.get(), itemString);
  5988. });
  5989. };
  5990. var update = function (items) {
  5991. var currentDataByValue = dataByValue.get();
  5992. var currentDataByText = dataByText.get();
  5993. var newDataByValue = {};
  5994. var newDataByText = {};
  5995. each$1(items, function (item) {
  5996. newDataByValue[item.value] = item;
  5997. get$e(item, 'meta').each(function (meta) {
  5998. get$e(meta, 'text').each(function (text) {
  5999. newDataByText[text] = item;
  6000. });
  6001. });
  6002. });
  6003. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  6004. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  6005. };
  6006. return nu$8({
  6007. readState: readState,
  6008. lookup: lookup,
  6009. update: update,
  6010. clear: clear
  6011. });
  6012. };
  6013. var init$e = function (spec) {
  6014. return spec.store.manager.state(spec);
  6015. };
  6016. var RepresentState = /*#__PURE__*/Object.freeze({
  6017. __proto__: null,
  6018. memory: memory$1,
  6019. dataset: dataset,
  6020. manual: manual,
  6021. init: init$e
  6022. });
  6023. var setValue$2 = function (component, repConfig, repState, data) {
  6024. var store = repConfig.store;
  6025. repState.update([data]);
  6026. store.setValue(component, data);
  6027. repConfig.onSetValue(component, data);
  6028. };
  6029. var getValue$2 = function (component, repConfig, repState) {
  6030. var store = repConfig.store;
  6031. var key = store.getDataKey(component);
  6032. return repState.lookup(key).getOrThunk(function () {
  6033. return store.getFallbackEntry(key);
  6034. });
  6035. };
  6036. var onLoad$4 = function (component, repConfig, repState) {
  6037. var store = repConfig.store;
  6038. store.initialValue.each(function (data) {
  6039. setValue$2(component, repConfig, repState, data);
  6040. });
  6041. };
  6042. var onUnload$1 = function (component, repConfig, repState) {
  6043. repState.clear();
  6044. };
  6045. var DatasetStore = [
  6046. option('initialValue'),
  6047. required$1('getFallbackEntry'),
  6048. required$1('getDataKey'),
  6049. required$1('setValue'),
  6050. output$1('manager', {
  6051. setValue: setValue$2,
  6052. getValue: getValue$2,
  6053. onLoad: onLoad$4,
  6054. onUnload: onUnload$1,
  6055. state: dataset
  6056. })
  6057. ];
  6058. var getValue$1 = function (component, repConfig, _repState) {
  6059. return repConfig.store.getValue(component);
  6060. };
  6061. var setValue$1 = function (component, repConfig, _repState, data) {
  6062. repConfig.store.setValue(component, data);
  6063. repConfig.onSetValue(component, data);
  6064. };
  6065. var onLoad$3 = function (component, repConfig, _repState) {
  6066. repConfig.store.initialValue.each(function (data) {
  6067. repConfig.store.setValue(component, data);
  6068. });
  6069. };
  6070. var ManualStore = [
  6071. required$1('getValue'),
  6072. defaulted('setValue', noop),
  6073. option('initialValue'),
  6074. output$1('manager', {
  6075. setValue: setValue$1,
  6076. getValue: getValue$1,
  6077. onLoad: onLoad$3,
  6078. onUnload: noop,
  6079. state: NoState.init
  6080. })
  6081. ];
  6082. var setValue = function (component, repConfig, repState, data) {
  6083. repState.set(data);
  6084. repConfig.onSetValue(component, data);
  6085. };
  6086. var getValue = function (component, repConfig, repState) {
  6087. return repState.get();
  6088. };
  6089. var onLoad$2 = function (component, repConfig, repState) {
  6090. repConfig.store.initialValue.each(function (initVal) {
  6091. if (repState.isNotSet()) {
  6092. repState.set(initVal);
  6093. }
  6094. });
  6095. };
  6096. var onUnload = function (component, repConfig, repState) {
  6097. repState.clear();
  6098. };
  6099. var MemoryStore = [
  6100. option('initialValue'),
  6101. output$1('manager', {
  6102. setValue: setValue,
  6103. getValue: getValue,
  6104. onLoad: onLoad$2,
  6105. onUnload: onUnload,
  6106. state: memory$1
  6107. })
  6108. ];
  6109. var RepresentSchema = [
  6110. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  6111. memory: MemoryStore,
  6112. manual: ManualStore,
  6113. dataset: DatasetStore
  6114. })),
  6115. onHandler('onSetValue'),
  6116. defaulted('resetOnDom', false)
  6117. ];
  6118. var Representing = create$7({
  6119. fields: RepresentSchema,
  6120. name: 'representing',
  6121. active: ActiveRepresenting,
  6122. apis: RepresentApis,
  6123. extra: {
  6124. setValueFrom: function (component, source) {
  6125. var value = Representing.getValue(source);
  6126. Representing.setValue(component, value);
  6127. }
  6128. },
  6129. state: RepresentState
  6130. });
  6131. var field = function (name, forbidden) {
  6132. return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  6133. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  6134. }).concat([customField('dump', identity$1)]));
  6135. };
  6136. var get$2 = function (data) {
  6137. return data.dump;
  6138. };
  6139. var augment = function (data, original) {
  6140. return __assign(__assign({}, data.dump), derive$1(original));
  6141. };
  6142. var SketchBehaviours = {
  6143. field: field,
  6144. augment: augment,
  6145. get: get$2
  6146. };
  6147. var _placeholder = 'placeholder';
  6148. var adt$3 = Adt.generate([
  6149. {
  6150. single: [
  6151. 'required',
  6152. 'valueThunk'
  6153. ]
  6154. },
  6155. {
  6156. multiple: [
  6157. 'required',
  6158. 'valueThunks'
  6159. ]
  6160. }
  6161. ]);
  6162. var isSubstituted = function (spec) {
  6163. return has$2(spec, 'uiType');
  6164. };
  6165. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  6166. if (owner.exists(function (o) {
  6167. return o !== compSpec.owner;
  6168. })) {
  6169. return adt$3.single(true, constant$1(compSpec));
  6170. }
  6171. return get$e(placeholders, compSpec.name).fold(function () {
  6172. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  6173. }, function (newSpec) {
  6174. return newSpec.replace();
  6175. });
  6176. };
  6177. var scan = function (owner, detail, compSpec, placeholders) {
  6178. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  6179. return subPlaceholder(owner, detail, compSpec, placeholders);
  6180. } else {
  6181. return adt$3.single(false, constant$1(compSpec));
  6182. }
  6183. };
  6184. var substitute = function (owner, detail, compSpec, placeholders) {
  6185. var base = scan(owner, detail, compSpec, placeholders);
  6186. return base.fold(function (req, valueThunk) {
  6187. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  6188. var childSpecs = get$e(value, 'components').getOr([]);
  6189. var substituted = bind$3(childSpecs, function (c) {
  6190. return substitute(owner, detail, c, placeholders);
  6191. });
  6192. return [__assign(__assign({}, value), { components: substituted })];
  6193. }, function (req, valuesThunk) {
  6194. if (isSubstituted(compSpec)) {
  6195. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  6196. var preprocessor = compSpec.validated.preprocess.getOr(identity$1);
  6197. return preprocessor(values);
  6198. } else {
  6199. return valuesThunk(detail);
  6200. }
  6201. });
  6202. };
  6203. var substituteAll = function (owner, detail, components, placeholders) {
  6204. return bind$3(components, function (c) {
  6205. return substitute(owner, detail, c, placeholders);
  6206. });
  6207. };
  6208. var oneReplace = function (label, replacements) {
  6209. var called = false;
  6210. var used = function () {
  6211. return called;
  6212. };
  6213. var replace = function () {
  6214. if (called) {
  6215. throw new Error('Trying to use the same placeholder more than once: ' + label);
  6216. }
  6217. called = true;
  6218. return replacements;
  6219. };
  6220. var required = function () {
  6221. return replacements.fold(function (req, _) {
  6222. return req;
  6223. }, function (req, _) {
  6224. return req;
  6225. });
  6226. };
  6227. return {
  6228. name: constant$1(label),
  6229. required: required,
  6230. used: used,
  6231. replace: replace
  6232. };
  6233. };
  6234. var substitutePlaces = function (owner, detail, components, placeholders) {
  6235. var ps = map(placeholders, function (ph, name) {
  6236. return oneReplace(name, ph);
  6237. });
  6238. var outcome = substituteAll(owner, detail, components, ps);
  6239. each(ps, function (p) {
  6240. if (p.used() === false && p.required()) {
  6241. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  6242. }
  6243. });
  6244. return outcome;
  6245. };
  6246. var single$2 = adt$3.single;
  6247. var multiple = adt$3.multiple;
  6248. var placeholder = constant$1(_placeholder);
  6249. var adt$2 = Adt.generate([
  6250. { required: ['data'] },
  6251. { external: ['data'] },
  6252. { optional: ['data'] },
  6253. { group: ['data'] }
  6254. ]);
  6255. var fFactory = defaulted('factory', { sketch: identity$1 });
  6256. var fSchema = defaulted('schema', []);
  6257. var fName = required$1('name');
  6258. var fPname = field$1('pname', 'pname', defaultedThunk(function (typeSpec) {
  6259. return '<alloy.' + generate$6(typeSpec.name) + '>';
  6260. }), anyValue());
  6261. var fGroupSchema = customField('schema', function () {
  6262. return [option('preprocess')];
  6263. });
  6264. var fDefaults = defaulted('defaults', constant$1({}));
  6265. var fOverrides = defaulted('overrides', constant$1({}));
  6266. var requiredSpec = objOf([
  6267. fFactory,
  6268. fSchema,
  6269. fName,
  6270. fPname,
  6271. fDefaults,
  6272. fOverrides
  6273. ]);
  6274. var externalSpec = objOf([
  6275. fFactory,
  6276. fSchema,
  6277. fName,
  6278. fDefaults,
  6279. fOverrides
  6280. ]);
  6281. var optionalSpec = objOf([
  6282. fFactory,
  6283. fSchema,
  6284. fName,
  6285. fPname,
  6286. fDefaults,
  6287. fOverrides
  6288. ]);
  6289. var groupSpec = objOf([
  6290. fFactory,
  6291. fGroupSchema,
  6292. fName,
  6293. required$1('unit'),
  6294. fPname,
  6295. fDefaults,
  6296. fOverrides
  6297. ]);
  6298. var asNamedPart = function (part) {
  6299. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  6300. };
  6301. var name$1 = function (part) {
  6302. var get = function (data) {
  6303. return data.name;
  6304. };
  6305. return part.fold(get, get, get, get);
  6306. };
  6307. var asCommon = function (part) {
  6308. return part.fold(identity$1, identity$1, identity$1, identity$1);
  6309. };
  6310. var convert = function (adtConstructor, partSchema) {
  6311. return function (spec) {
  6312. var data = asRawOrDie$1('Converting part type', partSchema, spec);
  6313. return adtConstructor(data);
  6314. };
  6315. };
  6316. var required = convert(adt$2.required, requiredSpec);
  6317. var external$1 = convert(adt$2.external, externalSpec);
  6318. var optional = convert(adt$2.optional, optionalSpec);
  6319. var group = convert(adt$2.group, groupSpec);
  6320. var original = constant$1('entirety');
  6321. var PartType = /*#__PURE__*/Object.freeze({
  6322. __proto__: null,
  6323. required: required,
  6324. external: external$1,
  6325. optional: optional,
  6326. group: group,
  6327. asNamedPart: asNamedPart,
  6328. name: name$1,
  6329. asCommon: asCommon,
  6330. original: original
  6331. });
  6332. var combine = function (detail, data, partSpec, partValidated) {
  6333. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  6334. };
  6335. var subs = function (owner, detail, parts) {
  6336. var internals = {};
  6337. var externals = {};
  6338. each$1(parts, function (part) {
  6339. part.fold(function (data) {
  6340. internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  6341. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6342. });
  6343. }, function (data) {
  6344. var partSpec = detail.parts[data.name];
  6345. externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  6346. }, function (data) {
  6347. internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  6348. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6349. });
  6350. }, function (data) {
  6351. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  6352. var units = detail[data.name];
  6353. return map$2(units, function (u) {
  6354. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  6355. });
  6356. });
  6357. });
  6358. });
  6359. return {
  6360. internals: constant$1(internals),
  6361. externals: constant$1(externals)
  6362. };
  6363. };
  6364. var generate$3 = function (owner, parts) {
  6365. var r = {};
  6366. each$1(parts, function (part) {
  6367. asNamedPart(part).each(function (np) {
  6368. var g = doGenerateOne(owner, np.pname);
  6369. r[np.name] = function (config) {
  6370. var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  6371. return __assign(__assign({}, g), {
  6372. config: config,
  6373. validated: validated
  6374. });
  6375. };
  6376. });
  6377. });
  6378. return r;
  6379. };
  6380. var doGenerateOne = function (owner, pname) {
  6381. return {
  6382. uiType: placeholder(),
  6383. owner: owner,
  6384. name: pname
  6385. };
  6386. };
  6387. var generateOne$1 = function (owner, pname, config) {
  6388. return {
  6389. uiType: placeholder(),
  6390. owner: owner,
  6391. name: pname,
  6392. config: config,
  6393. validated: {}
  6394. };
  6395. };
  6396. var schemas = function (parts) {
  6397. return bind$3(parts, function (part) {
  6398. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  6399. return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  6400. }).toArray();
  6401. });
  6402. };
  6403. var names = function (parts) {
  6404. return map$2(parts, name$1);
  6405. };
  6406. var substitutes = function (owner, detail, parts) {
  6407. return subs(owner, detail, parts);
  6408. };
  6409. var components$1 = function (owner, detail, internals) {
  6410. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  6411. };
  6412. var getPart = function (component, detail, partKey) {
  6413. var uid = detail.partUids[partKey];
  6414. return component.getSystem().getByUid(uid).toOptional();
  6415. };
  6416. var getPartOrDie = function (component, detail, partKey) {
  6417. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  6418. };
  6419. var getParts = function (component, detail, partKeys) {
  6420. var r = {};
  6421. var uids = detail.partUids;
  6422. var system = component.getSystem();
  6423. each$1(partKeys, function (pk) {
  6424. r[pk] = constant$1(system.getByUid(uids[pk]));
  6425. });
  6426. return r;
  6427. };
  6428. var getAllParts = function (component, detail) {
  6429. var system = component.getSystem();
  6430. return map(detail.partUids, function (pUid, _k) {
  6431. return constant$1(system.getByUid(pUid));
  6432. });
  6433. };
  6434. var getAllPartNames = function (detail) {
  6435. return keys(detail.partUids);
  6436. };
  6437. var getPartsOrDie = function (component, detail, partKeys) {
  6438. var r = {};
  6439. var uids = detail.partUids;
  6440. var system = component.getSystem();
  6441. each$1(partKeys, function (pk) {
  6442. r[pk] = constant$1(system.getByUid(uids[pk]).getOrDie());
  6443. });
  6444. return r;
  6445. };
  6446. var defaultUids = function (baseUid, partTypes) {
  6447. var partNames = names(partTypes);
  6448. return wrapAll(map$2(partNames, function (pn) {
  6449. return {
  6450. key: pn,
  6451. value: baseUid + '-' + pn
  6452. };
  6453. }));
  6454. };
  6455. var defaultUidsSchema = function (partTypes) {
  6456. return field$1('partUids', 'partUids', mergeWithThunk(function (spec) {
  6457. return defaultUids(spec.uid, partTypes);
  6458. }), anyValue());
  6459. };
  6460. var AlloyParts = /*#__PURE__*/Object.freeze({
  6461. __proto__: null,
  6462. generate: generate$3,
  6463. generateOne: generateOne$1,
  6464. schemas: schemas,
  6465. names: names,
  6466. substitutes: substitutes,
  6467. components: components$1,
  6468. defaultUids: defaultUids,
  6469. defaultUidsSchema: defaultUidsSchema,
  6470. getAllParts: getAllParts,
  6471. getAllPartNames: getAllPartNames,
  6472. getPart: getPart,
  6473. getPartOrDie: getPartOrDie,
  6474. getParts: getParts,
  6475. getPartsOrDie: getPartsOrDie
  6476. });
  6477. var base = function (partSchemas, partUidsSchemas) {
  6478. var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  6479. return ps.concat([
  6480. required$1('uid'),
  6481. defaulted('dom', {}),
  6482. defaulted('components', []),
  6483. snapshot('originalSpec'),
  6484. defaulted('debug.sketcher', {})
  6485. ]).concat(partUidsSchemas);
  6486. };
  6487. var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6488. var baseS = base(partSchemas, partUidsSchemas);
  6489. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6490. };
  6491. var single$1 = function (owner, schema, factory, spec) {
  6492. var specWithUid = supplyUid(spec);
  6493. var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  6494. return factory(detail, specWithUid);
  6495. };
  6496. var composite$1 = function (owner, schema, partTypes, factory, spec) {
  6497. var specWithUid = supplyUid(spec);
  6498. var partSchemas = schemas(partTypes);
  6499. var partUidsSchema = defaultUidsSchema(partTypes);
  6500. var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6501. var subs = substitutes(owner, detail, partTypes);
  6502. var components = components$1(owner, detail, subs.internals());
  6503. return factory(detail, components, specWithUid, subs.externals());
  6504. };
  6505. var hasUid = function (spec) {
  6506. return has$2(spec, 'uid');
  6507. };
  6508. var supplyUid = function (spec) {
  6509. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5('uid') });
  6510. };
  6511. var isSketchSpec = function (spec) {
  6512. return spec.uid !== undefined;
  6513. };
  6514. var singleSchema = objOfOnly([
  6515. required$1('name'),
  6516. required$1('factory'),
  6517. required$1('configFields'),
  6518. defaulted('apis', {}),
  6519. defaulted('extraApis', {})
  6520. ]);
  6521. var compositeSchema = objOfOnly([
  6522. required$1('name'),
  6523. required$1('factory'),
  6524. required$1('configFields'),
  6525. required$1('partFields'),
  6526. defaulted('apis', {}),
  6527. defaulted('extraApis', {})
  6528. ]);
  6529. var single = function (rawConfig) {
  6530. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6531. var sketch = function (spec) {
  6532. return single$1(config.name, config.configFields, config.factory, spec);
  6533. };
  6534. var apis = map(config.apis, makeApi);
  6535. var extraApis = map(config.extraApis, function (f, k) {
  6536. return markAsExtraApi(f, k);
  6537. });
  6538. return __assign(__assign({
  6539. name: config.name,
  6540. configFields: config.configFields,
  6541. sketch: sketch
  6542. }, apis), extraApis);
  6543. };
  6544. var composite = function (rawConfig) {
  6545. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6546. var sketch = function (spec) {
  6547. return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  6548. };
  6549. var parts = generate$3(config.name, config.partFields);
  6550. var apis = map(config.apis, makeApi);
  6551. var extraApis = map(config.extraApis, function (f, k) {
  6552. return markAsExtraApi(f, k);
  6553. });
  6554. return __assign(__assign({
  6555. name: config.name,
  6556. partFields: config.partFields,
  6557. configFields: config.configFields,
  6558. sketch: sketch,
  6559. parts: parts
  6560. }, apis), extraApis);
  6561. };
  6562. var inside = function (target) {
  6563. return name$2(target) === 'input' && get$c(target, 'type') !== 'radio' || name$2(target) === 'textarea';
  6564. };
  6565. var getCurrent = function (component, composeConfig, _composeState) {
  6566. return composeConfig.find(component);
  6567. };
  6568. var ComposeApis = /*#__PURE__*/Object.freeze({
  6569. __proto__: null,
  6570. getCurrent: getCurrent
  6571. });
  6572. var ComposeSchema = [required$1('find')];
  6573. var Composing = create$7({
  6574. fields: ComposeSchema,
  6575. name: 'composing',
  6576. apis: ComposeApis
  6577. });
  6578. var nativeDisabled = [
  6579. 'input',
  6580. 'button',
  6581. 'textarea',
  6582. 'select'
  6583. ];
  6584. var onLoad$1 = function (component, disableConfig, disableState) {
  6585. var f = disableConfig.disabled() ? disable$1 : enable$1;
  6586. f(component, disableConfig);
  6587. };
  6588. var hasNative = function (component, config) {
  6589. return config.useNative === true && contains$2(nativeDisabled, name$2(component.element));
  6590. };
  6591. var nativeIsDisabled = function (component) {
  6592. return has$1(component.element, 'disabled');
  6593. };
  6594. var nativeDisable = function (component) {
  6595. set$7(component.element, 'disabled', 'disabled');
  6596. };
  6597. var nativeEnable = function (component) {
  6598. remove$6(component.element, 'disabled');
  6599. };
  6600. var ariaIsDisabled = function (component) {
  6601. return get$c(component.element, 'aria-disabled') === 'true';
  6602. };
  6603. var ariaDisable = function (component) {
  6604. set$7(component.element, 'aria-disabled', 'true');
  6605. };
  6606. var ariaEnable = function (component) {
  6607. set$7(component.element, 'aria-disabled', 'false');
  6608. };
  6609. var disable$1 = function (component, disableConfig, _disableState) {
  6610. disableConfig.disableClass.each(function (disableClass) {
  6611. add$2(component.element, disableClass);
  6612. });
  6613. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6614. f(component);
  6615. disableConfig.onDisabled(component);
  6616. };
  6617. var enable$1 = function (component, disableConfig, _disableState) {
  6618. disableConfig.disableClass.each(function (disableClass) {
  6619. remove$3(component.element, disableClass);
  6620. });
  6621. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6622. f(component);
  6623. disableConfig.onEnabled(component);
  6624. };
  6625. var isDisabled = function (component, disableConfig) {
  6626. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6627. };
  6628. var set$3 = function (component, disableConfig, disableState, disabled) {
  6629. var f = disabled ? disable$1 : enable$1;
  6630. f(component, disableConfig);
  6631. };
  6632. var DisableApis = /*#__PURE__*/Object.freeze({
  6633. __proto__: null,
  6634. enable: enable$1,
  6635. disable: disable$1,
  6636. isDisabled: isDisabled,
  6637. onLoad: onLoad$1,
  6638. set: set$3
  6639. });
  6640. var exhibit$5 = function (base, disableConfig) {
  6641. return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6642. };
  6643. var events$e = function (disableConfig, disableState) {
  6644. return derive$2([
  6645. abort(execute$5(), function (component, _simulatedEvent) {
  6646. return isDisabled(component, disableConfig);
  6647. }),
  6648. loadEvent(disableConfig, disableState, onLoad$1)
  6649. ]);
  6650. };
  6651. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6652. __proto__: null,
  6653. exhibit: exhibit$5,
  6654. events: events$e
  6655. });
  6656. var DisableSchema = [
  6657. defaultedFunction('disabled', never),
  6658. defaulted('useNative', true),
  6659. option('disableClass'),
  6660. onHandler('onDisabled'),
  6661. onHandler('onEnabled')
  6662. ];
  6663. var Disabling = create$7({
  6664. fields: DisableSchema,
  6665. name: 'disabling',
  6666. active: ActiveDisable,
  6667. apis: DisableApis
  6668. });
  6669. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6670. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  6671. each$1(highlighted, function (h) {
  6672. if (!exists(skip, function (skipComp) {
  6673. return skipComp.element === h;
  6674. })) {
  6675. remove$3(h, hConfig.highlightClass);
  6676. component.getSystem().getByDom(h).each(function (target) {
  6677. hConfig.onDehighlight(component, target);
  6678. emit(target, dehighlight$1());
  6679. });
  6680. }
  6681. });
  6682. };
  6683. var dehighlightAll = function (component, hConfig, hState) {
  6684. return dehighlightAllExcept(component, hConfig, hState, []);
  6685. };
  6686. var dehighlight = function (component, hConfig, hState, target) {
  6687. if (isHighlighted(component, hConfig, hState, target)) {
  6688. remove$3(target.element, hConfig.highlightClass);
  6689. hConfig.onDehighlight(component, target);
  6690. emit(target, dehighlight$1());
  6691. }
  6692. };
  6693. var highlight = function (component, hConfig, hState, target) {
  6694. dehighlightAllExcept(component, hConfig, hState, [target]);
  6695. if (!isHighlighted(component, hConfig, hState, target)) {
  6696. add$2(target.element, hConfig.highlightClass);
  6697. hConfig.onHighlight(component, target);
  6698. emit(target, highlight$1());
  6699. }
  6700. };
  6701. var highlightFirst = function (component, hConfig, hState) {
  6702. getFirst(component, hConfig).each(function (firstComp) {
  6703. highlight(component, hConfig, hState, firstComp);
  6704. });
  6705. };
  6706. var highlightLast = function (component, hConfig, hState) {
  6707. getLast(component, hConfig).each(function (lastComp) {
  6708. highlight(component, hConfig, hState, lastComp);
  6709. });
  6710. };
  6711. var highlightAt = function (component, hConfig, hState, index) {
  6712. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6713. throw err;
  6714. }, function (firstComp) {
  6715. highlight(component, hConfig, hState, firstComp);
  6716. });
  6717. };
  6718. var highlightBy = function (component, hConfig, hState, predicate) {
  6719. var candidates = getCandidates(component, hConfig);
  6720. var targetComp = find$5(candidates, predicate);
  6721. targetComp.each(function (c) {
  6722. highlight(component, hConfig, hState, c);
  6723. });
  6724. };
  6725. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6726. return has(queryTarget.element, hConfig.highlightClass);
  6727. };
  6728. var getHighlighted = function (component, hConfig, _hState) {
  6729. return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  6730. return component.getSystem().getByDom(e).toOptional();
  6731. });
  6732. };
  6733. var getByIndex = function (component, hConfig, hState, index) {
  6734. var items = descendants(component.element, '.' + hConfig.itemClass);
  6735. return Optional.from(items[index]).fold(function () {
  6736. return Result.error(new Error('No element found with index ' + index));
  6737. }, component.getSystem().getByDom);
  6738. };
  6739. var getFirst = function (component, hConfig, _hState) {
  6740. return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  6741. return component.getSystem().getByDom(e).toOptional();
  6742. });
  6743. };
  6744. var getLast = function (component, hConfig, _hState) {
  6745. var items = descendants(component.element, '.' + hConfig.itemClass);
  6746. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  6747. return last.bind(function (c) {
  6748. return component.getSystem().getByDom(c).toOptional();
  6749. });
  6750. };
  6751. var getDelta$2 = function (component, hConfig, hState, delta) {
  6752. var items = descendants(component.element, '.' + hConfig.itemClass);
  6753. var current = findIndex$1(items, function (item) {
  6754. return has(item, hConfig.highlightClass);
  6755. });
  6756. return current.bind(function (selected) {
  6757. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6758. return component.getSystem().getByDom(items[dest]).toOptional();
  6759. });
  6760. };
  6761. var getPrevious = function (component, hConfig, hState) {
  6762. return getDelta$2(component, hConfig, hState, -1);
  6763. };
  6764. var getNext = function (component, hConfig, hState) {
  6765. return getDelta$2(component, hConfig, hState, +1);
  6766. };
  6767. var getCandidates = function (component, hConfig, _hState) {
  6768. var items = descendants(component.element, '.' + hConfig.itemClass);
  6769. return cat(map$2(items, function (i) {
  6770. return component.getSystem().getByDom(i).toOptional();
  6771. }));
  6772. };
  6773. var HighlightApis = /*#__PURE__*/Object.freeze({
  6774. __proto__: null,
  6775. dehighlightAll: dehighlightAll,
  6776. dehighlight: dehighlight,
  6777. highlight: highlight,
  6778. highlightFirst: highlightFirst,
  6779. highlightLast: highlightLast,
  6780. highlightAt: highlightAt,
  6781. highlightBy: highlightBy,
  6782. isHighlighted: isHighlighted,
  6783. getHighlighted: getHighlighted,
  6784. getFirst: getFirst,
  6785. getLast: getLast,
  6786. getPrevious: getPrevious,
  6787. getNext: getNext,
  6788. getCandidates: getCandidates
  6789. });
  6790. var HighlightSchema = [
  6791. required$1('highlightClass'),
  6792. required$1('itemClass'),
  6793. onHandler('onHighlight'),
  6794. onHandler('onDehighlight')
  6795. ];
  6796. var Highlighting = create$7({
  6797. fields: HighlightSchema,
  6798. name: 'highlighting',
  6799. apis: HighlightApis
  6800. });
  6801. var BACKSPACE = [8];
  6802. var TAB = [9];
  6803. var ENTER = [13];
  6804. var ESCAPE = [27];
  6805. var SPACE = [32];
  6806. var LEFT = [37];
  6807. var UP = [38];
  6808. var RIGHT = [39];
  6809. var DOWN = [40];
  6810. var cyclePrev = function (values, index, predicate) {
  6811. var before = reverse(values.slice(0, index));
  6812. var after = reverse(values.slice(index + 1));
  6813. return find$5(before.concat(after), predicate);
  6814. };
  6815. var tryPrev = function (values, index, predicate) {
  6816. var before = reverse(values.slice(0, index));
  6817. return find$5(before, predicate);
  6818. };
  6819. var cycleNext = function (values, index, predicate) {
  6820. var before = values.slice(0, index);
  6821. var after = values.slice(index + 1);
  6822. return find$5(after.concat(before), predicate);
  6823. };
  6824. var tryNext = function (values, index, predicate) {
  6825. var after = values.slice(index + 1);
  6826. return find$5(after, predicate);
  6827. };
  6828. var inSet = function (keys) {
  6829. return function (event) {
  6830. var raw = event.raw;
  6831. return contains$2(keys, raw.which);
  6832. };
  6833. };
  6834. var and = function (preds) {
  6835. return function (event) {
  6836. return forall(preds, function (pred) {
  6837. return pred(event);
  6838. });
  6839. };
  6840. };
  6841. var isShift = function (event) {
  6842. var raw = event.raw;
  6843. return raw.shiftKey === true;
  6844. };
  6845. var isControl = function (event) {
  6846. var raw = event.raw;
  6847. return raw.ctrlKey === true;
  6848. };
  6849. var isNotShift = not(isShift);
  6850. var rule = function (matches, action) {
  6851. return {
  6852. matches: matches,
  6853. classification: action
  6854. };
  6855. };
  6856. var choose = function (transitions, event) {
  6857. var transition = find$5(transitions, function (t) {
  6858. return t.matches(event);
  6859. });
  6860. return transition.map(function (t) {
  6861. return t.classification;
  6862. });
  6863. };
  6864. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6865. var noChange = prevFocus.exists(function (p) {
  6866. return newFocus.exists(function (n) {
  6867. return eq(n, p);
  6868. });
  6869. });
  6870. if (!noChange) {
  6871. emitWith(component, focusShifted(), {
  6872. prevFocus: prevFocus,
  6873. newFocus: newFocus
  6874. });
  6875. }
  6876. };
  6877. var dom$2 = function () {
  6878. var get = function (component) {
  6879. return search(component.element);
  6880. };
  6881. var set = function (component, focusee) {
  6882. var prevFocus = get(component);
  6883. component.getSystem().triggerFocus(focusee, component.element);
  6884. var newFocus = get(component);
  6885. reportFocusShifting(component, prevFocus, newFocus);
  6886. };
  6887. return {
  6888. get: get,
  6889. set: set
  6890. };
  6891. };
  6892. var highlights = function () {
  6893. var get = function (component) {
  6894. return Highlighting.getHighlighted(component).map(function (item) {
  6895. return item.element;
  6896. });
  6897. };
  6898. var set = function (component, element) {
  6899. var prevFocus = get(component);
  6900. component.getSystem().getByDom(element).fold(noop, function (item) {
  6901. Highlighting.highlight(component, item);
  6902. });
  6903. var newFocus = get(component);
  6904. reportFocusShifting(component, prevFocus, newFocus);
  6905. };
  6906. return {
  6907. get: get,
  6908. set: set
  6909. };
  6910. };
  6911. var FocusInsideModes;
  6912. (function (FocusInsideModes) {
  6913. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6914. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6915. FocusInsideModes['OnApiMode'] = 'onApi';
  6916. }(FocusInsideModes || (FocusInsideModes = {})));
  6917. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6918. var schema = function () {
  6919. return infoSchema.concat([
  6920. defaulted('focusManager', dom$2()),
  6921. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6922. return contains$2([
  6923. 'onFocus',
  6924. 'onEnterOrSpace',
  6925. 'onApi'
  6926. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6927. })),
  6928. output$1('handler', me),
  6929. output$1('state', stateInit),
  6930. output$1('sendFocusIn', optFocusIn)
  6931. ]);
  6932. };
  6933. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6934. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6935. return choose(rules, simulatedEvent.event).bind(function (rule) {
  6936. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6937. });
  6938. };
  6939. var toEvents = function (keyingConfig, keyingState) {
  6940. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6941. return run$1(focus$4(), function (component, simulatedEvent) {
  6942. focusIn(component, keyingConfig, keyingState);
  6943. simulatedEvent.stop();
  6944. });
  6945. });
  6946. var tryGoInsideComponent = function (component, simulatedEvent) {
  6947. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  6948. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6949. optFocusIn(keyingConfig).each(function (focusIn) {
  6950. focusIn(component, keyingConfig, keyingState);
  6951. simulatedEvent.stop();
  6952. });
  6953. }
  6954. };
  6955. var keyboardEvents = [
  6956. run$1(keydown(), function (component, simulatedEvent) {
  6957. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6958. tryGoInsideComponent(component, simulatedEvent);
  6959. }, function (_) {
  6960. simulatedEvent.stop();
  6961. });
  6962. }),
  6963. run$1(keyup(), function (component, simulatedEvent) {
  6964. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6965. simulatedEvent.stop();
  6966. });
  6967. })
  6968. ];
  6969. return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
  6970. };
  6971. var me = {
  6972. schema: schema,
  6973. processKey: processKey,
  6974. toEvents: toEvents
  6975. };
  6976. return me;
  6977. };
  6978. var create$5 = function (cyclicField) {
  6979. var schema = [
  6980. option('onEscape'),
  6981. option('onEnter'),
  6982. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6983. defaulted('firstTabstop', 0),
  6984. defaulted('useTabstopAt', always),
  6985. option('visibilitySelector')
  6986. ].concat([cyclicField]);
  6987. var isVisible = function (tabbingConfig, element) {
  6988. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6989. return closest$1(element, sel);
  6990. }).getOr(element);
  6991. return get$8(target) > 0;
  6992. };
  6993. var findInitial = function (component, tabbingConfig) {
  6994. var tabstops = descendants(component.element, tabbingConfig.selector);
  6995. var visibles = filter$2(tabstops, function (elem) {
  6996. return isVisible(tabbingConfig, elem);
  6997. });
  6998. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  6999. };
  7000. var findCurrent = function (component, tabbingConfig) {
  7001. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  7002. return closest$1(elem, tabbingConfig.selector);
  7003. });
  7004. };
  7005. var isTabstop = function (tabbingConfig, element) {
  7006. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  7007. };
  7008. var focusIn = function (component, tabbingConfig, _tabbingState) {
  7009. findInitial(component, tabbingConfig).each(function (target) {
  7010. tabbingConfig.focusManager.set(component, target);
  7011. });
  7012. };
  7013. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  7014. return cycle(tabstops, stopIndex, function (elem) {
  7015. return isTabstop(tabbingConfig, elem);
  7016. }).fold(function () {
  7017. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  7018. }, function (target) {
  7019. tabbingConfig.focusManager.set(component, target);
  7020. return Optional.some(true);
  7021. });
  7022. };
  7023. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  7024. var tabstops = descendants(component.element, tabbingConfig.selector);
  7025. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  7026. var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  7027. return optStopIndex.bind(function (stopIndex) {
  7028. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  7029. });
  7030. });
  7031. };
  7032. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  7033. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  7034. return go(component, simulatedEvent, tabbingConfig, navigate);
  7035. };
  7036. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  7037. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  7038. return go(component, simulatedEvent, tabbingConfig, navigate);
  7039. };
  7040. var execute = function (component, simulatedEvent, tabbingConfig) {
  7041. return tabbingConfig.onEnter.bind(function (f) {
  7042. return f(component, simulatedEvent);
  7043. });
  7044. };
  7045. var exit = function (component, simulatedEvent, tabbingConfig) {
  7046. return tabbingConfig.onEscape.bind(function (f) {
  7047. return f(component, simulatedEvent);
  7048. });
  7049. };
  7050. var getKeydownRules = constant$1([
  7051. rule(and([
  7052. isShift,
  7053. inSet(TAB)
  7054. ]), goBackwards),
  7055. rule(inSet(TAB), goForwards),
  7056. rule(inSet(ESCAPE), exit),
  7057. rule(and([
  7058. isNotShift,
  7059. inSet(ENTER)
  7060. ]), execute)
  7061. ]);
  7062. var getKeyupRules = constant$1([]);
  7063. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  7064. return Optional.some(focusIn);
  7065. });
  7066. };
  7067. var AcyclicType = create$5(customField('cyclic', never));
  7068. var CyclicType = create$5(customField('cyclic', always));
  7069. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  7070. dispatch(component, focused, execute$5());
  7071. return Optional.some(true);
  7072. };
  7073. var defaultExecute = function (component, simulatedEvent, focused) {
  7074. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  7075. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  7076. };
  7077. var stopEventForFirefox = function (_component, _simulatedEvent) {
  7078. return Optional.some(true);
  7079. };
  7080. var schema$v = [
  7081. defaulted('execute', defaultExecute),
  7082. defaulted('useSpace', false),
  7083. defaulted('useEnter', true),
  7084. defaulted('useControlEnter', false),
  7085. defaulted('useDown', false)
  7086. ];
  7087. var execute$4 = function (component, simulatedEvent, executeConfig) {
  7088. return executeConfig.execute(component, simulatedEvent, component.element);
  7089. };
  7090. var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7091. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  7092. var enterExec = executeConfig.useEnter ? ENTER : [];
  7093. var downExec = executeConfig.useDown ? DOWN : [];
  7094. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  7095. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  7096. isControl,
  7097. inSet(ENTER)
  7098. ]), execute$4)] : []);
  7099. };
  7100. var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7101. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7102. };
  7103. var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  7104. return Optional.none();
  7105. });
  7106. var flatgrid$1 = function () {
  7107. var dimensions = value$1();
  7108. var setGridSize = function (numRows, numColumns) {
  7109. dimensions.set({
  7110. numRows: numRows,
  7111. numColumns: numColumns
  7112. });
  7113. };
  7114. var getNumRows = function () {
  7115. return dimensions.get().map(function (d) {
  7116. return d.numRows;
  7117. });
  7118. };
  7119. var getNumColumns = function () {
  7120. return dimensions.get().map(function (d) {
  7121. return d.numColumns;
  7122. });
  7123. };
  7124. return nu$8({
  7125. readState: function () {
  7126. return dimensions.get().map(function (d) {
  7127. return {
  7128. numRows: String(d.numRows),
  7129. numColumns: String(d.numColumns)
  7130. };
  7131. }).getOr({
  7132. numRows: '?',
  7133. numColumns: '?'
  7134. });
  7135. },
  7136. setGridSize: setGridSize,
  7137. getNumRows: getNumRows,
  7138. getNumColumns: getNumColumns
  7139. });
  7140. };
  7141. var init$d = function (spec) {
  7142. return spec.state(spec);
  7143. };
  7144. var KeyingState = /*#__PURE__*/Object.freeze({
  7145. __proto__: null,
  7146. flatgrid: flatgrid$1,
  7147. init: init$d
  7148. });
  7149. var useH = function (movement) {
  7150. return function (component, simulatedEvent, config, state) {
  7151. var move = movement(component.element);
  7152. return use(move, component, simulatedEvent, config, state);
  7153. };
  7154. };
  7155. var west$1 = function (moveLeft, moveRight) {
  7156. var movement = onDirection(moveLeft, moveRight);
  7157. return useH(movement);
  7158. };
  7159. var east$1 = function (moveLeft, moveRight) {
  7160. var movement = onDirection(moveRight, moveLeft);
  7161. return useH(movement);
  7162. };
  7163. var useV = function (move) {
  7164. return function (component, simulatedEvent, config, state) {
  7165. return use(move, component, simulatedEvent, config, state);
  7166. };
  7167. };
  7168. var use = function (move, component, simulatedEvent, config, state) {
  7169. var outcome = config.focusManager.get(component).bind(function (focused) {
  7170. return move(component.element, focused, config, state);
  7171. });
  7172. return outcome.map(function (newFocus) {
  7173. config.focusManager.set(component, newFocus);
  7174. return true;
  7175. });
  7176. };
  7177. var north$1 = useV;
  7178. var south$1 = useV;
  7179. var move$1 = useV;
  7180. var isHidden$1 = function (dom) {
  7181. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  7182. };
  7183. var isVisible = function (element) {
  7184. return !isHidden$1(element.dom);
  7185. };
  7186. var locate = function (candidates, predicate) {
  7187. return findIndex$1(candidates, predicate).map(function (index) {
  7188. return {
  7189. index: index,
  7190. candidates: candidates
  7191. };
  7192. });
  7193. };
  7194. var locateVisible = function (container, current, selector) {
  7195. var predicate = function (x) {
  7196. return eq(x, current);
  7197. };
  7198. var candidates = descendants(container, selector);
  7199. var visible = filter$2(candidates, isVisible);
  7200. return locate(visible, predicate);
  7201. };
  7202. var findIndex = function (elements, target) {
  7203. return findIndex$1(elements, function (elem) {
  7204. return eq(target, elem);
  7205. });
  7206. };
  7207. var withGrid = function (values, index, numCols, f) {
  7208. var oldRow = Math.floor(index / numCols);
  7209. var oldColumn = index % numCols;
  7210. return f(oldRow, oldColumn).bind(function (address) {
  7211. var newIndex = address.row * numCols + address.column;
  7212. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  7213. });
  7214. };
  7215. var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  7216. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7217. var onLastRow = oldRow === numRows - 1;
  7218. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  7219. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  7220. return Optional.some({
  7221. row: oldRow,
  7222. column: newColumn
  7223. });
  7224. });
  7225. };
  7226. var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  7227. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7228. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  7229. var onLastRow = newRow === numRows - 1;
  7230. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  7231. var newCol = clamp$1(oldColumn, 0, colsInRow - 1);
  7232. return Optional.some({
  7233. row: newRow,
  7234. column: newCol
  7235. });
  7236. });
  7237. };
  7238. var cycleRight$1 = function (values, index, numRows, numCols) {
  7239. return cycleHorizontal$1(values, index, numRows, numCols, +1);
  7240. };
  7241. var cycleLeft$1 = function (values, index, numRows, numCols) {
  7242. return cycleHorizontal$1(values, index, numRows, numCols, -1);
  7243. };
  7244. var cycleUp$1 = function (values, index, numRows, numCols) {
  7245. return cycleVertical$1(values, index, numRows, numCols, -1);
  7246. };
  7247. var cycleDown$1 = function (values, index, numRows, numCols) {
  7248. return cycleVertical$1(values, index, numRows, numCols, +1);
  7249. };
  7250. var schema$u = [
  7251. required$1('selector'),
  7252. defaulted('execute', defaultExecute),
  7253. onKeyboardHandler('onEscape'),
  7254. defaulted('captureTab', false),
  7255. initSize()
  7256. ];
  7257. var focusIn$3 = function (component, gridConfig, _gridState) {
  7258. descendant(component.element, gridConfig.selector).each(function (first) {
  7259. gridConfig.focusManager.set(component, first);
  7260. });
  7261. };
  7262. var findCurrent$1 = function (component, gridConfig) {
  7263. return gridConfig.focusManager.get(component).bind(function (elem) {
  7264. return closest$1(elem, gridConfig.selector);
  7265. });
  7266. };
  7267. var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  7268. return findCurrent$1(component, gridConfig).bind(function (focused) {
  7269. return gridConfig.execute(component, simulatedEvent, focused);
  7270. });
  7271. };
  7272. var doMove$2 = function (cycle) {
  7273. return function (element, focused, gridConfig, gridState) {
  7274. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  7275. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  7276. });
  7277. };
  7278. };
  7279. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  7280. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  7281. };
  7282. var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  7283. return gridConfig.onEscape(component, simulatedEvent);
  7284. };
  7285. var moveLeft$3 = doMove$2(cycleLeft$1);
  7286. var moveRight$3 = doMove$2(cycleRight$1);
  7287. var moveNorth$1 = doMove$2(cycleUp$1);
  7288. var moveSouth$1 = doMove$2(cycleDown$1);
  7289. var getKeydownRules$4 = constant$1([
  7290. rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
  7291. rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
  7292. rule(inSet(UP), north$1(moveNorth$1)),
  7293. rule(inSet(DOWN), south$1(moveSouth$1)),
  7294. rule(and([
  7295. isShift,
  7296. inSet(TAB)
  7297. ]), handleTab),
  7298. rule(and([
  7299. isNotShift,
  7300. inSet(TAB)
  7301. ]), handleTab),
  7302. rule(inSet(ESCAPE), doEscape$1),
  7303. rule(inSet(SPACE.concat(ENTER)), execute$3)
  7304. ]);
  7305. var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7306. var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  7307. return Optional.some(focusIn$3);
  7308. });
  7309. var horizontal = function (container, selector, current, delta) {
  7310. var isDisabledButton = function (candidate) {
  7311. return name$2(candidate) === 'button' && get$c(candidate, 'disabled') === 'disabled';
  7312. };
  7313. var tryCycle = function (initial, index, candidates) {
  7314. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  7315. if (newIndex === initial) {
  7316. return Optional.none();
  7317. } else {
  7318. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  7319. }
  7320. };
  7321. return locateVisible(container, current, selector).bind(function (identified) {
  7322. var index = identified.index;
  7323. var candidates = identified.candidates;
  7324. return tryCycle(index, index, candidates);
  7325. });
  7326. };
  7327. var schema$t = [
  7328. required$1('selector'),
  7329. defaulted('getInitial', Optional.none),
  7330. defaulted('execute', defaultExecute),
  7331. onKeyboardHandler('onEscape'),
  7332. defaulted('executeOnMove', false),
  7333. defaulted('allowVertical', true)
  7334. ];
  7335. var findCurrent = function (component, flowConfig) {
  7336. return flowConfig.focusManager.get(component).bind(function (elem) {
  7337. return closest$1(elem, flowConfig.selector);
  7338. });
  7339. };
  7340. var execute$2 = function (component, simulatedEvent, flowConfig) {
  7341. return findCurrent(component, flowConfig).bind(function (focused) {
  7342. return flowConfig.execute(component, simulatedEvent, focused);
  7343. });
  7344. };
  7345. var focusIn$2 = function (component, flowConfig, _state) {
  7346. flowConfig.getInitial(component).orThunk(function () {
  7347. return descendant(component.element, flowConfig.selector);
  7348. }).each(function (first) {
  7349. flowConfig.focusManager.set(component, first);
  7350. });
  7351. };
  7352. var moveLeft$2 = function (element, focused, info) {
  7353. return horizontal(element, info.selector, focused, -1);
  7354. };
  7355. var moveRight$2 = function (element, focused, info) {
  7356. return horizontal(element, info.selector, focused, +1);
  7357. };
  7358. var doMove$1 = function (movement) {
  7359. return function (component, simulatedEvent, flowConfig, flowState) {
  7360. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  7361. return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  7362. });
  7363. };
  7364. };
  7365. var doEscape = function (component, simulatedEvent, flowConfig) {
  7366. return flowConfig.onEscape(component, simulatedEvent);
  7367. };
  7368. var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  7369. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  7370. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  7371. return [
  7372. rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
  7373. rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
  7374. rule(inSet(ENTER), execute$2),
  7375. rule(inSet(SPACE), execute$2),
  7376. rule(inSet(ESCAPE), doEscape)
  7377. ];
  7378. };
  7379. var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7380. var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7381. return Optional.some(focusIn$2);
  7382. });
  7383. var toCell = function (matrix, rowIndex, columnIndex) {
  7384. return Optional.from(matrix[rowIndex]).bind(function (row) {
  7385. return Optional.from(row[columnIndex]).map(function (cell) {
  7386. return {
  7387. rowIndex: rowIndex,
  7388. columnIndex: columnIndex,
  7389. cell: cell
  7390. };
  7391. });
  7392. });
  7393. };
  7394. var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7395. var row = matrix[rowIndex];
  7396. var colsInRow = row.length;
  7397. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  7398. return toCell(matrix, rowIndex, newColIndex);
  7399. };
  7400. var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  7401. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  7402. var colsInNextRow = matrix[nextRowIndex].length;
  7403. var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7404. return toCell(matrix, nextRowIndex, nextColIndex);
  7405. };
  7406. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7407. var row = matrix[rowIndex];
  7408. var colsInRow = row.length;
  7409. var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1);
  7410. return toCell(matrix, rowIndex, newColIndex);
  7411. };
  7412. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  7413. var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix.length - 1);
  7414. var colsInNextRow = matrix[nextRowIndex].length;
  7415. var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7416. return toCell(matrix, nextRowIndex, nextColIndex);
  7417. };
  7418. var cycleRight = function (matrix, startRow, startCol) {
  7419. return cycleHorizontal(matrix, startRow, startCol, +1);
  7420. };
  7421. var cycleLeft = function (matrix, startRow, startCol) {
  7422. return cycleHorizontal(matrix, startRow, startCol, -1);
  7423. };
  7424. var cycleUp = function (matrix, startRow, startCol) {
  7425. return cycleVertical(matrix, startCol, startRow, -1);
  7426. };
  7427. var cycleDown = function (matrix, startRow, startCol) {
  7428. return cycleVertical(matrix, startCol, startRow, +1);
  7429. };
  7430. var moveLeft$1 = function (matrix, startRow, startCol) {
  7431. return moveHorizontal(matrix, startRow, startCol, -1);
  7432. };
  7433. var moveRight$1 = function (matrix, startRow, startCol) {
  7434. return moveHorizontal(matrix, startRow, startCol, +1);
  7435. };
  7436. var moveUp$1 = function (matrix, startRow, startCol) {
  7437. return moveVertical(matrix, startCol, startRow, -1);
  7438. };
  7439. var moveDown$1 = function (matrix, startRow, startCol) {
  7440. return moveVertical(matrix, startCol, startRow, +1);
  7441. };
  7442. var schema$s = [
  7443. requiredObjOf('selectors', [
  7444. required$1('row'),
  7445. required$1('cell')
  7446. ]),
  7447. defaulted('cycles', true),
  7448. defaulted('previousSelector', Optional.none),
  7449. defaulted('execute', defaultExecute)
  7450. ];
  7451. var focusIn$1 = function (component, matrixConfig, _state) {
  7452. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  7453. var selectors = matrixConfig.selectors;
  7454. return descendant(component.element, selectors.cell);
  7455. });
  7456. focused.each(function (cell) {
  7457. matrixConfig.focusManager.set(component, cell);
  7458. });
  7459. };
  7460. var execute$1 = function (component, simulatedEvent, matrixConfig) {
  7461. return search(component.element).bind(function (focused) {
  7462. return matrixConfig.execute(component, simulatedEvent, focused);
  7463. });
  7464. };
  7465. var toMatrix = function (rows, matrixConfig) {
  7466. return map$2(rows, function (row) {
  7467. return descendants(row, matrixConfig.selectors.cell);
  7468. });
  7469. };
  7470. var doMove = function (ifCycle, ifMove) {
  7471. return function (element, focused, matrixConfig) {
  7472. var move = matrixConfig.cycles ? ifCycle : ifMove;
  7473. return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  7474. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  7475. return findIndex(cellsInRow, focused).bind(function (colIndex) {
  7476. var allRows = descendants(element, matrixConfig.selectors.row);
  7477. return findIndex(allRows, inRow).bind(function (rowIndex) {
  7478. var matrix = toMatrix(allRows, matrixConfig);
  7479. return move(matrix, rowIndex, colIndex).map(function (next) {
  7480. return next.cell;
  7481. });
  7482. });
  7483. });
  7484. });
  7485. };
  7486. };
  7487. var moveLeft = doMove(cycleLeft, moveLeft$1);
  7488. var moveRight = doMove(cycleRight, moveRight$1);
  7489. var moveNorth = doMove(cycleUp, moveUp$1);
  7490. var moveSouth = doMove(cycleDown, moveDown$1);
  7491. var getKeydownRules$2 = constant$1([
  7492. rule(inSet(LEFT), west$1(moveLeft, moveRight)),
  7493. rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
  7494. rule(inSet(UP), north$1(moveNorth)),
  7495. rule(inSet(DOWN), south$1(moveSouth)),
  7496. rule(inSet(SPACE.concat(ENTER)), execute$1)
  7497. ]);
  7498. var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7499. var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  7500. return Optional.some(focusIn$1);
  7501. });
  7502. var schema$r = [
  7503. required$1('selector'),
  7504. defaulted('execute', defaultExecute),
  7505. defaulted('moveOnTab', false)
  7506. ];
  7507. var execute = function (component, simulatedEvent, menuConfig) {
  7508. return menuConfig.focusManager.get(component).bind(function (focused) {
  7509. return menuConfig.execute(component, simulatedEvent, focused);
  7510. });
  7511. };
  7512. var focusIn = function (component, menuConfig, _state) {
  7513. descendant(component.element, menuConfig.selector).each(function (first) {
  7514. menuConfig.focusManager.set(component, first);
  7515. });
  7516. };
  7517. var moveUp = function (element, focused, info) {
  7518. return horizontal(element, info.selector, focused, -1);
  7519. };
  7520. var moveDown = function (element, focused, info) {
  7521. return horizontal(element, info.selector, focused, +1);
  7522. };
  7523. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7524. return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7525. };
  7526. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7527. return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7528. };
  7529. var getKeydownRules$1 = constant$1([
  7530. rule(inSet(UP), move$1(moveUp)),
  7531. rule(inSet(DOWN), move$1(moveDown)),
  7532. rule(and([
  7533. isShift,
  7534. inSet(TAB)
  7535. ]), fireShiftTab),
  7536. rule(and([
  7537. isNotShift,
  7538. inSet(TAB)
  7539. ]), fireTab),
  7540. rule(inSet(ENTER), execute),
  7541. rule(inSet(SPACE), execute)
  7542. ]);
  7543. var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7544. var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  7545. return Optional.some(focusIn);
  7546. });
  7547. var schema$q = [
  7548. onKeyboardHandler('onSpace'),
  7549. onKeyboardHandler('onEnter'),
  7550. onKeyboardHandler('onShiftEnter'),
  7551. onKeyboardHandler('onLeft'),
  7552. onKeyboardHandler('onRight'),
  7553. onKeyboardHandler('onTab'),
  7554. onKeyboardHandler('onShiftTab'),
  7555. onKeyboardHandler('onUp'),
  7556. onKeyboardHandler('onDown'),
  7557. onKeyboardHandler('onEscape'),
  7558. defaulted('stopSpaceKeyup', false),
  7559. option('focusIn')
  7560. ];
  7561. var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  7562. return [
  7563. rule(inSet(SPACE), specialInfo.onSpace),
  7564. rule(and([
  7565. isNotShift,
  7566. inSet(ENTER)
  7567. ]), specialInfo.onEnter),
  7568. rule(and([
  7569. isShift,
  7570. inSet(ENTER)
  7571. ]), specialInfo.onShiftEnter),
  7572. rule(and([
  7573. isShift,
  7574. inSet(TAB)
  7575. ]), specialInfo.onShiftTab),
  7576. rule(and([
  7577. isNotShift,
  7578. inSet(TAB)
  7579. ]), specialInfo.onTab),
  7580. rule(inSet(UP), specialInfo.onUp),
  7581. rule(inSet(DOWN), specialInfo.onDown),
  7582. rule(inSet(LEFT), specialInfo.onLeft),
  7583. rule(inSet(RIGHT), specialInfo.onRight),
  7584. rule(inSet(SPACE), specialInfo.onSpace),
  7585. rule(inSet(ESCAPE), specialInfo.onEscape)
  7586. ];
  7587. };
  7588. var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  7589. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7590. };
  7591. var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  7592. return specialInfo.focusIn;
  7593. });
  7594. var acyclic = AcyclicType.schema();
  7595. var cyclic = CyclicType.schema();
  7596. var flow = FlowType.schema();
  7597. var flatgrid = FlatgridType.schema();
  7598. var matrix = MatrixType.schema();
  7599. var execution = ExecutionType.schema();
  7600. var menu = MenuType.schema();
  7601. var special = SpecialType.schema();
  7602. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7603. __proto__: null,
  7604. acyclic: acyclic,
  7605. cyclic: cyclic,
  7606. flow: flow,
  7607. flatgrid: flatgrid,
  7608. matrix: matrix,
  7609. execution: execution,
  7610. menu: menu,
  7611. special: special
  7612. });
  7613. var isFlatgridState = function (keyState) {
  7614. return hasNonNullableKey(keyState, 'setGridSize');
  7615. };
  7616. var Keying = createModes({
  7617. branchKey: 'mode',
  7618. branches: KeyboardBranches,
  7619. name: 'keying',
  7620. active: {
  7621. events: function (keyingConfig, keyingState) {
  7622. var handler = keyingConfig.handler;
  7623. return handler.toEvents(keyingConfig, keyingState);
  7624. }
  7625. },
  7626. apis: {
  7627. focusIn: function (component, keyConfig, keyState) {
  7628. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7629. component.getSystem().triggerFocus(component.element, component.element);
  7630. }, function (sendFocusIn) {
  7631. sendFocusIn(component, keyConfig, keyState);
  7632. });
  7633. },
  7634. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7635. if (!isFlatgridState(keyState)) {
  7636. console.error('Layout does not support setGridSize');
  7637. } else {
  7638. keyState.setGridSize(numRows, numColumns);
  7639. }
  7640. }
  7641. },
  7642. state: KeyingState
  7643. });
  7644. var set$2 = function (component, replaceConfig, replaceState, data) {
  7645. preserve$1(function () {
  7646. var newChildren = map$2(data, component.getSystem().build);
  7647. replaceChildren(component, newChildren);
  7648. }, component.element);
  7649. };
  7650. var insert = function (component, replaceConfig, insertion, childSpec) {
  7651. var child = component.getSystem().build(childSpec);
  7652. attachWith(component, child, insertion);
  7653. };
  7654. var append = function (component, replaceConfig, replaceState, appendee) {
  7655. insert(component, replaceConfig, append$2, appendee);
  7656. };
  7657. var prepend = function (component, replaceConfig, replaceState, prependee) {
  7658. insert(component, replaceConfig, prepend$1, prependee);
  7659. };
  7660. var remove = function (component, replaceConfig, replaceState, removee) {
  7661. var children = contents(component);
  7662. var foundChild = find$5(children, function (child) {
  7663. return eq(removee.element, child.element);
  7664. });
  7665. foundChild.each(detach);
  7666. };
  7667. var contents = function (component, _replaceConfig) {
  7668. return component.components();
  7669. };
  7670. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7671. var children = contents(component);
  7672. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  7673. remove(component, replaceConfig, replaceState, replacee);
  7674. replacer.each(function (r) {
  7675. insert(component, replaceConfig, function (p, c) {
  7676. appendAt(p, c, replaceeIndex);
  7677. }, r);
  7678. });
  7679. return replacee;
  7680. });
  7681. };
  7682. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7683. var children = contents(component);
  7684. return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  7685. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7686. });
  7687. };
  7688. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7689. __proto__: null,
  7690. append: append,
  7691. prepend: prepend,
  7692. remove: remove,
  7693. replaceAt: replaceAt,
  7694. replaceBy: replaceBy,
  7695. set: set$2,
  7696. contents: contents
  7697. });
  7698. var Replacing = create$7({
  7699. fields: [],
  7700. name: 'replacing',
  7701. apis: ReplaceApis
  7702. });
  7703. var events$d = function (name, eventHandlers) {
  7704. var events = derive$2(eventHandlers);
  7705. return create$7({
  7706. fields: [required$1('enabled')],
  7707. name: name,
  7708. active: { events: constant$1(events) }
  7709. });
  7710. };
  7711. var config = function (name, eventHandlers) {
  7712. var me = events$d(name, eventHandlers);
  7713. return {
  7714. key: name,
  7715. value: {
  7716. config: {},
  7717. me: me,
  7718. configAsRaw: constant$1({}),
  7719. initialConfig: {},
  7720. state: NoState
  7721. }
  7722. };
  7723. };
  7724. var focus$2 = function (component, focusConfig) {
  7725. if (!focusConfig.ignore) {
  7726. focus$3(component.element);
  7727. focusConfig.onFocus(component);
  7728. }
  7729. };
  7730. var blur = function (component, focusConfig) {
  7731. if (!focusConfig.ignore) {
  7732. blur$1(component.element);
  7733. }
  7734. };
  7735. var isFocused = function (component) {
  7736. return hasFocus(component.element);
  7737. };
  7738. var FocusApis = /*#__PURE__*/Object.freeze({
  7739. __proto__: null,
  7740. focus: focus$2,
  7741. blur: blur,
  7742. isFocused: isFocused
  7743. });
  7744. var exhibit$4 = function (base, focusConfig) {
  7745. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7746. return nu$7(mod);
  7747. };
  7748. var events$c = function (focusConfig) {
  7749. return derive$2([run$1(focus$4(), function (component, simulatedEvent) {
  7750. focus$2(component, focusConfig);
  7751. simulatedEvent.stop();
  7752. })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function (_, simulatedEvent) {
  7753. simulatedEvent.event.prevent();
  7754. })] : []));
  7755. };
  7756. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7757. __proto__: null,
  7758. exhibit: exhibit$4,
  7759. events: events$c
  7760. });
  7761. var FocusSchema = [
  7762. onHandler('onFocus'),
  7763. defaulted('stopMousedown', false),
  7764. defaulted('ignore', false)
  7765. ];
  7766. var Focusing = create$7({
  7767. fields: FocusSchema,
  7768. name: 'focusing',
  7769. active: ActiveFocus,
  7770. apis: FocusApis
  7771. });
  7772. var SetupBehaviourCellState = function (initialState) {
  7773. var init = function () {
  7774. var cell = Cell(initialState);
  7775. var get = function () {
  7776. return cell.get();
  7777. };
  7778. var set = function (newState) {
  7779. return cell.set(newState);
  7780. };
  7781. var clear = function () {
  7782. return cell.set(initialState);
  7783. };
  7784. var readState = function () {
  7785. return cell.get();
  7786. };
  7787. return {
  7788. get: get,
  7789. set: set,
  7790. clear: clear,
  7791. readState: readState
  7792. };
  7793. };
  7794. return { init: init };
  7795. };
  7796. var updateAriaState = function (component, toggleConfig, toggleState) {
  7797. var ariaInfo = toggleConfig.aria;
  7798. ariaInfo.update(component, ariaInfo, toggleState.get());
  7799. };
  7800. var updateClass = function (component, toggleConfig, toggleState) {
  7801. toggleConfig.toggleClass.each(function (toggleClass) {
  7802. if (toggleState.get()) {
  7803. add$2(component.element, toggleClass);
  7804. } else {
  7805. remove$3(component.element, toggleClass);
  7806. }
  7807. });
  7808. };
  7809. var toggle$2 = function (component, toggleConfig, toggleState) {
  7810. set$1(component, toggleConfig, toggleState, !toggleState.get());
  7811. };
  7812. var on = function (component, toggleConfig, toggleState) {
  7813. toggleState.set(true);
  7814. updateClass(component, toggleConfig, toggleState);
  7815. updateAriaState(component, toggleConfig, toggleState);
  7816. };
  7817. var off = function (component, toggleConfig, toggleState) {
  7818. toggleState.set(false);
  7819. updateClass(component, toggleConfig, toggleState);
  7820. updateAriaState(component, toggleConfig, toggleState);
  7821. };
  7822. var set$1 = function (component, toggleConfig, toggleState, state) {
  7823. var action = state ? on : off;
  7824. action(component, toggleConfig, toggleState);
  7825. };
  7826. var isOn = function (component, toggleConfig, toggleState) {
  7827. return toggleState.get();
  7828. };
  7829. var onLoad = function (component, toggleConfig, toggleState) {
  7830. set$1(component, toggleConfig, toggleState, toggleConfig.selected);
  7831. };
  7832. var ToggleApis = /*#__PURE__*/Object.freeze({
  7833. __proto__: null,
  7834. onLoad: onLoad,
  7835. toggle: toggle$2,
  7836. isOn: isOn,
  7837. on: on,
  7838. off: off,
  7839. set: set$1
  7840. });
  7841. var exhibit$3 = function () {
  7842. return nu$7({});
  7843. };
  7844. var events$b = function (toggleConfig, toggleState) {
  7845. var execute = executeEvent(toggleConfig, toggleState, toggle$2);
  7846. var load = loadEvent(toggleConfig, toggleState, onLoad);
  7847. return derive$2(flatten([
  7848. toggleConfig.toggleOnExecute ? [execute] : [],
  7849. [load]
  7850. ]));
  7851. };
  7852. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7853. __proto__: null,
  7854. exhibit: exhibit$3,
  7855. events: events$b
  7856. });
  7857. var updatePressed = function (component, ariaInfo, status) {
  7858. set$7(component.element, 'aria-pressed', status);
  7859. if (ariaInfo.syncWithExpanded) {
  7860. updateExpanded(component, ariaInfo, status);
  7861. }
  7862. };
  7863. var updateSelected = function (component, ariaInfo, status) {
  7864. set$7(component.element, 'aria-selected', status);
  7865. };
  7866. var updateChecked = function (component, ariaInfo, status) {
  7867. set$7(component.element, 'aria-checked', status);
  7868. };
  7869. var updateExpanded = function (component, ariaInfo, status) {
  7870. set$7(component.element, 'aria-expanded', status);
  7871. };
  7872. var ToggleSchema = [
  7873. defaulted('selected', false),
  7874. option('toggleClass'),
  7875. defaulted('toggleOnExecute', true),
  7876. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7877. pressed: [
  7878. defaulted('syncWithExpanded', false),
  7879. output$1('update', updatePressed)
  7880. ],
  7881. checked: [output$1('update', updateChecked)],
  7882. expanded: [output$1('update', updateExpanded)],
  7883. selected: [output$1('update', updateSelected)],
  7884. none: [output$1('update', noop)]
  7885. }))
  7886. ];
  7887. var Toggling = create$7({
  7888. fields: ToggleSchema,
  7889. name: 'toggling',
  7890. active: ActiveToggle,
  7891. apis: ToggleApis,
  7892. state: SetupBehaviourCellState(false)
  7893. });
  7894. var pointerEvents = function () {
  7895. var onClick = function (component, simulatedEvent) {
  7896. simulatedEvent.stop();
  7897. emitExecute(component);
  7898. };
  7899. return [
  7900. run$1(click(), onClick),
  7901. run$1(tap(), onClick),
  7902. cutter(touchstart()),
  7903. cutter(mousedown())
  7904. ];
  7905. };
  7906. var events$a = function (optAction) {
  7907. var executeHandler = function (action) {
  7908. return runOnExecute$1(function (component, simulatedEvent) {
  7909. action(component);
  7910. simulatedEvent.stop();
  7911. });
  7912. };
  7913. return derive$2(flatten([
  7914. optAction.map(executeHandler).toArray(),
  7915. pointerEvents()
  7916. ]));
  7917. };
  7918. var hoverEvent = 'alloy.item-hover';
  7919. var focusEvent = 'alloy.item-focus';
  7920. var onHover = function (item) {
  7921. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7922. if (!Focusing.isFocused(item)) {
  7923. Focusing.focus(item);
  7924. }
  7925. emitWith(item, hoverEvent, { item: item });
  7926. }
  7927. };
  7928. var onFocus$1 = function (item) {
  7929. emitWith(item, focusEvent, { item: item });
  7930. };
  7931. var hover = constant$1(hoverEvent);
  7932. var focus$1 = constant$1(focusEvent);
  7933. var builder$2 = function (detail) {
  7934. return {
  7935. dom: detail.dom,
  7936. domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes), { 'aria-haspopup': detail.hasSubmenu }), detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  7937. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7938. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7939. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7940. }),
  7941. Focusing.config({
  7942. ignore: detail.ignoreFocus,
  7943. stopMousedown: detail.ignoreFocus,
  7944. onFocus: function (component) {
  7945. onFocus$1(component);
  7946. }
  7947. }),
  7948. Keying.config({ mode: 'execution' }),
  7949. Representing.config({
  7950. store: {
  7951. mode: 'memory',
  7952. initialValue: detail.data
  7953. }
  7954. }),
  7955. config('item-type-events', __spreadArray(__spreadArray([], pointerEvents()), [
  7956. run$1(mouseover(), onHover),
  7957. run$1(focusItem(), Focusing.focus)
  7958. ]))
  7959. ]),
  7960. components: detail.components,
  7961. eventOrder: detail.eventOrder
  7962. };
  7963. };
  7964. var schema$p = [
  7965. required$1('data'),
  7966. required$1('components'),
  7967. required$1('dom'),
  7968. defaulted('hasSubmenu', false),
  7969. option('toggling'),
  7970. SketchBehaviours.field('itemBehaviours', [
  7971. Toggling,
  7972. Focusing,
  7973. Keying,
  7974. Representing
  7975. ]),
  7976. defaulted('ignoreFocus', false),
  7977. defaulted('domModification', {}),
  7978. output$1('builder', builder$2),
  7979. defaulted('eventOrder', {})
  7980. ];
  7981. var builder$1 = function (detail) {
  7982. return {
  7983. dom: detail.dom,
  7984. components: detail.components,
  7985. events: derive$2([stopper(focusItem())])
  7986. };
  7987. };
  7988. var schema$o = [
  7989. required$1('dom'),
  7990. required$1('components'),
  7991. output$1('builder', builder$1)
  7992. ];
  7993. var owner$2 = constant$1('item-widget');
  7994. var parts$h = constant$1([required({
  7995. name: 'widget',
  7996. overrides: function (detail) {
  7997. return {
  7998. behaviours: derive$1([Representing.config({
  7999. store: {
  8000. mode: 'manual',
  8001. getValue: function (_component) {
  8002. return detail.data;
  8003. },
  8004. setValue: noop
  8005. }
  8006. })])
  8007. };
  8008. }
  8009. })]);
  8010. var builder = function (detail) {
  8011. var subs = substitutes(owner$2(), detail, parts$h());
  8012. var components = components$1(owner$2(), detail, subs.internals());
  8013. var focusWidget = function (component) {
  8014. return getPart(component, detail, 'widget').map(function (widget) {
  8015. Keying.focusIn(widget);
  8016. return widget;
  8017. });
  8018. };
  8019. var onHorizontalArrow = function (component, simulatedEvent) {
  8020. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  8021. if (detail.autofocus) {
  8022. simulatedEvent.setSource(component.element);
  8023. return Optional.none();
  8024. } else {
  8025. return Optional.none();
  8026. }
  8027. }();
  8028. };
  8029. return {
  8030. dom: detail.dom,
  8031. components: components,
  8032. domModification: detail.domModification,
  8033. events: derive$2([
  8034. runOnExecute$1(function (component, simulatedEvent) {
  8035. focusWidget(component).each(function (_widget) {
  8036. simulatedEvent.stop();
  8037. });
  8038. }),
  8039. run$1(mouseover(), onHover),
  8040. run$1(focusItem(), function (component, _simulatedEvent) {
  8041. if (detail.autofocus) {
  8042. focusWidget(component);
  8043. } else {
  8044. Focusing.focus(component);
  8045. }
  8046. })
  8047. ]),
  8048. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  8049. Representing.config({
  8050. store: {
  8051. mode: 'memory',
  8052. initialValue: detail.data
  8053. }
  8054. }),
  8055. Focusing.config({
  8056. ignore: detail.ignoreFocus,
  8057. onFocus: function (component) {
  8058. onFocus$1(component);
  8059. }
  8060. }),
  8061. Keying.config({
  8062. mode: 'special',
  8063. focusIn: detail.autofocus ? function (component) {
  8064. focusWidget(component);
  8065. } : revoke(),
  8066. onLeft: onHorizontalArrow,
  8067. onRight: onHorizontalArrow,
  8068. onEscape: function (component, simulatedEvent) {
  8069. if (!Focusing.isFocused(component) && !detail.autofocus) {
  8070. Focusing.focus(component);
  8071. return Optional.some(true);
  8072. } else if (detail.autofocus) {
  8073. simulatedEvent.setSource(component.element);
  8074. return Optional.none();
  8075. } else {
  8076. return Optional.none();
  8077. }
  8078. }
  8079. })
  8080. ])
  8081. };
  8082. };
  8083. var schema$n = [
  8084. required$1('uid'),
  8085. required$1('data'),
  8086. required$1('components'),
  8087. required$1('dom'),
  8088. defaulted('autofocus', false),
  8089. defaulted('ignoreFocus', false),
  8090. SketchBehaviours.field('widgetBehaviours', [
  8091. Representing,
  8092. Focusing,
  8093. Keying
  8094. ]),
  8095. defaulted('domModification', {}),
  8096. defaultUidsSchema(parts$h()),
  8097. output$1('builder', builder)
  8098. ];
  8099. var itemSchema$2 = choose$1('type', {
  8100. widget: schema$n,
  8101. item: schema$p,
  8102. separator: schema$o
  8103. });
  8104. var configureGrid = function (detail, movementInfo) {
  8105. return {
  8106. mode: 'flatgrid',
  8107. selector: '.' + detail.markers.item,
  8108. initSize: {
  8109. numColumns: movementInfo.initSize.numColumns,
  8110. numRows: movementInfo.initSize.numRows
  8111. },
  8112. focusManager: detail.focusManager
  8113. };
  8114. };
  8115. var configureMatrix = function (detail, movementInfo) {
  8116. return {
  8117. mode: 'matrix',
  8118. selectors: {
  8119. row: movementInfo.rowSelector,
  8120. cell: '.' + detail.markers.item
  8121. },
  8122. focusManager: detail.focusManager
  8123. };
  8124. };
  8125. var configureMenu = function (detail, movementInfo) {
  8126. return {
  8127. mode: 'menu',
  8128. selector: '.' + detail.markers.item,
  8129. moveOnTab: movementInfo.moveOnTab,
  8130. focusManager: detail.focusManager
  8131. };
  8132. };
  8133. var parts$g = constant$1([group({
  8134. factory: {
  8135. sketch: function (spec) {
  8136. var itemInfo = asRawOrDie$1('menu.spec item', itemSchema$2, spec);
  8137. return itemInfo.builder(itemInfo);
  8138. }
  8139. },
  8140. name: 'items',
  8141. unit: 'item',
  8142. defaults: function (detail, u) {
  8143. return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$5('item') });
  8144. },
  8145. overrides: function (detail, u) {
  8146. return {
  8147. type: u.type,
  8148. ignoreFocus: detail.fakeFocus,
  8149. domModification: { classes: [detail.markers.item] }
  8150. };
  8151. }
  8152. })]);
  8153. var schema$m = constant$1([
  8154. required$1('value'),
  8155. required$1('items'),
  8156. required$1('dom'),
  8157. required$1('components'),
  8158. defaulted('eventOrder', {}),
  8159. field('menuBehaviours', [
  8160. Highlighting,
  8161. Representing,
  8162. Composing,
  8163. Keying
  8164. ]),
  8165. defaultedOf('movement', {
  8166. mode: 'menu',
  8167. moveOnTab: true
  8168. }, choose$1('mode', {
  8169. grid: [
  8170. initSize(),
  8171. output$1('config', configureGrid)
  8172. ],
  8173. matrix: [
  8174. output$1('config', configureMatrix),
  8175. required$1('rowSelector')
  8176. ],
  8177. menu: [
  8178. defaulted('moveOnTab', true),
  8179. output$1('config', configureMenu)
  8180. ]
  8181. })),
  8182. itemMarkers(),
  8183. defaulted('fakeFocus', false),
  8184. defaulted('focusManager', dom$2()),
  8185. onHandler('onHighlight')
  8186. ]);
  8187. var focus = constant$1('alloy.menu-focus');
  8188. var make$7 = function (detail, components, _spec, _externals) {
  8189. return {
  8190. uid: detail.uid,
  8191. dom: detail.dom,
  8192. markers: detail.markers,
  8193. behaviours: augment(detail.menuBehaviours, [
  8194. Highlighting.config({
  8195. highlightClass: detail.markers.selectedItem,
  8196. itemClass: detail.markers.item,
  8197. onHighlight: detail.onHighlight
  8198. }),
  8199. Representing.config({
  8200. store: {
  8201. mode: 'memory',
  8202. initialValue: detail.value
  8203. }
  8204. }),
  8205. Composing.config({ find: Optional.some }),
  8206. Keying.config(detail.movement.config(detail, detail.movement))
  8207. ]),
  8208. events: derive$2([
  8209. run$1(focus$1(), function (menu, simulatedEvent) {
  8210. var event = simulatedEvent.event;
  8211. menu.getSystem().getByDom(event.target).each(function (item) {
  8212. Highlighting.highlight(menu, item);
  8213. simulatedEvent.stop();
  8214. emitWith(menu, focus(), {
  8215. menu: menu,
  8216. item: item
  8217. });
  8218. });
  8219. }),
  8220. run$1(hover(), function (menu, simulatedEvent) {
  8221. var item = simulatedEvent.event.item;
  8222. Highlighting.highlight(menu, item);
  8223. })
  8224. ]),
  8225. components: components,
  8226. eventOrder: detail.eventOrder,
  8227. domModification: { attributes: { role: 'menu' } }
  8228. };
  8229. };
  8230. var Menu = composite({
  8231. name: 'Menu',
  8232. configFields: schema$m(),
  8233. partFields: parts$g(),
  8234. factory: make$7
  8235. });
  8236. var transpose$1 = function (obj) {
  8237. return tupleMap(obj, function (v, k) {
  8238. return {
  8239. k: v,
  8240. v: k
  8241. };
  8242. });
  8243. };
  8244. var trace = function (items, byItem, byMenu, finish) {
  8245. return get$e(byMenu, finish).bind(function (triggerItem) {
  8246. return get$e(items, triggerItem).bind(function (triggerMenu) {
  8247. var rest = trace(items, byItem, byMenu, triggerMenu);
  8248. return Optional.some([triggerMenu].concat(rest));
  8249. });
  8250. }).getOr([]);
  8251. };
  8252. var generate$2 = function (menus, expansions) {
  8253. var items = {};
  8254. each(menus, function (menuItems, menu) {
  8255. each$1(menuItems, function (item) {
  8256. items[item] = menu;
  8257. });
  8258. });
  8259. var byItem = expansions;
  8260. var byMenu = transpose$1(expansions);
  8261. var menuPaths = map(byMenu, function (_triggerItem, submenu) {
  8262. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8263. });
  8264. return map(items, function (menu) {
  8265. return get$e(menuPaths, menu).getOr([menu]);
  8266. });
  8267. };
  8268. var init$c = function () {
  8269. var expansions = Cell({});
  8270. var menus = Cell({});
  8271. var paths = Cell({});
  8272. var primary = value$1();
  8273. var directory = Cell({});
  8274. var clear = function () {
  8275. expansions.set({});
  8276. menus.set({});
  8277. paths.set({});
  8278. primary.clear();
  8279. };
  8280. var isClear = function () {
  8281. return primary.get().isNone();
  8282. };
  8283. var setMenuBuilt = function (menuName, built) {
  8284. var _a;
  8285. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8286. type: 'prepared',
  8287. menu: built
  8288. }, _a)));
  8289. };
  8290. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8291. primary.set(sPrimary);
  8292. expansions.set(sExpansions);
  8293. menus.set(sMenus);
  8294. directory.set(dir);
  8295. var sPaths = generate$2(dir, sExpansions);
  8296. paths.set(sPaths);
  8297. };
  8298. var getTriggeringItem = function (menuValue) {
  8299. return find$4(expansions.get(), function (v, _k) {
  8300. return v === menuValue;
  8301. });
  8302. };
  8303. var getTriggerData = function (menuValue, getItemByValue, path) {
  8304. return getPreparedMenu(menuValue).bind(function (menu) {
  8305. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8306. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8307. return {
  8308. triggeredMenu: menu,
  8309. triggeringItem: triggeredItem,
  8310. triggeringPath: path
  8311. };
  8312. });
  8313. });
  8314. });
  8315. };
  8316. var getTriggeringPath = function (itemValue, getItemByValue) {
  8317. var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8318. return getPreparedMenu(menuValue).isSome();
  8319. });
  8320. return get$e(paths.get(), itemValue).bind(function (path) {
  8321. var revPath = reverse(extraPath.concat(path));
  8322. var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8323. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8324. return is(primary.get(), menuValue) ? [] : [Optional.none()];
  8325. }, function (data) {
  8326. return [Optional.some(data)];
  8327. });
  8328. });
  8329. return sequence(triggers);
  8330. });
  8331. };
  8332. var expand = function (itemValue) {
  8333. return get$e(expansions.get(), itemValue).map(function (menu) {
  8334. var current = get$e(paths.get(), itemValue).getOr([]);
  8335. return [menu].concat(current);
  8336. });
  8337. };
  8338. var collapse = function (itemValue) {
  8339. return get$e(paths.get(), itemValue).bind(function (path) {
  8340. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8341. });
  8342. };
  8343. var refresh = function (itemValue) {
  8344. return get$e(paths.get(), itemValue);
  8345. };
  8346. var getPreparedMenu = function (menuValue) {
  8347. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8348. };
  8349. var lookupMenu = function (menuValue) {
  8350. return get$e(menus.get(), menuValue);
  8351. };
  8352. var lookupItem = function (itemValue) {
  8353. return get$e(expansions.get(), itemValue);
  8354. };
  8355. var otherMenus = function (path) {
  8356. var menuValues = directory.get();
  8357. return difference(keys(menuValues), path);
  8358. };
  8359. var getPrimary = function () {
  8360. return primary.get().bind(getPreparedMenu);
  8361. };
  8362. var getMenus = function () {
  8363. return menus.get();
  8364. };
  8365. return {
  8366. setMenuBuilt: setMenuBuilt,
  8367. setContents: setContents,
  8368. expand: expand,
  8369. refresh: refresh,
  8370. collapse: collapse,
  8371. lookupMenu: lookupMenu,
  8372. lookupItem: lookupItem,
  8373. otherMenus: otherMenus,
  8374. getPrimary: getPrimary,
  8375. getMenus: getMenus,
  8376. clear: clear,
  8377. isClear: isClear,
  8378. getTriggeringPath: getTriggeringPath
  8379. };
  8380. };
  8381. var extractPreparedMenu = function (prep) {
  8382. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8383. };
  8384. var LayeredState = {
  8385. init: init$c,
  8386. extractPreparedMenu: extractPreparedMenu
  8387. };
  8388. var make$6 = function (detail, _rawUiSpec) {
  8389. var submenuParentItems = value$1();
  8390. var buildMenus = function (container, primaryName, menus) {
  8391. return map(menus, function (spec, name) {
  8392. var makeSketch = function () {
  8393. return Menu.sketch(__assign(__assign({}, spec), {
  8394. value: name,
  8395. markers: detail.markers,
  8396. fakeFocus: detail.fakeFocus,
  8397. onHighlight: detail.onHighlight,
  8398. focusManager: detail.fakeFocus ? highlights() : dom$2()
  8399. }));
  8400. };
  8401. return name === primaryName ? {
  8402. type: 'prepared',
  8403. menu: container.getSystem().build(makeSketch())
  8404. } : {
  8405. type: 'notbuilt',
  8406. nbMenu: makeSketch
  8407. };
  8408. });
  8409. };
  8410. var layeredState = LayeredState.init();
  8411. var setup = function (container) {
  8412. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8413. var directory = toDirectory();
  8414. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8415. return layeredState.getPrimary();
  8416. };
  8417. var getItemValue = function (item) {
  8418. return Representing.getValue(item).value;
  8419. };
  8420. var getItemByValue = function (_container, menus, itemValue) {
  8421. return findMap(menus, function (menu) {
  8422. if (!menu.getSystem().isConnected()) {
  8423. return Optional.none();
  8424. }
  8425. var candidates = Highlighting.getCandidates(menu);
  8426. return find$5(candidates, function (c) {
  8427. return getItemValue(c) === itemValue;
  8428. });
  8429. });
  8430. };
  8431. var toDirectory = function (_container) {
  8432. return map(detail.data.menus, function (data, _menuName) {
  8433. return bind$3(data.items, function (item) {
  8434. return item.type === 'separator' ? [] : [item.data.value];
  8435. });
  8436. });
  8437. };
  8438. var setActiveMenu = function (container, menu) {
  8439. Highlighting.highlight(container, menu);
  8440. Highlighting.getHighlighted(menu).orThunk(function () {
  8441. return Highlighting.getFirst(menu);
  8442. }).each(function (item) {
  8443. dispatch(container, item.element, focusItem());
  8444. });
  8445. };
  8446. var getMenus = function (state, menuValues) {
  8447. return cat(map$2(menuValues, function (mv) {
  8448. return state.lookupMenu(mv).bind(function (prep) {
  8449. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8450. });
  8451. }));
  8452. };
  8453. var closeOthers = function (container, state, path) {
  8454. var others = getMenus(state, state.otherMenus(path));
  8455. each$1(others, function (o) {
  8456. remove$2(o.element, [detail.markers.backgroundMenu]);
  8457. if (!detail.stayInDom) {
  8458. Replacing.remove(container, o);
  8459. }
  8460. });
  8461. };
  8462. var getSubmenuParents = function (container) {
  8463. return submenuParentItems.get().getOrThunk(function () {
  8464. var r = {};
  8465. var items = descendants(container.element, '.' + detail.markers.item);
  8466. var parentItems = filter$2(items, function (i) {
  8467. return get$c(i, 'aria-haspopup') === 'true';
  8468. });
  8469. each$1(parentItems, function (i) {
  8470. container.getSystem().getByDom(i).each(function (itemComp) {
  8471. var key = getItemValue(itemComp);
  8472. r[key] = itemComp;
  8473. });
  8474. });
  8475. submenuParentItems.set(r);
  8476. return r;
  8477. });
  8478. };
  8479. var updateAriaExpansions = function (container, path) {
  8480. var parentItems = getSubmenuParents(container);
  8481. each(parentItems, function (v, k) {
  8482. var expanded = contains$2(path, k);
  8483. set$7(v.element, 'aria-expanded', expanded);
  8484. });
  8485. };
  8486. var updateMenuPath = function (container, state, path) {
  8487. return Optional.from(path[0]).bind(function (latestMenuName) {
  8488. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8489. if (menuPrep.type === 'notbuilt') {
  8490. return Optional.none();
  8491. } else {
  8492. var activeMenu = menuPrep.menu;
  8493. var rest = getMenus(state, path.slice(1));
  8494. each$1(rest, function (r) {
  8495. add$2(r.element, detail.markers.backgroundMenu);
  8496. });
  8497. if (!inBody(activeMenu.element)) {
  8498. Replacing.append(container, premade(activeMenu));
  8499. }
  8500. remove$2(activeMenu.element, [detail.markers.backgroundMenu]);
  8501. setActiveMenu(container, activeMenu);
  8502. closeOthers(container, state, path);
  8503. return Optional.some(activeMenu);
  8504. }
  8505. });
  8506. });
  8507. };
  8508. var ExpandHighlightDecision;
  8509. (function (ExpandHighlightDecision) {
  8510. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8511. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8512. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8513. var buildIfRequired = function (container, menuName, menuPrep) {
  8514. if (menuPrep.type === 'notbuilt') {
  8515. var menu = container.getSystem().build(menuPrep.nbMenu());
  8516. layeredState.setMenuBuilt(menuName, menu);
  8517. return menu;
  8518. } else {
  8519. return menuPrep.menu;
  8520. }
  8521. };
  8522. var expandRight = function (container, item, decision) {
  8523. if (decision === void 0) {
  8524. decision = ExpandHighlightDecision.HighlightSubmenu;
  8525. }
  8526. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8527. return Optional.some(item);
  8528. } else {
  8529. var value = getItemValue(item);
  8530. return layeredState.expand(value).bind(function (path) {
  8531. updateAriaExpansions(container, path);
  8532. return Optional.from(path[0]).bind(function (menuName) {
  8533. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8534. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8535. if (!inBody(activeMenu.element)) {
  8536. Replacing.append(container, premade(activeMenu));
  8537. }
  8538. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8539. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8540. Highlighting.highlightFirst(activeMenu);
  8541. return updateMenuPath(container, layeredState, path);
  8542. } else {
  8543. Highlighting.dehighlightAll(activeMenu);
  8544. return Optional.some(item);
  8545. }
  8546. });
  8547. });
  8548. });
  8549. }
  8550. };
  8551. var collapseLeft = function (container, item) {
  8552. var value = getItemValue(item);
  8553. return layeredState.collapse(value).bind(function (path) {
  8554. updateAriaExpansions(container, path);
  8555. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8556. detail.onCollapseMenu(container, item, activeMenu);
  8557. return activeMenu;
  8558. });
  8559. });
  8560. };
  8561. var updateView = function (container, item) {
  8562. var value = getItemValue(item);
  8563. return layeredState.refresh(value).bind(function (path) {
  8564. updateAriaExpansions(container, path);
  8565. return updateMenuPath(container, layeredState, path);
  8566. });
  8567. };
  8568. var onRight = function (container, item) {
  8569. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8570. };
  8571. var onLeft = function (container, item) {
  8572. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8573. };
  8574. var onEscape = function (container, item) {
  8575. return collapseLeft(container, item).orThunk(function () {
  8576. return detail.onEscape(container, item).map(function () {
  8577. return container;
  8578. });
  8579. });
  8580. };
  8581. var keyOnItem = function (f) {
  8582. return function (container, simulatedEvent) {
  8583. return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8584. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8585. return f(container, item).map(always);
  8586. });
  8587. });
  8588. };
  8589. };
  8590. var events = derive$2([
  8591. run$1(focus(), function (sandbox, simulatedEvent) {
  8592. var item = simulatedEvent.event.item;
  8593. layeredState.lookupItem(getItemValue(item)).each(function () {
  8594. var menu = simulatedEvent.event.menu;
  8595. Highlighting.highlight(sandbox, menu);
  8596. var value = getItemValue(simulatedEvent.event.item);
  8597. layeredState.refresh(value).each(function (path) {
  8598. return closeOthers(sandbox, layeredState, path);
  8599. });
  8600. });
  8601. }),
  8602. runOnExecute$1(function (component, simulatedEvent) {
  8603. var target = simulatedEvent.event.target;
  8604. component.getSystem().getByDom(target).each(function (item) {
  8605. var itemValue = getItemValue(item);
  8606. if (itemValue.indexOf('collapse-item') === 0) {
  8607. collapseLeft(component, item);
  8608. }
  8609. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8610. detail.onExecute(component, item);
  8611. }, noop);
  8612. });
  8613. }),
  8614. runOnAttached(function (container, _simulatedEvent) {
  8615. setup(container).each(function (primary) {
  8616. Replacing.append(container, premade(primary));
  8617. detail.onOpenMenu(container, primary);
  8618. if (detail.highlightImmediately) {
  8619. setActiveMenu(container, primary);
  8620. }
  8621. });
  8622. })
  8623. ].concat(detail.navigateOnHover ? [run$1(hover(), function (sandbox, simulatedEvent) {
  8624. var item = simulatedEvent.event.item;
  8625. updateView(sandbox, item);
  8626. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8627. detail.onHover(sandbox, item);
  8628. })] : []));
  8629. var getActiveItem = function (container) {
  8630. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8631. };
  8632. var collapseMenuApi = function (container) {
  8633. getActiveItem(container).each(function (currentItem) {
  8634. collapseLeft(container, currentItem);
  8635. });
  8636. };
  8637. var highlightPrimary = function (container) {
  8638. layeredState.getPrimary().each(function (primary) {
  8639. setActiveMenu(container, primary);
  8640. });
  8641. };
  8642. var extractMenuFromContainer = function (container) {
  8643. return Optional.from(container.components()[0]).filter(function (comp) {
  8644. return get$c(comp.element, 'role') === 'menu';
  8645. });
  8646. };
  8647. var repositionMenus = function (container) {
  8648. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8649. return getActiveItem(container).bind(function (currentItem) {
  8650. var itemValue = getItemValue(currentItem);
  8651. var allMenus = values(layeredState.getMenus());
  8652. var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8653. return layeredState.getTriggeringPath(itemValue, function (v) {
  8654. return getItemByValue(container, preparedMenus, v);
  8655. });
  8656. }).map(function (triggeringPath) {
  8657. return {
  8658. primary: primary,
  8659. triggeringPath: triggeringPath
  8660. };
  8661. });
  8662. });
  8663. maybeActivePrimary.fold(function () {
  8664. extractMenuFromContainer(container).each(function (primaryMenu) {
  8665. detail.onRepositionMenu(container, primaryMenu, []);
  8666. });
  8667. }, function (_a) {
  8668. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8669. detail.onRepositionMenu(container, primary, triggeringPath);
  8670. });
  8671. };
  8672. var apis = {
  8673. collapseMenu: collapseMenuApi,
  8674. highlightPrimary: highlightPrimary,
  8675. repositionMenus: repositionMenus
  8676. };
  8677. return {
  8678. uid: detail.uid,
  8679. dom: detail.dom,
  8680. markers: detail.markers,
  8681. behaviours: augment(detail.tmenuBehaviours, [
  8682. Keying.config({
  8683. mode: 'special',
  8684. onRight: keyOnItem(onRight),
  8685. onLeft: keyOnItem(onLeft),
  8686. onEscape: keyOnItem(onEscape),
  8687. focusIn: function (container, _keyInfo) {
  8688. layeredState.getPrimary().each(function (primary) {
  8689. dispatch(container, primary.element, focusItem());
  8690. });
  8691. }
  8692. }),
  8693. Highlighting.config({
  8694. highlightClass: detail.markers.selectedMenu,
  8695. itemClass: detail.markers.menu
  8696. }),
  8697. Composing.config({
  8698. find: function (container) {
  8699. return Highlighting.getHighlighted(container);
  8700. }
  8701. }),
  8702. Replacing.config({})
  8703. ]),
  8704. eventOrder: detail.eventOrder,
  8705. apis: apis,
  8706. events: events
  8707. };
  8708. };
  8709. var collapseItem$1 = constant$1('collapse-item');
  8710. var tieredData = function (primary, menus, expansions) {
  8711. return {
  8712. primary: primary,
  8713. menus: menus,
  8714. expansions: expansions
  8715. };
  8716. };
  8717. var singleData = function (name, menu) {
  8718. return {
  8719. primary: name,
  8720. menus: wrap$1(name, menu),
  8721. expansions: {}
  8722. };
  8723. };
  8724. var collapseItem = function (text) {
  8725. return {
  8726. value: generate$6(collapseItem$1()),
  8727. meta: { text: text }
  8728. };
  8729. };
  8730. var tieredMenu = single({
  8731. name: 'TieredMenu',
  8732. configFields: [
  8733. onStrictKeyboardHandler('onExecute'),
  8734. onStrictKeyboardHandler('onEscape'),
  8735. onStrictHandler('onOpenMenu'),
  8736. onStrictHandler('onOpenSubmenu'),
  8737. onHandler('onRepositionMenu'),
  8738. onHandler('onCollapseMenu'),
  8739. defaulted('highlightImmediately', true),
  8740. requiredObjOf('data', [
  8741. required$1('primary'),
  8742. required$1('menus'),
  8743. required$1('expansions')
  8744. ]),
  8745. defaulted('fakeFocus', false),
  8746. onHandler('onHighlight'),
  8747. onHandler('onHover'),
  8748. tieredMenuMarkers(),
  8749. required$1('dom'),
  8750. defaulted('navigateOnHover', true),
  8751. defaulted('stayInDom', false),
  8752. field('tmenuBehaviours', [
  8753. Keying,
  8754. Highlighting,
  8755. Composing,
  8756. Replacing
  8757. ]),
  8758. defaulted('eventOrder', {})
  8759. ],
  8760. apis: {
  8761. collapseMenu: function (apis, tmenu) {
  8762. apis.collapseMenu(tmenu);
  8763. },
  8764. highlightPrimary: function (apis, tmenu) {
  8765. apis.highlightPrimary(tmenu);
  8766. },
  8767. repositionMenus: function (apis, tmenu) {
  8768. apis.repositionMenus(tmenu);
  8769. }
  8770. },
  8771. factory: make$6,
  8772. extraApis: {
  8773. tieredData: tieredData,
  8774. singleData: singleData,
  8775. collapseItem: collapseItem
  8776. }
  8777. });
  8778. var makeMenu = function (detail, menuSandbox, placementSpec, menuSpec, getBounds) {
  8779. var lazySink = function () {
  8780. return detail.lazySink(menuSandbox);
  8781. };
  8782. var layouts = menuSpec.type === 'horizontal' ? {
  8783. layouts: {
  8784. onLtr: function () {
  8785. return belowOrAbove();
  8786. },
  8787. onRtl: function () {
  8788. return belowOrAboveRtl();
  8789. }
  8790. }
  8791. } : {};
  8792. var isFirstTierSubmenu = function (triggeringPaths) {
  8793. return triggeringPaths.length === 2;
  8794. };
  8795. var getSubmenuLayouts = function (triggeringPaths) {
  8796. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8797. };
  8798. return tieredMenu.sketch({
  8799. dom: { tag: 'div' },
  8800. data: menuSpec.data,
  8801. markers: menuSpec.menu.markers,
  8802. highlightImmediately: menuSpec.menu.highlightImmediately,
  8803. onEscape: function () {
  8804. Sandboxing.close(menuSandbox);
  8805. detail.onEscape.map(function (handler) {
  8806. return handler(menuSandbox);
  8807. });
  8808. return Optional.some(true);
  8809. },
  8810. onExecute: function () {
  8811. return Optional.some(true);
  8812. },
  8813. onOpenMenu: function (tmenu, menu) {
  8814. Positioning.positionWithinBounds(lazySink().getOrDie(), menu, placementSpec, getBounds());
  8815. },
  8816. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8817. var sink = lazySink().getOrDie();
  8818. Positioning.position(sink, submenu, {
  8819. anchor: __assign({
  8820. type: 'submenu',
  8821. item: item
  8822. }, getSubmenuLayouts(triggeringPaths))
  8823. });
  8824. },
  8825. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8826. var sink = lazySink().getOrDie();
  8827. Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds());
  8828. each$1(submenuTriggers, function (st) {
  8829. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8830. Positioning.position(sink, st.triggeredMenu, {
  8831. anchor: __assign({
  8832. type: 'submenu',
  8833. item: st.triggeringItem
  8834. }, submenuLayouts)
  8835. });
  8836. });
  8837. }
  8838. });
  8839. };
  8840. var factory$m = function (detail, spec) {
  8841. var isPartOfRelated = function (sandbox, queryElem) {
  8842. var related = detail.getRelated(sandbox);
  8843. return related.exists(function (rel) {
  8844. return isPartOf$1(rel, queryElem);
  8845. });
  8846. };
  8847. var setContent = function (sandbox, thing) {
  8848. Sandboxing.setContent(sandbox, thing);
  8849. };
  8850. var showAt = function (sandbox, thing, placementSpec) {
  8851. showWithin(sandbox, thing, placementSpec, Optional.none());
  8852. };
  8853. var showWithin = function (sandbox, thing, placementSpec, boxElement) {
  8854. showWithinBounds(sandbox, thing, placementSpec, function () {
  8855. return boxElement.map(function (elem) {
  8856. return box$1(elem);
  8857. });
  8858. });
  8859. };
  8860. var showWithinBounds = function (sandbox, thing, placementSpec, getBounds) {
  8861. var sink = detail.lazySink(sandbox).getOrDie();
  8862. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8863. return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds());
  8864. });
  8865. Representing.setValue(sandbox, Optional.some({
  8866. mode: 'position',
  8867. config: placementSpec,
  8868. getBounds: getBounds
  8869. }));
  8870. };
  8871. var showMenuAt = function (sandbox, placementSpec, menuSpec) {
  8872. showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
  8873. };
  8874. var showMenuWithinBounds = function (sandbox, placementSpec, menuSpec, getBounds) {
  8875. var menu = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds);
  8876. Sandboxing.open(sandbox, menu);
  8877. Representing.setValue(sandbox, Optional.some({
  8878. mode: 'menu',
  8879. menu: menu
  8880. }));
  8881. };
  8882. var hide = function (sandbox) {
  8883. if (Sandboxing.isOpen(sandbox)) {
  8884. Representing.setValue(sandbox, Optional.none());
  8885. Sandboxing.close(sandbox);
  8886. }
  8887. };
  8888. var getContent = function (sandbox) {
  8889. return Sandboxing.getState(sandbox);
  8890. };
  8891. var reposition = function (sandbox) {
  8892. if (Sandboxing.isOpen(sandbox)) {
  8893. Representing.getValue(sandbox).each(function (state) {
  8894. switch (state.mode) {
  8895. case 'menu':
  8896. Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
  8897. break;
  8898. case 'position':
  8899. var sink = detail.lazySink(sandbox).getOrDie();
  8900. Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
  8901. break;
  8902. }
  8903. });
  8904. }
  8905. };
  8906. var apis = {
  8907. setContent: setContent,
  8908. showAt: showAt,
  8909. showWithin: showWithin,
  8910. showWithinBounds: showWithinBounds,
  8911. showMenuAt: showMenuAt,
  8912. showMenuWithinBounds: showMenuWithinBounds,
  8913. hide: hide,
  8914. getContent: getContent,
  8915. reposition: reposition,
  8916. isOpen: Sandboxing.isOpen
  8917. };
  8918. return {
  8919. uid: detail.uid,
  8920. dom: detail.dom,
  8921. behaviours: augment(detail.inlineBehaviours, [
  8922. Sandboxing.config({
  8923. isPartOf: function (sandbox, data, queryElem) {
  8924. return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8925. },
  8926. getAttachPoint: function (sandbox) {
  8927. return detail.lazySink(sandbox).getOrDie();
  8928. },
  8929. onOpen: function (sandbox) {
  8930. detail.onShow(sandbox);
  8931. },
  8932. onClose: function (sandbox) {
  8933. detail.onHide(sandbox);
  8934. }
  8935. }),
  8936. Representing.config({
  8937. store: {
  8938. mode: 'memory',
  8939. initialValue: Optional.none()
  8940. }
  8941. }),
  8942. Receiving.config({
  8943. channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) {
  8944. return { fireEventInstead: { event: fe.event } };
  8945. }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) {
  8946. return { fireEventInstead: { event: fe.event } };
  8947. }).getOr({})), { doReposition: reposition })))
  8948. })
  8949. ]),
  8950. eventOrder: detail.eventOrder,
  8951. apis: apis
  8952. };
  8953. };
  8954. var InlineView = single({
  8955. name: 'InlineView',
  8956. configFields: [
  8957. required$1('lazySink'),
  8958. onHandler('onShow'),
  8959. onHandler('onHide'),
  8960. optionFunction('onEscape'),
  8961. field('inlineBehaviours', [
  8962. Sandboxing,
  8963. Representing,
  8964. Receiving
  8965. ]),
  8966. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  8967. optionObjOf('fireRepositionEventInstead', [defaulted('event', repositionRequested())]),
  8968. defaulted('getRelated', Optional.none),
  8969. defaulted('isExtraPart', never),
  8970. defaulted('eventOrder', Optional.none)
  8971. ],
  8972. factory: factory$m,
  8973. apis: {
  8974. showAt: function (apis, component, anchor, thing) {
  8975. apis.showAt(component, anchor, thing);
  8976. },
  8977. showWithin: function (apis, component, anchor, thing, boxElement) {
  8978. apis.showWithin(component, anchor, thing, boxElement);
  8979. },
  8980. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8981. apis.showWithinBounds(component, anchor, thing, bounds);
  8982. },
  8983. showMenuAt: function (apis, component, anchor, menuSpec) {
  8984. apis.showMenuAt(component, anchor, menuSpec);
  8985. },
  8986. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8987. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8988. },
  8989. hide: function (apis, component) {
  8990. apis.hide(component);
  8991. },
  8992. isOpen: function (apis, component) {
  8993. return apis.isOpen(component);
  8994. },
  8995. getContent: function (apis, component) {
  8996. return apis.getContent(component);
  8997. },
  8998. setContent: function (apis, component, thing) {
  8999. apis.setContent(component, thing);
  9000. },
  9001. reposition: function (apis, component) {
  9002. apis.reposition(component);
  9003. }
  9004. }
  9005. });
  9006. var labelPrefix = 'layout-inset';
  9007. var westEdgeX = function (anchor) {
  9008. return anchor.x;
  9009. };
  9010. var middleX = function (anchor, element) {
  9011. return anchor.x + anchor.width / 2 - element.width / 2;
  9012. };
  9013. var eastEdgeX = function (anchor, element) {
  9014. return anchor.x + anchor.width - element.width;
  9015. };
  9016. var northY = function (anchor) {
  9017. return anchor.y;
  9018. };
  9019. var southY = function (anchor, element) {
  9020. return anchor.y + anchor.height - element.height;
  9021. };
  9022. var centreY = function (anchor, element) {
  9023. return anchor.y + anchor.height / 2 - element.height / 2;
  9024. };
  9025. var southwest = function (anchor, element, bubbles) {
  9026. return nu$6(eastEdgeX(anchor, element), southY(anchor, element), bubbles.insetSouthwest(), northwest$3(), 'southwest', boundsRestriction(anchor, {
  9027. right: 0,
  9028. bottom: 3
  9029. }), labelPrefix);
  9030. };
  9031. var southeast = function (anchor, element, bubbles) {
  9032. return nu$6(westEdgeX(anchor), southY(anchor, element), bubbles.insetSoutheast(), northeast$3(), 'southeast', boundsRestriction(anchor, {
  9033. left: 1,
  9034. bottom: 3
  9035. }), labelPrefix);
  9036. };
  9037. var northwest = function (anchor, element, bubbles) {
  9038. return nu$6(eastEdgeX(anchor, element), northY(anchor), bubbles.insetNorthwest(), southwest$3(), 'northwest', boundsRestriction(anchor, {
  9039. right: 0,
  9040. top: 2
  9041. }), labelPrefix);
  9042. };
  9043. var northeast = function (anchor, element, bubbles) {
  9044. return nu$6(westEdgeX(anchor), northY(anchor), bubbles.insetNortheast(), southeast$3(), 'northeast', boundsRestriction(anchor, {
  9045. left: 1,
  9046. top: 2
  9047. }), labelPrefix);
  9048. };
  9049. var north = function (anchor, element, bubbles) {
  9050. return nu$6(middleX(anchor, element), northY(anchor), bubbles.insetNorth(), south$3(), 'north', boundsRestriction(anchor, { top: 2 }), labelPrefix);
  9051. };
  9052. var south = function (anchor, element, bubbles) {
  9053. return nu$6(middleX(anchor, element), southY(anchor, element), bubbles.insetSouth(), north$3(), 'south', boundsRestriction(anchor, { bottom: 3 }), labelPrefix);
  9054. };
  9055. var east = function (anchor, element, bubbles) {
  9056. return nu$6(eastEdgeX(anchor, element), centreY(anchor, element), bubbles.insetEast(), west$3(), 'east', boundsRestriction(anchor, { right: 0 }), labelPrefix);
  9057. };
  9058. var west = function (anchor, element, bubbles) {
  9059. return nu$6(westEdgeX(anchor), centreY(anchor, element), bubbles.insetWest(), east$3(), 'west', boundsRestriction(anchor, { left: 1 }), labelPrefix);
  9060. };
  9061. var lookupPreserveLayout = function (lastPlacement) {
  9062. switch (lastPlacement) {
  9063. case 'north':
  9064. return north;
  9065. case 'northeast':
  9066. return northeast;
  9067. case 'northwest':
  9068. return northwest;
  9069. case 'south':
  9070. return south;
  9071. case 'southeast':
  9072. return southeast;
  9073. case 'southwest':
  9074. return southwest;
  9075. case 'east':
  9076. return east;
  9077. case 'west':
  9078. return west;
  9079. }
  9080. };
  9081. var preserve = function (anchor, element, bubbles, placee, bounds) {
  9082. var layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
  9083. return layout(anchor, element, bubbles, placee, bounds);
  9084. };
  9085. var lookupFlippedLayout = function (lastPlacement) {
  9086. switch (lastPlacement) {
  9087. case 'north':
  9088. return south;
  9089. case 'northeast':
  9090. return southeast;
  9091. case 'northwest':
  9092. return southwest;
  9093. case 'south':
  9094. return north;
  9095. case 'southeast':
  9096. return northeast;
  9097. case 'southwest':
  9098. return northwest;
  9099. case 'east':
  9100. return west;
  9101. case 'west':
  9102. return east;
  9103. }
  9104. };
  9105. var flip$2 = function (anchor, element, bubbles, placee, bounds) {
  9106. var layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
  9107. return layout(anchor, element, bubbles, placee, bounds);
  9108. };
  9109. var global$g = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9110. var factory$l = function (detail) {
  9111. var events = events$a(detail.action);
  9112. var tag = detail.dom.tag;
  9113. var lookupAttr = function (attr) {
  9114. return get$e(detail.dom, 'attributes').bind(function (attrs) {
  9115. return get$e(attrs, attr);
  9116. });
  9117. };
  9118. var getModAttributes = function () {
  9119. if (tag === 'button') {
  9120. var type = lookupAttr('type').getOr('button');
  9121. var roleAttrs = lookupAttr('role').map(function (role) {
  9122. return { role: role };
  9123. }).getOr({});
  9124. return __assign({ type: type }, roleAttrs);
  9125. } else {
  9126. var role = lookupAttr('role').getOr('button');
  9127. return { role: role };
  9128. }
  9129. };
  9130. return {
  9131. uid: detail.uid,
  9132. dom: detail.dom,
  9133. components: detail.components,
  9134. events: events,
  9135. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  9136. Focusing.config({}),
  9137. Keying.config({
  9138. mode: 'execution',
  9139. useSpace: true,
  9140. useEnter: true
  9141. })
  9142. ]),
  9143. domModification: { attributes: getModAttributes() },
  9144. eventOrder: detail.eventOrder
  9145. };
  9146. };
  9147. var Button = single({
  9148. name: 'Button',
  9149. factory: factory$l,
  9150. configFields: [
  9151. defaulted('uid', undefined),
  9152. required$1('dom'),
  9153. defaulted('components', []),
  9154. SketchBehaviours.field('buttonBehaviours', [
  9155. Focusing,
  9156. Keying
  9157. ]),
  9158. option('action'),
  9159. option('role'),
  9160. defaulted('eventOrder', {})
  9161. ]
  9162. });
  9163. var record = function (spec) {
  9164. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$5('memento');
  9165. var get = function (anyInSystem) {
  9166. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  9167. };
  9168. var getOpt = function (anyInSystem) {
  9169. return anyInSystem.getSystem().getByUid(uid).toOptional();
  9170. };
  9171. var asSpec = function () {
  9172. return __assign(__assign({}, spec), { uid: uid });
  9173. };
  9174. return {
  9175. get: get,
  9176. getOpt: getOpt,
  9177. asSpec: asSpec
  9178. };
  9179. };
  9180. var global$f = tinymce.util.Tools.resolve('tinymce.util.I18n');
  9181. var rtlTransform = {
  9182. 'indent': true,
  9183. 'outdent': true,
  9184. 'table-insert-column-after': true,
  9185. 'table-insert-column-before': true,
  9186. 'paste-column-after': true,
  9187. 'paste-column-before': true,
  9188. 'unordered-list': true,
  9189. 'list-bull-circle': true,
  9190. 'list-bull-default': true,
  9191. 'list-bull-square': true
  9192. };
  9193. var defaultIconName = 'temporary-placeholder';
  9194. var defaultIcon = function (icons) {
  9195. return function () {
  9196. return get$e(icons, defaultIconName).getOr('!not found!');
  9197. };
  9198. };
  9199. var getIconName = function (name, icons) {
  9200. var lcName = name.toLowerCase();
  9201. if (global$f.isRtl()) {
  9202. var rtlName = ensureTrailing(lcName, '-rtl');
  9203. return has$2(icons, rtlName) ? rtlName : lcName;
  9204. } else {
  9205. return lcName;
  9206. }
  9207. };
  9208. var lookupIcon = function (name, icons) {
  9209. return get$e(icons, getIconName(name, icons));
  9210. };
  9211. var get$1 = function (name, iconProvider) {
  9212. var icons = iconProvider();
  9213. return lookupIcon(name, icons).getOrThunk(defaultIcon(icons));
  9214. };
  9215. var getOr = function (name, iconProvider, fallbackIcon) {
  9216. var icons = iconProvider();
  9217. return lookupIcon(name, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  9218. };
  9219. var needsRtlTransform = function (iconName) {
  9220. return global$f.isRtl() ? has$2(rtlTransform, iconName) : false;
  9221. };
  9222. var addFocusableBehaviour = function () {
  9223. return config('add-focusable', [runOnAttached(function (comp) {
  9224. child(comp.element, 'svg').each(function (svg) {
  9225. return set$7(svg, 'focusable', 'false');
  9226. });
  9227. })]);
  9228. };
  9229. var renderIcon$2 = function (spec, iconName, icons, fallbackIcon) {
  9230. var _a, _b;
  9231. var rtlIconClasses = needsRtlTransform(iconName) ? ['tox-icon--flip'] : [];
  9232. var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  9233. return {
  9234. dom: {
  9235. tag: spec.tag,
  9236. attributes: (_a = spec.attributes) !== null && _a !== void 0 ? _a : {},
  9237. classes: spec.classes.concat(rtlIconClasses),
  9238. innerHtml: iconHtml
  9239. },
  9240. behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : []), [addFocusableBehaviour()]))
  9241. };
  9242. };
  9243. var render$3 = function (iconName, spec, iconProvider, fallbackIcon) {
  9244. if (fallbackIcon === void 0) {
  9245. fallbackIcon = Optional.none();
  9246. }
  9247. return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
  9248. };
  9249. var renderFirst = function (iconNames, spec, iconProvider) {
  9250. var icons = iconProvider();
  9251. var iconName = find$5(iconNames, function (name) {
  9252. return has$2(icons, getIconName(name, icons));
  9253. });
  9254. return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
  9255. };
  9256. var notificationIconMap = {
  9257. success: 'checkmark',
  9258. error: 'warning',
  9259. err: 'error',
  9260. warning: 'warning',
  9261. warn: 'warning',
  9262. info: 'info'
  9263. };
  9264. var factory$k = function (detail) {
  9265. var memBannerText = record({
  9266. dom: {
  9267. tag: 'p',
  9268. innerHtml: detail.translationProvider(detail.text)
  9269. },
  9270. behaviours: derive$1([Replacing.config({})])
  9271. });
  9272. var renderPercentBar = function (percent) {
  9273. return {
  9274. dom: {
  9275. tag: 'div',
  9276. classes: ['tox-bar'],
  9277. attributes: { style: 'width: ' + percent + '%' }
  9278. }
  9279. };
  9280. };
  9281. var renderPercentText = function (percent) {
  9282. return {
  9283. dom: {
  9284. tag: 'div',
  9285. classes: ['tox-text'],
  9286. innerHtml: percent + '%'
  9287. }
  9288. };
  9289. };
  9290. var memBannerProgress = record({
  9291. dom: {
  9292. tag: 'div',
  9293. classes: detail.progress ? [
  9294. 'tox-progress-bar',
  9295. 'tox-progress-indicator'
  9296. ] : ['tox-progress-bar']
  9297. },
  9298. components: [
  9299. {
  9300. dom: {
  9301. tag: 'div',
  9302. classes: ['tox-bar-container']
  9303. },
  9304. components: [renderPercentBar(0)]
  9305. },
  9306. renderPercentText(0)
  9307. ],
  9308. behaviours: derive$1([Replacing.config({})])
  9309. });
  9310. var updateProgress = function (comp, percent) {
  9311. if (comp.getSystem().isConnected()) {
  9312. memBannerProgress.getOpt(comp).each(function (progress) {
  9313. Replacing.set(progress, [
  9314. {
  9315. dom: {
  9316. tag: 'div',
  9317. classes: ['tox-bar-container']
  9318. },
  9319. components: [renderPercentBar(percent)]
  9320. },
  9321. renderPercentText(percent)
  9322. ]);
  9323. });
  9324. }
  9325. };
  9326. var updateText = function (comp, text$1) {
  9327. if (comp.getSystem().isConnected()) {
  9328. var banner = memBannerText.get(comp);
  9329. Replacing.set(banner, [text(text$1)]);
  9330. }
  9331. };
  9332. var apis = {
  9333. updateProgress: updateProgress,
  9334. updateText: updateText
  9335. };
  9336. var iconChoices = flatten([
  9337. detail.icon.toArray(),
  9338. detail.level.toArray(),
  9339. detail.level.bind(function (level) {
  9340. return Optional.from(notificationIconMap[level]);
  9341. }).toArray()
  9342. ]);
  9343. var memButton = record(Button.sketch({
  9344. dom: {
  9345. tag: 'button',
  9346. classes: [
  9347. 'tox-notification__dismiss',
  9348. 'tox-button',
  9349. 'tox-button--naked',
  9350. 'tox-button--icon'
  9351. ]
  9352. },
  9353. components: [render$3('close', {
  9354. tag: 'div',
  9355. classes: ['tox-icon'],
  9356. attributes: { 'aria-label': detail.translationProvider('Close') }
  9357. }, detail.iconProvider)],
  9358. action: function (comp) {
  9359. detail.onAction(comp);
  9360. }
  9361. }));
  9362. var notificationIconSpec = renderFirst(iconChoices, {
  9363. tag: 'div',
  9364. classes: ['tox-notification__icon']
  9365. }, detail.iconProvider);
  9366. var notificationBodySpec = {
  9367. dom: {
  9368. tag: 'div',
  9369. classes: ['tox-notification__body']
  9370. },
  9371. components: [memBannerText.asSpec()],
  9372. behaviours: derive$1([Replacing.config({})])
  9373. };
  9374. var components = [
  9375. notificationIconSpec,
  9376. notificationBodySpec
  9377. ];
  9378. return {
  9379. uid: detail.uid,
  9380. dom: {
  9381. tag: 'div',
  9382. attributes: { role: 'alert' },
  9383. classes: detail.level.map(function (level) {
  9384. return [
  9385. 'tox-notification',
  9386. 'tox-notification--in',
  9387. 'tox-notification--' + level
  9388. ];
  9389. }).getOr([
  9390. 'tox-notification',
  9391. 'tox-notification--in'
  9392. ])
  9393. },
  9394. behaviours: derive$1([
  9395. Focusing.config({}),
  9396. config('notification-events', [run$1(focusin(), function (comp) {
  9397. memButton.getOpt(comp).each(Focusing.focus);
  9398. })])
  9399. ]),
  9400. components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
  9401. apis: apis
  9402. };
  9403. };
  9404. var Notification = single({
  9405. name: 'Notification',
  9406. factory: factory$k,
  9407. configFields: [
  9408. option('level'),
  9409. required$1('progress'),
  9410. required$1('icon'),
  9411. required$1('onAction'),
  9412. required$1('text'),
  9413. required$1('iconProvider'),
  9414. required$1('translationProvider'),
  9415. defaultedBoolean('closeButton', true)
  9416. ],
  9417. apis: {
  9418. updateProgress: function (apis, comp, percent) {
  9419. apis.updateProgress(comp, percent);
  9420. },
  9421. updateText: function (apis, comp, text) {
  9422. apis.updateText(comp, text);
  9423. }
  9424. }
  9425. });
  9426. function NotificationManagerImpl (editor, extras, uiMothership) {
  9427. var sharedBackstage = extras.backstage.shared;
  9428. var getLayoutDirection = function (rel) {
  9429. switch (rel) {
  9430. case 'bc-bc':
  9431. return south;
  9432. case 'tc-tc':
  9433. return north;
  9434. case 'tc-bc':
  9435. return north$2;
  9436. case 'bc-tc':
  9437. default:
  9438. return south$2;
  9439. }
  9440. };
  9441. var prePositionNotifications = function (notifications) {
  9442. each$1(notifications, function (notification) {
  9443. return notification.moveTo(0, 0);
  9444. });
  9445. };
  9446. var positionNotifications = function (notifications) {
  9447. if (notifications.length > 0) {
  9448. head(notifications).each(function (firstItem) {
  9449. return firstItem.moveRel(null, 'banner');
  9450. });
  9451. each$1(notifications, function (notification, index) {
  9452. if (index > 0) {
  9453. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  9454. }
  9455. });
  9456. }
  9457. };
  9458. var reposition = function (notifications) {
  9459. prePositionNotifications(notifications);
  9460. positionNotifications(notifications);
  9461. };
  9462. var open = function (settings, closeCallback) {
  9463. var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  9464. var close = function () {
  9465. closeCallback();
  9466. InlineView.hide(notificationWrapper);
  9467. };
  9468. var notification = build$1(Notification.sketch({
  9469. text: settings.text,
  9470. level: contains$2([
  9471. 'success',
  9472. 'error',
  9473. 'warning',
  9474. 'warn',
  9475. 'info'
  9476. ], settings.type) ? settings.type : undefined,
  9477. progress: settings.progressBar === true,
  9478. icon: Optional.from(settings.icon),
  9479. closeButton: !hideCloseButton,
  9480. onAction: close,
  9481. iconProvider: sharedBackstage.providers.icons,
  9482. translationProvider: sharedBackstage.providers.translate
  9483. }));
  9484. var notificationWrapper = build$1(InlineView.sketch(__assign({
  9485. dom: {
  9486. tag: 'div',
  9487. classes: ['tox-notifications-container']
  9488. },
  9489. lazySink: sharedBackstage.getSink,
  9490. fireDismissalEventInstead: {}
  9491. }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
  9492. uiMothership.add(notificationWrapper);
  9493. if (settings.timeout > 0) {
  9494. global$g.setTimeout(function () {
  9495. close();
  9496. }, settings.timeout);
  9497. }
  9498. return {
  9499. close: close,
  9500. moveTo: function (x, y) {
  9501. InlineView.showAt(notificationWrapper, premade(notification), {
  9502. anchor: {
  9503. type: 'makeshift',
  9504. x: x,
  9505. y: y
  9506. }
  9507. });
  9508. },
  9509. moveRel: function (element, rel) {
  9510. if (rel !== 'banner') {
  9511. var layoutDirection_1 = getLayoutDirection(rel);
  9512. var nodeAnchor = {
  9513. type: 'node',
  9514. root: body(),
  9515. node: Optional.some(SugarElement.fromDom(element)),
  9516. layouts: {
  9517. onRtl: function () {
  9518. return [layoutDirection_1];
  9519. },
  9520. onLtr: function () {
  9521. return [layoutDirection_1];
  9522. }
  9523. }
  9524. };
  9525. InlineView.showAt(notificationWrapper, premade(notification), { anchor: nodeAnchor });
  9526. } else {
  9527. InlineView.showAt(notificationWrapper, premade(notification), { anchor: sharedBackstage.anchors.banner() });
  9528. }
  9529. },
  9530. text: function (nuText) {
  9531. Notification.updateText(notification, nuText);
  9532. },
  9533. settings: settings,
  9534. getEl: function () {
  9535. return notification.element.dom;
  9536. },
  9537. progressBar: {
  9538. value: function (percent) {
  9539. Notification.updateProgress(notification, percent);
  9540. }
  9541. }
  9542. };
  9543. };
  9544. var close = function (notification) {
  9545. notification.close();
  9546. };
  9547. var getArgs = function (notification) {
  9548. return notification.settings;
  9549. };
  9550. return {
  9551. open: open,
  9552. close: close,
  9553. reposition: reposition,
  9554. getArgs: getArgs
  9555. };
  9556. }
  9557. var first = function (fn, rate) {
  9558. var timer = null;
  9559. var cancel = function () {
  9560. if (!isNull(timer)) {
  9561. clearTimeout(timer);
  9562. timer = null;
  9563. }
  9564. };
  9565. var throttle = function () {
  9566. var args = [];
  9567. for (var _i = 0; _i < arguments.length; _i++) {
  9568. args[_i] = arguments[_i];
  9569. }
  9570. if (isNull(timer)) {
  9571. timer = setTimeout(function () {
  9572. timer = null;
  9573. fn.apply(null, args);
  9574. }, rate);
  9575. }
  9576. };
  9577. return {
  9578. cancel: cancel,
  9579. throttle: throttle
  9580. };
  9581. };
  9582. var last = function (fn, rate) {
  9583. var timer = null;
  9584. var cancel = function () {
  9585. if (!isNull(timer)) {
  9586. clearTimeout(timer);
  9587. timer = null;
  9588. }
  9589. };
  9590. var throttle = function () {
  9591. var args = [];
  9592. for (var _i = 0; _i < arguments.length; _i++) {
  9593. args[_i] = arguments[_i];
  9594. }
  9595. cancel();
  9596. timer = setTimeout(function () {
  9597. timer = null;
  9598. fn.apply(null, args);
  9599. }, rate);
  9600. };
  9601. return {
  9602. cancel: cancel,
  9603. throttle: throttle
  9604. };
  9605. };
  9606. var global$e = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  9607. var isBoundary = function (dom, node) {
  9608. return dom.isBlock(node) || contains$2([
  9609. 'BR',
  9610. 'IMG',
  9611. 'HR',
  9612. 'INPUT'
  9613. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9614. };
  9615. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9616. var search = global$e(dom, function (node) {
  9617. return isBoundary(dom, node);
  9618. });
  9619. return Optional.from(search.backwards(node, offset, process, rootNode));
  9620. };
  9621. var autocompleteSelector = '[data-mce-autocompleter]';
  9622. var create$4 = function (editor, range) {
  9623. return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9624. var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9625. append$2(wrapper, SugarElement.fromDom(range.extractContents()));
  9626. range.insertNode(wrapper.dom);
  9627. parent(wrapper).each(function (elm) {
  9628. return elm.dom.normalize();
  9629. });
  9630. last$1(wrapper).map(function (last) {
  9631. editor.selection.setCursorLocation(last.dom, getEnd(last));
  9632. });
  9633. return wrapper;
  9634. });
  9635. };
  9636. var detect = function (elm) {
  9637. return closest$1(elm, autocompleteSelector);
  9638. };
  9639. var isValidTextRange = function (rng) {
  9640. return rng.collapsed && rng.startContainer.nodeType === 3;
  9641. };
  9642. var getText = function (rng) {
  9643. return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9644. };
  9645. var isWhitespace = function (chr) {
  9646. return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  9647. };
  9648. var stripTriggerChar = function (text, triggerCh) {
  9649. return text.substring(triggerCh.length);
  9650. };
  9651. var findChar = function (text, index, ch) {
  9652. var i;
  9653. for (i = index - 1; i >= 0; i--) {
  9654. var char = text.charAt(i);
  9655. if (isWhitespace(char)) {
  9656. return Optional.none();
  9657. }
  9658. if (char === ch) {
  9659. break;
  9660. }
  9661. }
  9662. return Optional.some(i);
  9663. };
  9664. var findStart = function (dom, initRange, ch, minChars) {
  9665. if (minChars === void 0) {
  9666. minChars = 0;
  9667. }
  9668. if (!isValidTextRange(initRange)) {
  9669. return Optional.none();
  9670. }
  9671. var findTriggerChIndex = function (element, offset, text) {
  9672. return findChar(text, offset, ch).getOr(offset);
  9673. };
  9674. var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  9675. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  9676. var range = initRange.cloneRange();
  9677. range.setStart(spot.container, spot.offset);
  9678. range.setEnd(initRange.endContainer, initRange.endOffset);
  9679. if (range.collapsed) {
  9680. return Optional.none();
  9681. }
  9682. var text = getText(range);
  9683. var triggerCharIndex = text.lastIndexOf(ch);
  9684. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  9685. return Optional.none();
  9686. } else {
  9687. return Optional.some({
  9688. text: stripTriggerChar(text, ch),
  9689. range: range,
  9690. triggerChar: ch
  9691. });
  9692. }
  9693. });
  9694. };
  9695. var getContext = function (dom, initRange, ch, minChars) {
  9696. if (minChars === void 0) {
  9697. minChars = 0;
  9698. }
  9699. return detect(SugarElement.fromDom(initRange.startContainer)).fold(function () {
  9700. return findStart(dom, initRange, ch, minChars);
  9701. }, function (elm) {
  9702. var range = dom.createRng();
  9703. range.selectNode(elm.dom);
  9704. var text = getText(range);
  9705. return Optional.some({
  9706. range: range,
  9707. text: stripTriggerChar(text, ch),
  9708. triggerChar: ch
  9709. });
  9710. });
  9711. };
  9712. var setup$e = function (api, editor) {
  9713. editor.on('keypress compositionend', api.onKeypress.throttle);
  9714. editor.on('remove', api.onKeypress.cancel);
  9715. var redirectKeyToItem = function (item, e) {
  9716. emitWith(item, keydown(), { raw: e });
  9717. };
  9718. editor.on('keydown', function (e) {
  9719. var getItem = function () {
  9720. return api.getView().bind(Highlighting.getHighlighted);
  9721. };
  9722. if (e.which === 8) {
  9723. api.onKeypress.throttle(e);
  9724. }
  9725. if (api.isActive()) {
  9726. if (e.which === 27) {
  9727. api.cancelIfNecessary();
  9728. }
  9729. if (api.isMenuOpen()) {
  9730. if (e.which === 13) {
  9731. getItem().each(emitExecute);
  9732. e.preventDefault();
  9733. } else if (e.which === 40) {
  9734. getItem().fold(function () {
  9735. api.getView().each(Highlighting.highlightFirst);
  9736. }, function (item) {
  9737. redirectKeyToItem(item, e);
  9738. });
  9739. e.preventDefault();
  9740. e.stopImmediatePropagation();
  9741. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9742. getItem().each(function (item) {
  9743. redirectKeyToItem(item, e);
  9744. e.preventDefault();
  9745. e.stopImmediatePropagation();
  9746. });
  9747. }
  9748. } else {
  9749. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9750. api.cancelIfNecessary();
  9751. }
  9752. }
  9753. }
  9754. });
  9755. editor.on('NodeChange', function (e) {
  9756. if (api.isActive() && !api.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) {
  9757. api.cancelIfNecessary();
  9758. }
  9759. });
  9760. };
  9761. var AutocompleterEditorEvents = { setup: setup$e };
  9762. var global$d = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9763. var point = function (container, offset) {
  9764. return {
  9765. container: container,
  9766. offset: offset
  9767. };
  9768. };
  9769. var isText = function (node) {
  9770. return node.nodeType === TEXT;
  9771. };
  9772. var isElement$1 = function (node) {
  9773. return node.nodeType === ELEMENT;
  9774. };
  9775. var toLast = function (node) {
  9776. if (isText(node)) {
  9777. return point(node, node.data.length);
  9778. } else {
  9779. var children = node.childNodes;
  9780. return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  9781. }
  9782. };
  9783. var toLeaf = function (node, offset) {
  9784. var children = node.childNodes;
  9785. if (children.length > 0 && offset < children.length) {
  9786. return toLeaf(children[offset], 0);
  9787. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9788. return toLast(children[children.length - 1]);
  9789. } else {
  9790. return point(node, offset);
  9791. }
  9792. };
  9793. var isPreviousCharContent = function (dom, leaf) {
  9794. return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  9795. return offset === 0 ? -1 : offset;
  9796. }, dom.getRoot()).filter(function (spot) {
  9797. var char = spot.container.data.charAt(spot.offset - 1);
  9798. return !isWhitespace(char);
  9799. }).isSome();
  9800. };
  9801. var isStartOfWord = function (dom) {
  9802. return function (rng) {
  9803. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9804. return !isPreviousCharContent(dom, leaf);
  9805. };
  9806. };
  9807. var getTriggerContext = function (dom, initRange, database) {
  9808. return findMap(database.triggerChars, function (ch) {
  9809. return getContext(dom, initRange, ch);
  9810. });
  9811. };
  9812. var lookup$2 = function (editor, getDatabase) {
  9813. var database = getDatabase();
  9814. var rng = editor.selection.getRng();
  9815. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9816. return lookupWithContext(editor, getDatabase, context);
  9817. });
  9818. };
  9819. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9820. if (fetchOptions === void 0) {
  9821. fetchOptions = {};
  9822. }
  9823. var database = getDatabase();
  9824. var rng = editor.selection.getRng();
  9825. var startText = rng.startContainer.nodeValue;
  9826. var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9827. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9828. return isStartOfWord(editor.dom);
  9829. })(context.range, startText, context.text);
  9830. });
  9831. if (autocompleters.length === 0) {
  9832. return Optional.none();
  9833. }
  9834. var lookupData = global$d.all(map$2(autocompleters, function (ac) {
  9835. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9836. return fetchResult.then(function (results) {
  9837. return {
  9838. matchText: context.text,
  9839. items: results,
  9840. columns: ac.columns,
  9841. onAction: ac.onAction,
  9842. highlightOn: ac.highlightOn
  9843. };
  9844. });
  9845. }));
  9846. return Optional.some({
  9847. lookupData: lookupData,
  9848. context: context
  9849. });
  9850. };
  9851. var separatorMenuItemSchema = objOf([
  9852. requiredString('type'),
  9853. optionString('text')
  9854. ]);
  9855. var createSeparatorMenuItem = function (spec) {
  9856. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9857. };
  9858. var autocompleterItemSchema = objOf([
  9859. defaulted('type', 'autocompleteitem'),
  9860. defaulted('active', false),
  9861. defaulted('disabled', false),
  9862. defaulted('meta', {}),
  9863. requiredString('value'),
  9864. optionString('text'),
  9865. optionString('icon')
  9866. ]);
  9867. var autocompleterSchema = objOf([
  9868. requiredString('type'),
  9869. requiredString('ch'),
  9870. defaultedNumber('minChars', 1),
  9871. defaulted('columns', 1),
  9872. defaultedNumber('maxResults', 10),
  9873. optionFunction('matches'),
  9874. requiredFunction('fetch'),
  9875. requiredFunction('onAction'),
  9876. defaultedArrayOf('highlightOn', [], string)
  9877. ]);
  9878. var createSeparatorItem = function (spec) {
  9879. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9880. };
  9881. var createAutocompleterItem = function (spec) {
  9882. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9883. };
  9884. var createAutocompleter = function (spec) {
  9885. return asRaw('Autocompleter', autocompleterSchema, spec);
  9886. };
  9887. var baseToolbarButtonFields = [
  9888. defaultedBoolean('disabled', false),
  9889. optionString('tooltip'),
  9890. optionString('icon'),
  9891. optionString('text'),
  9892. defaultedFunction('onSetup', function () {
  9893. return noop;
  9894. })
  9895. ];
  9896. var toolbarButtonSchema = objOf([
  9897. requiredString('type'),
  9898. requiredFunction('onAction')
  9899. ].concat(baseToolbarButtonFields));
  9900. var createToolbarButton = function (spec) {
  9901. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  9902. };
  9903. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  9904. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  9905. requiredString('type'),
  9906. requiredFunction('onAction')
  9907. ]));
  9908. var createToggleButton = function (spec) {
  9909. return asRaw('ToggleButton', toggleButtonSchema, spec);
  9910. };
  9911. var contextBarFields = [
  9912. defaultedFunction('predicate', never),
  9913. defaultedStringEnum('scope', 'node', [
  9914. 'node',
  9915. 'editor'
  9916. ]),
  9917. defaultedStringEnum('position', 'selection', [
  9918. 'node',
  9919. 'selection',
  9920. 'line'
  9921. ])
  9922. ];
  9923. var contextButtonFields = baseToolbarButtonFields.concat([
  9924. defaulted('type', 'contextformbutton'),
  9925. defaulted('primary', false),
  9926. requiredFunction('onAction'),
  9927. customField('original', identity$1)
  9928. ]);
  9929. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  9930. defaulted('type', 'contextformbutton'),
  9931. defaulted('primary', false),
  9932. requiredFunction('onAction'),
  9933. customField('original', identity$1)
  9934. ]);
  9935. var launchButtonFields = baseToolbarButtonFields.concat([defaulted('type', 'contextformbutton')]);
  9936. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted('type', 'contextformtogglebutton')]);
  9937. var toggleOrNormal = choose$1('type', {
  9938. contextformbutton: contextButtonFields,
  9939. contextformtogglebutton: contextToggleButtonFields
  9940. });
  9941. var contextFormSchema = objOf([
  9942. defaulted('type', 'contextform'),
  9943. defaultedFunction('initValue', constant$1('')),
  9944. optionString('label'),
  9945. requiredArrayOf('commands', toggleOrNormal),
  9946. optionOf('launch', choose$1('type', {
  9947. contextformbutton: launchButtonFields,
  9948. contextformtogglebutton: launchToggleButtonFields
  9949. }))
  9950. ].concat(contextBarFields));
  9951. var createContextForm = function (spec) {
  9952. return asRaw('ContextForm', contextFormSchema, spec);
  9953. };
  9954. var contextToolbarSchema = objOf([
  9955. defaulted('type', 'contexttoolbar'),
  9956. requiredString('items')
  9957. ].concat(contextBarFields));
  9958. var createContextToolbar = function (spec) {
  9959. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  9960. };
  9961. var stringArray = function (a) {
  9962. var all = {};
  9963. each$1(a, function (key) {
  9964. all[key] = {};
  9965. });
  9966. return keys(all);
  9967. };
  9968. var register$b = function (editor) {
  9969. var popups = editor.ui.registry.getAll().popups;
  9970. var dataset = map(popups, function (popup) {
  9971. return createAutocompleter(popup).fold(function (err) {
  9972. throw new Error(formatError(err));
  9973. }, identity$1);
  9974. });
  9975. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9976. return v.ch;
  9977. }));
  9978. var datasetValues = values(dataset);
  9979. var lookupByChar = function (ch) {
  9980. return filter$2(datasetValues, function (dv) {
  9981. return dv.ch === ch;
  9982. });
  9983. };
  9984. return {
  9985. dataset: dataset,
  9986. triggerChars: triggerChars,
  9987. lookupByChar: lookupByChar
  9988. };
  9989. };
  9990. var ItemResponse;
  9991. (function (ItemResponse) {
  9992. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  9993. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  9994. }(ItemResponse || (ItemResponse = {})));
  9995. var ItemResponse$1 = ItemResponse;
  9996. var navClass = 'tox-menu-nav__js';
  9997. var selectableClass = 'tox-collection__item';
  9998. var colorClass = 'tox-swatch';
  9999. var presetClasses = {
  10000. normal: navClass,
  10001. color: colorClass
  10002. };
  10003. var tickedClass = 'tox-collection__item--enabled';
  10004. var groupHeadingClass = 'tox-collection__group-heading';
  10005. var iconClass = 'tox-collection__item-icon';
  10006. var textClass = 'tox-collection__item-label';
  10007. var accessoryClass = 'tox-collection__item-accessory';
  10008. var caretClass = 'tox-collection__item-caret';
  10009. var checkmarkClass = 'tox-collection__item-checkmark';
  10010. var activeClass = 'tox-collection__item--active';
  10011. var containerClass = 'tox-collection__item-container';
  10012. var containerColumnClass = 'tox-collection__item-container--column';
  10013. var containerRowClass = 'tox-collection__item-container--row';
  10014. var containerAlignRightClass = 'tox-collection__item-container--align-right';
  10015. var containerAlignLeftClass = 'tox-collection__item-container--align-left';
  10016. var containerValignTopClass = 'tox-collection__item-container--valign-top';
  10017. var containerValignMiddleClass = 'tox-collection__item-container--valign-middle';
  10018. var containerValignBottomClass = 'tox-collection__item-container--valign-bottom';
  10019. var classForPreset = function (presets) {
  10020. return get$e(presetClasses, presets).getOr(navClass);
  10021. };
  10022. var forMenu = function (presets) {
  10023. if (presets === 'color') {
  10024. return 'tox-swatches';
  10025. } else {
  10026. return 'tox-menu';
  10027. }
  10028. };
  10029. var classes = function (presets) {
  10030. return {
  10031. backgroundMenu: 'tox-background-menu',
  10032. selectedMenu: 'tox-selected-menu',
  10033. selectedItem: 'tox-collection__item--active',
  10034. hasIcons: 'tox-menu--has-icons',
  10035. menu: forMenu(presets),
  10036. tieredMenu: 'tox-tiered-menu'
  10037. };
  10038. };
  10039. var markers = function (presets) {
  10040. var menuClasses = classes(presets);
  10041. return {
  10042. backgroundMenu: menuClasses.backgroundMenu,
  10043. selectedMenu: menuClasses.selectedMenu,
  10044. menu: menuClasses.menu,
  10045. selectedItem: menuClasses.selectedItem,
  10046. item: classForPreset(presets)
  10047. };
  10048. };
  10049. var dom$1 = function (hasIcons, columns, presets) {
  10050. var menuClasses = classes(presets);
  10051. return {
  10052. tag: 'div',
  10053. classes: flatten([
  10054. [
  10055. menuClasses.menu,
  10056. 'tox-menu-' + columns + '-column'
  10057. ],
  10058. hasIcons ? [menuClasses.hasIcons] : []
  10059. ])
  10060. };
  10061. };
  10062. var components = [Menu.parts.items({})];
  10063. var part = function (hasIcons, columns, presets) {
  10064. var menuClasses = classes(presets);
  10065. var d = {
  10066. tag: 'div',
  10067. classes: flatten([[menuClasses.tieredMenu]])
  10068. };
  10069. return {
  10070. dom: d,
  10071. markers: markers(presets)
  10072. };
  10073. };
  10074. var chunk = function (rowDom, numColumns) {
  10075. return function (items) {
  10076. var chunks = chunk$1(items, numColumns);
  10077. return map$2(chunks, function (c) {
  10078. return {
  10079. dom: rowDom,
  10080. components: c
  10081. };
  10082. });
  10083. };
  10084. };
  10085. var forSwatch = function (columns) {
  10086. return {
  10087. dom: {
  10088. tag: 'div',
  10089. classes: [
  10090. 'tox-menu',
  10091. 'tox-swatches-menu'
  10092. ]
  10093. },
  10094. components: [{
  10095. dom: {
  10096. tag: 'div',
  10097. classes: ['tox-swatches']
  10098. },
  10099. components: [Menu.parts.items({
  10100. preprocess: columns !== 'auto' ? chunk({
  10101. tag: 'div',
  10102. classes: ['tox-swatches__row']
  10103. }, columns) : identity$1
  10104. })]
  10105. }]
  10106. };
  10107. };
  10108. var forToolbar = function (columns) {
  10109. return {
  10110. dom: {
  10111. tag: 'div',
  10112. classes: [
  10113. 'tox-menu',
  10114. 'tox-collection',
  10115. 'tox-collection--toolbar',
  10116. 'tox-collection--toolbar-lg'
  10117. ]
  10118. },
  10119. components: [Menu.parts.items({
  10120. preprocess: chunk({
  10121. tag: 'div',
  10122. classes: ['tox-collection__group']
  10123. }, columns)
  10124. })]
  10125. };
  10126. };
  10127. var preprocessCollection = function (items, isSeparator) {
  10128. var allSplits = [];
  10129. var currentSplit = [];
  10130. each$1(items, function (item, i) {
  10131. if (isSeparator(item, i)) {
  10132. if (currentSplit.length > 0) {
  10133. allSplits.push(currentSplit);
  10134. }
  10135. currentSplit = [];
  10136. if (has$2(item.dom, 'innerHtml')) {
  10137. currentSplit.push(item);
  10138. }
  10139. } else {
  10140. currentSplit.push(item);
  10141. }
  10142. });
  10143. if (currentSplit.length > 0) {
  10144. allSplits.push(currentSplit);
  10145. }
  10146. return map$2(allSplits, function (s) {
  10147. return {
  10148. dom: {
  10149. tag: 'div',
  10150. classes: ['tox-collection__group']
  10151. },
  10152. components: s
  10153. };
  10154. });
  10155. };
  10156. var forCollection = function (columns, initItems, _hasIcons) {
  10157. return {
  10158. dom: {
  10159. tag: 'div',
  10160. classes: [
  10161. 'tox-menu',
  10162. 'tox-collection'
  10163. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  10164. },
  10165. components: [Menu.parts.items({
  10166. preprocess: function (items) {
  10167. if (columns !== 'auto' && columns > 1) {
  10168. return chunk({
  10169. tag: 'div',
  10170. classes: ['tox-collection__group']
  10171. }, columns)(items);
  10172. } else {
  10173. return preprocessCollection(items, function (_item, i) {
  10174. return initItems[i].type === 'separator';
  10175. });
  10176. }
  10177. }
  10178. })]
  10179. };
  10180. };
  10181. var forHorizontalCollection = function (initItems, _hasIcons) {
  10182. return {
  10183. dom: {
  10184. tag: 'div',
  10185. classes: [
  10186. 'tox-collection',
  10187. 'tox-collection--horizontal'
  10188. ]
  10189. },
  10190. components: [Menu.parts.items({
  10191. preprocess: function (items) {
  10192. return preprocessCollection(items, function (_item, i) {
  10193. return initItems[i].type === 'separator';
  10194. });
  10195. }
  10196. })]
  10197. };
  10198. };
  10199. var menuHasIcons = function (xs) {
  10200. return exists(xs, function (item) {
  10201. return 'icon' in item && item.icon !== undefined;
  10202. });
  10203. };
  10204. var handleError = function (error) {
  10205. console.error(formatError(error));
  10206. console.log(error);
  10207. return Optional.none();
  10208. };
  10209. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  10210. var structure = forHorizontalCollection(items);
  10211. return {
  10212. value: value,
  10213. dom: structure.dom,
  10214. components: structure.components,
  10215. items: items
  10216. };
  10217. };
  10218. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  10219. if (presets === 'color') {
  10220. var structure = forSwatch(columns);
  10221. return {
  10222. value: value,
  10223. dom: structure.dom,
  10224. components: structure.components,
  10225. items: items
  10226. };
  10227. }
  10228. if (presets === 'normal' && columns === 'auto') {
  10229. var structure = forCollection(columns, items);
  10230. return {
  10231. value: value,
  10232. dom: structure.dom,
  10233. components: structure.components,
  10234. items: items
  10235. };
  10236. }
  10237. if (presets === 'normal' && columns === 1) {
  10238. var structure = forCollection(1, items);
  10239. return {
  10240. value: value,
  10241. dom: structure.dom,
  10242. components: structure.components,
  10243. items: items
  10244. };
  10245. }
  10246. if (presets === 'normal') {
  10247. var structure = forCollection(columns, items);
  10248. return {
  10249. value: value,
  10250. dom: structure.dom,
  10251. components: structure.components,
  10252. items: items
  10253. };
  10254. }
  10255. if (presets === 'listpreview' && columns !== 'auto') {
  10256. var structure = forToolbar(columns);
  10257. return {
  10258. value: value,
  10259. dom: structure.dom,
  10260. components: structure.components,
  10261. items: items
  10262. };
  10263. }
  10264. return {
  10265. value: value,
  10266. dom: dom$1(hasIcons, columns, presets),
  10267. components: components,
  10268. items: items
  10269. };
  10270. };
  10271. var cardImageFields = [
  10272. requiredString('type'),
  10273. requiredString('src'),
  10274. optionString('alt'),
  10275. defaultedArrayOf('classes', [], string)
  10276. ];
  10277. var cardImageSchema = objOf(cardImageFields);
  10278. var cardTextFields = [
  10279. requiredString('type'),
  10280. requiredString('text'),
  10281. optionString('name'),
  10282. defaultedArrayOf('classes', ['tox-collection__item-label'], string)
  10283. ];
  10284. var cardTextSchema = objOf(cardTextFields);
  10285. var itemSchema$1 = valueThunk(function () {
  10286. return choose$2('type', {
  10287. cardimage: cardImageSchema,
  10288. cardtext: cardTextSchema,
  10289. cardcontainer: cardContainerSchema
  10290. });
  10291. });
  10292. var cardContainerSchema = objOf([
  10293. requiredString('type'),
  10294. defaultedString('direction', 'horizontal'),
  10295. defaultedString('align', 'left'),
  10296. defaultedString('valign', 'middle'),
  10297. requiredArrayOf('items', itemSchema$1)
  10298. ]);
  10299. var commonMenuItemFields = [
  10300. defaultedBoolean('disabled', false),
  10301. optionString('text'),
  10302. optionString('shortcut'),
  10303. field$1('value', 'value', defaultedThunk(function () {
  10304. return generate$6('menuitem-value');
  10305. }), anyValue()),
  10306. defaulted('meta', {})
  10307. ];
  10308. var cardMenuItemSchema = objOf([
  10309. requiredString('type'),
  10310. optionString('label'),
  10311. requiredArrayOf('items', itemSchema$1),
  10312. defaultedFunction('onSetup', function () {
  10313. return noop;
  10314. }),
  10315. defaultedFunction('onAction', noop)
  10316. ].concat(commonMenuItemFields));
  10317. var createCardMenuItem = function (spec) {
  10318. return asRaw('cardmenuitem', cardMenuItemSchema, spec);
  10319. };
  10320. var choiceMenuItemSchema = objOf([
  10321. requiredString('type'),
  10322. defaultedBoolean('active', false),
  10323. optionString('icon')
  10324. ].concat(commonMenuItemFields));
  10325. var createChoiceMenuItem = function (spec) {
  10326. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  10327. };
  10328. var baseFields = [
  10329. requiredString('type'),
  10330. requiredString('fancytype'),
  10331. defaultedFunction('onAction', noop)
  10332. ];
  10333. var insertTableFields = [defaulted('initData', {})].concat(baseFields);
  10334. var colorSwatchFields = [defaultedObjOf('initData', {}, [
  10335. defaultedBoolean('allowCustomColors', true),
  10336. optionArrayOf('colors', anyValue())
  10337. ])].concat(baseFields);
  10338. var fancyMenuItemSchema = choose$1('fancytype', {
  10339. inserttable: insertTableFields,
  10340. colorswatch: colorSwatchFields
  10341. });
  10342. var createFancyMenuItem = function (spec) {
  10343. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  10344. };
  10345. var menuItemSchema = objOf([
  10346. requiredString('type'),
  10347. defaultedFunction('onSetup', function () {
  10348. return noop;
  10349. }),
  10350. defaultedFunction('onAction', noop),
  10351. optionString('icon')
  10352. ].concat(commonMenuItemFields));
  10353. var createMenuItem = function (spec) {
  10354. return asRaw('menuitem', menuItemSchema, spec);
  10355. };
  10356. var nestedMenuItemSchema = objOf([
  10357. requiredString('type'),
  10358. requiredFunction('getSubmenuItems'),
  10359. defaultedFunction('onSetup', function () {
  10360. return noop;
  10361. }),
  10362. optionString('icon')
  10363. ].concat(commonMenuItemFields));
  10364. var createNestedMenuItem = function (spec) {
  10365. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  10366. };
  10367. var toggleMenuItemSchema = objOf([
  10368. requiredString('type'),
  10369. optionString('icon'),
  10370. defaultedBoolean('active', false),
  10371. defaultedFunction('onSetup', function () {
  10372. return noop;
  10373. }),
  10374. requiredFunction('onAction')
  10375. ].concat(commonMenuItemFields));
  10376. var createToggleMenuItem = function (spec) {
  10377. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  10378. };
  10379. var detectSize = function (comp, margin, selectorClass) {
  10380. var descendants$1 = descendants(comp.element, '.' + selectorClass);
  10381. if (descendants$1.length > 0) {
  10382. var columnLength = findIndex$1(descendants$1, function (c) {
  10383. var thisTop = c.dom.getBoundingClientRect().top;
  10384. var cTop = descendants$1[0].dom.getBoundingClientRect().top;
  10385. return Math.abs(thisTop - cTop) > margin;
  10386. }).getOr(descendants$1.length);
  10387. return Optional.some({
  10388. numColumns: columnLength,
  10389. numRows: Math.ceil(descendants$1.length / columnLength)
  10390. });
  10391. } else {
  10392. return Optional.none();
  10393. }
  10394. };
  10395. var namedEvents = function (name, handlers) {
  10396. return derive$1([config(name, handlers)]);
  10397. };
  10398. var unnamedEvents = function (handlers) {
  10399. return namedEvents(generate$6('unnamed-events'), handlers);
  10400. };
  10401. var SimpleBehaviours = {
  10402. namedEvents: namedEvents,
  10403. unnamedEvents: unnamedEvents
  10404. };
  10405. var ExclusivityChannel = generate$6('tooltip.exclusive');
  10406. var ShowTooltipEvent = generate$6('tooltip.show');
  10407. var HideTooltipEvent = generate$6('tooltip.hide');
  10408. var hideAllExclusive = function (component, _tConfig, _tState) {
  10409. component.getSystem().broadcastOn([ExclusivityChannel], {});
  10410. };
  10411. var setComponents = function (component, tConfig, tState, specs) {
  10412. tState.getTooltip().each(function (tooltip) {
  10413. if (tooltip.getSystem().isConnected()) {
  10414. Replacing.set(tooltip, specs);
  10415. }
  10416. });
  10417. };
  10418. var TooltippingApis = /*#__PURE__*/Object.freeze({
  10419. __proto__: null,
  10420. hideAllExclusive: hideAllExclusive,
  10421. setComponents: setComponents
  10422. });
  10423. var events$9 = function (tooltipConfig, state) {
  10424. var hide = function (comp) {
  10425. state.getTooltip().each(function (p) {
  10426. detach(p);
  10427. tooltipConfig.onHide(comp, p);
  10428. state.clearTooltip();
  10429. });
  10430. state.clearTimer();
  10431. };
  10432. var show = function (comp) {
  10433. if (!state.isShowing()) {
  10434. hideAllExclusive(comp);
  10435. var sink = tooltipConfig.lazySink(comp).getOrDie();
  10436. var popup = comp.getSystem().build({
  10437. dom: tooltipConfig.tooltipDom,
  10438. components: tooltipConfig.tooltipComponents,
  10439. events: derive$2(tooltipConfig.mode === 'normal' ? [
  10440. run$1(mouseover(), function (_) {
  10441. emit(comp, ShowTooltipEvent);
  10442. }),
  10443. run$1(mouseout(), function (_) {
  10444. emit(comp, HideTooltipEvent);
  10445. })
  10446. ] : []),
  10447. behaviours: derive$1([Replacing.config({})])
  10448. });
  10449. state.setTooltip(popup);
  10450. attach(sink, popup);
  10451. tooltipConfig.onShow(comp, popup);
  10452. Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
  10453. }
  10454. };
  10455. return derive$2(flatten([
  10456. [
  10457. run$1(ShowTooltipEvent, function (comp) {
  10458. state.resetTimer(function () {
  10459. show(comp);
  10460. }, tooltipConfig.delay);
  10461. }),
  10462. run$1(HideTooltipEvent, function (comp) {
  10463. state.resetTimer(function () {
  10464. hide(comp);
  10465. }, tooltipConfig.delay);
  10466. }),
  10467. run$1(receive(), function (comp, message) {
  10468. var receivingData = message;
  10469. if (!receivingData.universal) {
  10470. if (contains$2(receivingData.channels, ExclusivityChannel)) {
  10471. hide(comp);
  10472. }
  10473. }
  10474. }),
  10475. runOnDetached(function (comp) {
  10476. hide(comp);
  10477. })
  10478. ],
  10479. tooltipConfig.mode === 'normal' ? [
  10480. run$1(focusin(), function (comp) {
  10481. emit(comp, ShowTooltipEvent);
  10482. }),
  10483. run$1(postBlur(), function (comp) {
  10484. emit(comp, HideTooltipEvent);
  10485. }),
  10486. run$1(mouseover(), function (comp) {
  10487. emit(comp, ShowTooltipEvent);
  10488. }),
  10489. run$1(mouseout(), function (comp) {
  10490. emit(comp, HideTooltipEvent);
  10491. })
  10492. ] : [
  10493. run$1(highlight$1(), function (comp, _se) {
  10494. emit(comp, ShowTooltipEvent);
  10495. }),
  10496. run$1(dehighlight$1(), function (comp) {
  10497. emit(comp, HideTooltipEvent);
  10498. })
  10499. ]
  10500. ]));
  10501. };
  10502. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  10503. __proto__: null,
  10504. events: events$9
  10505. });
  10506. var TooltippingSchema = [
  10507. required$1('lazySink'),
  10508. required$1('tooltipDom'),
  10509. defaulted('exclusive', true),
  10510. defaulted('tooltipComponents', []),
  10511. defaulted('delay', 300),
  10512. defaultedStringEnum('mode', 'normal', [
  10513. 'normal',
  10514. 'follow-highlight'
  10515. ]),
  10516. defaulted('anchor', function (comp) {
  10517. return {
  10518. type: 'hotspot',
  10519. hotspot: comp,
  10520. layouts: {
  10521. onLtr: constant$1([
  10522. south$2,
  10523. north$2,
  10524. southeast$2,
  10525. northeast$2,
  10526. southwest$2,
  10527. northwest$2
  10528. ]),
  10529. onRtl: constant$1([
  10530. south$2,
  10531. north$2,
  10532. southeast$2,
  10533. northeast$2,
  10534. southwest$2,
  10535. northwest$2
  10536. ])
  10537. }
  10538. };
  10539. }),
  10540. onHandler('onHide'),
  10541. onHandler('onShow')
  10542. ];
  10543. var init$b = function () {
  10544. var timer = value$1();
  10545. var popup = value$1();
  10546. var clearTimer = function () {
  10547. timer.on(clearTimeout);
  10548. };
  10549. var resetTimer = function (f, delay) {
  10550. clearTimer();
  10551. timer.set(setTimeout(f, delay));
  10552. };
  10553. var readState = constant$1('not-implemented');
  10554. return nu$8({
  10555. getTooltip: popup.get,
  10556. isShowing: popup.isSet,
  10557. setTooltip: popup.set,
  10558. clearTooltip: popup.clear,
  10559. clearTimer: clearTimer,
  10560. resetTimer: resetTimer,
  10561. readState: readState
  10562. });
  10563. };
  10564. var TooltippingState = /*#__PURE__*/Object.freeze({
  10565. __proto__: null,
  10566. init: init$b
  10567. });
  10568. var Tooltipping = create$7({
  10569. fields: TooltippingSchema,
  10570. name: 'tooltipping',
  10571. active: ActiveTooltipping,
  10572. state: TooltippingState,
  10573. apis: TooltippingApis
  10574. });
  10575. var escape = function (text) {
  10576. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10577. };
  10578. var global$c = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  10579. var global$b = tinymce.util.Tools.resolve('tinymce.EditorManager');
  10580. var getSkinUrl = function (editor) {
  10581. var skin = editor.getParam('skin');
  10582. var skinUrl = editor.getParam('skin_url');
  10583. if (skin !== false) {
  10584. var skinName = skin ? skin : 'oxide';
  10585. if (skinUrl) {
  10586. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  10587. } else {
  10588. skinUrl = global$b.baseURL + '/skins/ui/' + skinName;
  10589. }
  10590. }
  10591. return skinUrl;
  10592. };
  10593. var isReadOnly = function (editor) {
  10594. return editor.getParam('readonly', false, 'boolean');
  10595. };
  10596. var isSkinDisabled = function (editor) {
  10597. return editor.getParam('skin') === false;
  10598. };
  10599. var getHeightSetting = function (editor) {
  10600. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  10601. };
  10602. var getWidthSetting = function (editor) {
  10603. return editor.getParam('width', global$c.DOM.getStyle(editor.getElement(), 'width'));
  10604. };
  10605. var getMinWidthSetting = function (editor) {
  10606. return Optional.from(editor.getParam('min_width')).filter(isNumber);
  10607. };
  10608. var getMinHeightSetting = function (editor) {
  10609. return Optional.from(editor.getParam('min_height')).filter(isNumber);
  10610. };
  10611. var getMaxWidthSetting = function (editor) {
  10612. return Optional.from(editor.getParam('max_width')).filter(isNumber);
  10613. };
  10614. var getMaxHeightSetting = function (editor) {
  10615. return Optional.from(editor.getParam('max_height')).filter(isNumber);
  10616. };
  10617. var getUserStyleFormats = function (editor) {
  10618. return Optional.from(editor.getParam('style_formats')).filter(isArray);
  10619. };
  10620. var isMergeStyleFormats = function (editor) {
  10621. return editor.getParam('style_formats_merge', false, 'boolean');
  10622. };
  10623. var getLineHeightFormats = function (editor) {
  10624. return editor.getParam('lineheight_formats', '1 1.1 1.2 1.3 1.4 1.5 2', 'string').split(' ');
  10625. };
  10626. var getContentLanguages = function (editor) {
  10627. return editor.getParam('content_langs', undefined, 'array');
  10628. };
  10629. var getRemovedMenuItems = function (editor) {
  10630. return editor.getParam('removed_menuitems', '');
  10631. };
  10632. var isMenubarEnabled = function (editor) {
  10633. return editor.getParam('menubar', true, 'boolean') !== false;
  10634. };
  10635. var isToolbarEnabled = function (editor) {
  10636. var toolbar = editor.getParam('toolbar', true);
  10637. var isToolbarTrue = toolbar === true;
  10638. var isToolbarString = isString(toolbar);
  10639. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  10640. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  10641. };
  10642. var getMultipleToolbarsSetting = function (editor) {
  10643. var toolbars = range$2(9, function (num) {
  10644. return editor.getParam('toolbar' + (num + 1), false, 'string');
  10645. });
  10646. var toolbarArray = filter$2(toolbars, function (toolbar) {
  10647. return typeof toolbar === 'string';
  10648. });
  10649. return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
  10650. };
  10651. var isMultipleToolbars = function (editor) {
  10652. return getMultipleToolbarsSetting(editor).fold(function () {
  10653. var toolbar = editor.getParam('toolbar', [], 'string[]');
  10654. return toolbar.length > 0;
  10655. }, always);
  10656. };
  10657. var ToolbarMode;
  10658. (function (ToolbarMode) {
  10659. ToolbarMode['default'] = 'wrap';
  10660. ToolbarMode['floating'] = 'floating';
  10661. ToolbarMode['sliding'] = 'sliding';
  10662. ToolbarMode['scrolling'] = 'scrolling';
  10663. }(ToolbarMode || (ToolbarMode = {})));
  10664. var getToolbarMode = function (editor) {
  10665. return editor.getParam('toolbar_mode', '', 'string');
  10666. };
  10667. var ToolbarLocation;
  10668. (function (ToolbarLocation) {
  10669. ToolbarLocation['auto'] = 'auto';
  10670. ToolbarLocation['top'] = 'top';
  10671. ToolbarLocation['bottom'] = 'bottom';
  10672. }(ToolbarLocation || (ToolbarLocation = {})));
  10673. var getToolbarGroups = function (editor) {
  10674. return editor.getParam('toolbar_groups', {}, 'object');
  10675. };
  10676. var getToolbarLocation = function (editor) {
  10677. return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string');
  10678. };
  10679. var isToolbarLocationBottom = function (editor) {
  10680. return getToolbarLocation(editor) === ToolbarLocation.bottom;
  10681. };
  10682. var fixedContainerSelector = function (editor) {
  10683. return editor.getParam('fixed_toolbar_container', '', 'string');
  10684. };
  10685. var fixedToolbarContainerTarget = function (editor) {
  10686. return editor.getParam('fixed_toolbar_container_target');
  10687. };
  10688. var isToolbarPersist = function (editor) {
  10689. return editor.getParam('toolbar_persist', false, 'boolean');
  10690. };
  10691. var fixedContainerTarget = function (editor) {
  10692. if (!editor.inline) {
  10693. return Optional.none();
  10694. }
  10695. var selector = fixedContainerSelector(editor);
  10696. if (selector.length > 0) {
  10697. return descendant(body(), selector);
  10698. }
  10699. var element = fixedToolbarContainerTarget(editor);
  10700. if (isNonNullable(element)) {
  10701. return Optional.some(SugarElement.fromDom(element));
  10702. }
  10703. return Optional.none();
  10704. };
  10705. var useFixedContainer = function (editor) {
  10706. return editor.inline && fixedContainerTarget(editor).isSome();
  10707. };
  10708. var getUiContainer = function (editor) {
  10709. var fixedContainer = fixedContainerTarget(editor);
  10710. return fixedContainer.getOrThunk(function () {
  10711. return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
  10712. });
  10713. };
  10714. var isDistractionFree = function (editor) {
  10715. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  10716. };
  10717. var isStickyToolbar = function (editor) {
  10718. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  10719. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  10720. };
  10721. var getStickyToolbarOffset = function (editor) {
  10722. return editor.getParam('toolbar_sticky_offset', 0, 'number');
  10723. };
  10724. var isDraggableModal$1 = function (editor) {
  10725. return editor.getParam('draggable_modal', false, 'boolean');
  10726. };
  10727. var getMenus = function (editor) {
  10728. var menu = editor.getParam('menu');
  10729. if (menu) {
  10730. return map(menu, function (menu) {
  10731. return __assign(__assign({}, menu), { items: menu.items });
  10732. });
  10733. } else {
  10734. return {};
  10735. }
  10736. };
  10737. var getMenubar = function (editor) {
  10738. return editor.getParam('menubar');
  10739. };
  10740. var getToolbar = function (editor) {
  10741. return editor.getParam('toolbar', true);
  10742. };
  10743. var getFilePickerCallback = function (editor) {
  10744. return editor.getParam('file_picker_callback');
  10745. };
  10746. var getFilePickerTypes = function (editor) {
  10747. return editor.getParam('file_picker_types');
  10748. };
  10749. var getFileBrowserCallbackTypes = function (editor) {
  10750. return editor.getParam('file_browser_callback_types');
  10751. };
  10752. var noTypeaheadUrls = function (editor) {
  10753. return editor.getParam('typeahead_urls') === false;
  10754. };
  10755. var getAnchorTop = function (editor) {
  10756. return editor.getParam('anchor_top', '#top');
  10757. };
  10758. var getAnchorBottom = function (editor) {
  10759. return editor.getParam('anchor_bottom', '#bottom');
  10760. };
  10761. var getFilePickerValidatorHandler = function (editor) {
  10762. var handler = editor.getParam('file_picker_validator_handler', undefined, 'function');
  10763. if (handler === undefined) {
  10764. return editor.getParam('filepicker_validator_handler', undefined, 'function');
  10765. } else {
  10766. return handler;
  10767. }
  10768. };
  10769. var ReadOnlyChannel = 'silver.readonly';
  10770. var ReadOnlyDataSchema = objOf([requiredBoolean('readonly')]);
  10771. var broadcastReadonly = function (uiComponents, readonly) {
  10772. var outerContainer = uiComponents.outerContainer;
  10773. var target = outerContainer.element;
  10774. if (readonly) {
  10775. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  10776. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  10777. }
  10778. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10779. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10780. };
  10781. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  10782. editor.on('init', function () {
  10783. if (editor.mode.isReadOnly()) {
  10784. broadcastReadonly(uiComponents, true);
  10785. }
  10786. });
  10787. editor.on('SwitchMode', function () {
  10788. return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
  10789. });
  10790. if (isReadOnly(editor)) {
  10791. editor.setMode('readonly');
  10792. }
  10793. };
  10794. var receivingConfig = function () {
  10795. var _a;
  10796. return Receiving.config({
  10797. channels: (_a = {}, _a[ReadOnlyChannel] = {
  10798. schema: ReadOnlyDataSchema,
  10799. onReceive: function (comp, data) {
  10800. Disabling.set(comp, data.readonly);
  10801. }
  10802. }, _a)
  10803. });
  10804. };
  10805. var item = function (disabled) {
  10806. return Disabling.config({
  10807. disabled: disabled,
  10808. disableClass: 'tox-collection__item--state-disabled'
  10809. });
  10810. };
  10811. var button = function (disabled) {
  10812. return Disabling.config({ disabled: disabled });
  10813. };
  10814. var splitButton = function (disabled) {
  10815. return Disabling.config({
  10816. disabled: disabled,
  10817. disableClass: 'tox-tbtn--disabled'
  10818. });
  10819. };
  10820. var toolbarButton = function (disabled) {
  10821. return Disabling.config({
  10822. disabled: disabled,
  10823. disableClass: 'tox-tbtn--disabled',
  10824. useNative: false
  10825. });
  10826. };
  10827. var DisablingConfigs = {
  10828. item: item,
  10829. button: button,
  10830. splitButton: splitButton,
  10831. toolbarButton: toolbarButton
  10832. };
  10833. var runWithApi = function (info, comp) {
  10834. var api = info.getApi(comp);
  10835. return function (f) {
  10836. f(api);
  10837. };
  10838. };
  10839. var onControlAttached = function (info, editorOffCell) {
  10840. return runOnAttached(function (comp) {
  10841. var run = runWithApi(info, comp);
  10842. run(function (api) {
  10843. var onDestroy = info.onSetup(api);
  10844. if (isFunction(onDestroy)) {
  10845. editorOffCell.set(onDestroy);
  10846. }
  10847. });
  10848. });
  10849. };
  10850. var onControlDetached = function (getApi, editorOffCell) {
  10851. return runOnDetached(function (comp) {
  10852. return runWithApi(getApi, comp)(editorOffCell.get());
  10853. });
  10854. };
  10855. var _a$1;
  10856. var onMenuItemExecute = function (info, itemResponse) {
  10857. return runOnExecute$1(function (comp, simulatedEvent) {
  10858. runWithApi(info, comp)(info.onAction);
  10859. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10860. emit(comp, sandboxClose());
  10861. simulatedEvent.stop();
  10862. }
  10863. });
  10864. };
  10865. var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [
  10866. 'disabling',
  10867. 'alloy.base.behaviour',
  10868. 'toggling',
  10869. 'item-events'
  10870. ], _a$1);
  10871. var componentRenderPipeline = cat;
  10872. var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) {
  10873. var editorOffCell = Cell(noop);
  10874. return {
  10875. type: 'item',
  10876. dom: structure.dom,
  10877. components: componentRenderPipeline(structure.optComponents),
  10878. data: spec.data,
  10879. eventOrder: menuItemEventOrder,
  10880. hasSubmenu: spec.triggersSubmenu,
  10881. itemBehaviours: derive$1([
  10882. config('item-events', [
  10883. onMenuItemExecute(spec, itemResponse),
  10884. onControlAttached(spec, editorOffCell),
  10885. onControlDetached(spec, editorOffCell)
  10886. ]),
  10887. DisablingConfigs.item(function () {
  10888. return spec.disabled || providersbackstage.isDisabled();
  10889. }),
  10890. receivingConfig(),
  10891. Replacing.config({})
  10892. ].concat(spec.itemBehaviours))
  10893. };
  10894. };
  10895. var buildData = function (source) {
  10896. return {
  10897. value: source.value,
  10898. meta: __assign({ text: source.text.getOr('') }, source.meta)
  10899. };
  10900. };
  10901. var global$a = tinymce.util.Tools.resolve('tinymce.Env');
  10902. var convertText = function (source) {
  10903. var mac = {
  10904. alt: '&#x2325;',
  10905. ctrl: '&#x2303;',
  10906. shift: '&#x21E7;',
  10907. meta: '&#x2318;',
  10908. access: '&#x2303;&#x2325;'
  10909. };
  10910. var other = {
  10911. meta: 'Ctrl',
  10912. access: 'Shift+Alt'
  10913. };
  10914. var replace = global$a.mac ? mac : other;
  10915. var shortcut = source.split('+');
  10916. var updated = map$2(shortcut, function (segment) {
  10917. var search = segment.toLowerCase().trim();
  10918. return has$2(replace, search) ? replace[search] : segment;
  10919. });
  10920. return global$a.mac ? updated.join('') : updated.join('+');
  10921. };
  10922. var renderIcon$1 = function (name, icons, classes) {
  10923. if (classes === void 0) {
  10924. classes = [iconClass];
  10925. }
  10926. return render$3(name, {
  10927. tag: 'div',
  10928. classes: classes
  10929. }, icons);
  10930. };
  10931. var renderText = function (text$1) {
  10932. return {
  10933. dom: {
  10934. tag: 'div',
  10935. classes: [textClass]
  10936. },
  10937. components: [text(global$f.translate(text$1))]
  10938. };
  10939. };
  10940. var renderHtml = function (html, classes) {
  10941. return {
  10942. dom: {
  10943. tag: 'div',
  10944. classes: classes,
  10945. innerHtml: html
  10946. }
  10947. };
  10948. };
  10949. var renderStyledText = function (style, text$1) {
  10950. return {
  10951. dom: {
  10952. tag: 'div',
  10953. classes: [textClass]
  10954. },
  10955. components: [{
  10956. dom: {
  10957. tag: style.tag,
  10958. styles: style.styles
  10959. },
  10960. components: [text(global$f.translate(text$1))]
  10961. }]
  10962. };
  10963. };
  10964. var renderShortcut = function (shortcut) {
  10965. return {
  10966. dom: {
  10967. tag: 'div',
  10968. classes: [accessoryClass],
  10969. innerHtml: convertText(shortcut)
  10970. }
  10971. };
  10972. };
  10973. var renderCheckmark = function (icons) {
  10974. return renderIcon$1('checkmark', icons, [checkmarkClass]);
  10975. };
  10976. var renderSubmenuCaret = function (icons) {
  10977. return renderIcon$1('chevron-right', icons, [caretClass]);
  10978. };
  10979. var renderDownwardsCaret = function (icons) {
  10980. return renderIcon$1('chevron-down', icons, [caretClass]);
  10981. };
  10982. var renderContainer = function (container, components) {
  10983. var directionClass = container.direction === 'vertical' ? containerColumnClass : containerRowClass;
  10984. var alignClass = container.align === 'left' ? containerAlignLeftClass : containerAlignRightClass;
  10985. var getValignClass = function () {
  10986. switch (container.valign) {
  10987. case 'top':
  10988. return containerValignTopClass;
  10989. case 'middle':
  10990. return containerValignMiddleClass;
  10991. case 'bottom':
  10992. return containerValignBottomClass;
  10993. }
  10994. };
  10995. return {
  10996. dom: {
  10997. tag: 'div',
  10998. classes: [
  10999. containerClass,
  11000. directionClass,
  11001. alignClass,
  11002. getValignClass()
  11003. ]
  11004. },
  11005. components: components
  11006. };
  11007. };
  11008. var renderImage = function (src, classes, alt) {
  11009. return {
  11010. dom: {
  11011. tag: 'img',
  11012. classes: classes,
  11013. attributes: {
  11014. src: src,
  11015. alt: alt.getOr('')
  11016. }
  11017. }
  11018. };
  11019. };
  11020. var renderColorStructure = function (item, providerBackstage, fallbackIcon) {
  11021. var colorPickerCommand = 'custom';
  11022. var removeColorCommand = 'remove';
  11023. var itemText = item.ariaLabel;
  11024. var itemValue = item.value;
  11025. var iconSvg = item.iconContent.map(function (name) {
  11026. return getOr(name, providerBackstage.icons, fallbackIcon);
  11027. });
  11028. var getDom = function () {
  11029. var common = colorClass;
  11030. var icon = iconSvg.getOr('');
  11031. var attributes = itemText.map(function (text) {
  11032. return { title: providerBackstage.translate(text) };
  11033. }).getOr({});
  11034. var baseDom = {
  11035. tag: 'div',
  11036. attributes: attributes,
  11037. classes: [common]
  11038. };
  11039. if (itemValue === colorPickerCommand) {
  11040. return __assign(__assign({}, baseDom), {
  11041. tag: 'button',
  11042. classes: __spreadArray(__spreadArray([], baseDom.classes), ['tox-swatches__picker-btn']),
  11043. innerHtml: icon
  11044. });
  11045. } else if (itemValue === removeColorCommand) {
  11046. return __assign(__assign({}, baseDom), {
  11047. classes: __spreadArray(__spreadArray([], baseDom.classes), ['tox-swatch--remove']),
  11048. innerHtml: icon
  11049. });
  11050. } else {
  11051. return __assign(__assign({}, baseDom), {
  11052. attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  11053. styles: { 'background-color': itemValue }
  11054. });
  11055. }
  11056. };
  11057. return {
  11058. dom: getDom(),
  11059. optComponents: []
  11060. };
  11061. };
  11062. var renderItemDomStructure = function (ariaLabel) {
  11063. var domTitle = ariaLabel.map(function (label) {
  11064. return { attributes: { title: global$f.translate(label) } };
  11065. }).getOr({});
  11066. return __assign({
  11067. tag: 'div',
  11068. classes: [
  11069. navClass,
  11070. selectableClass
  11071. ]
  11072. }, domTitle);
  11073. };
  11074. var renderNormalItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  11075. var iconSpec = {
  11076. tag: 'div',
  11077. classes: [iconClass]
  11078. };
  11079. var renderIcon = function (iconName) {
  11080. return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
  11081. };
  11082. var renderEmptyIcon = function () {
  11083. return Optional.some({ dom: iconSpec });
  11084. };
  11085. var leftIcon = renderIcons ? info.iconContent.map(renderIcon).orThunk(renderEmptyIcon) : Optional.none();
  11086. var checkmark = info.checkMark;
  11087. var textRender = Optional.from(info.meta).fold(function () {
  11088. return renderText;
  11089. }, function (meta) {
  11090. return has$2(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  11091. });
  11092. var content = info.htmlContent.fold(function () {
  11093. return info.textContent.map(textRender);
  11094. }, function (html) {
  11095. return Optional.some(renderHtml(html, [textClass]));
  11096. });
  11097. var menuItem = {
  11098. dom: renderItemDomStructure(info.ariaLabel),
  11099. optComponents: [
  11100. leftIcon,
  11101. content,
  11102. info.shortcutContent.map(renderShortcut),
  11103. checkmark,
  11104. info.caret
  11105. ]
  11106. };
  11107. return menuItem;
  11108. };
  11109. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  11110. if (fallbackIcon === void 0) {
  11111. fallbackIcon = Optional.none();
  11112. }
  11113. if (info.presets === 'color') {
  11114. return renderColorStructure(info, providersBackstage, fallbackIcon);
  11115. } else {
  11116. return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
  11117. }
  11118. };
  11119. var tooltipBehaviour = function (meta, sharedBackstage) {
  11120. return get$e(meta, 'tooltipWorker').map(function (tooltipWorker) {
  11121. return [Tooltipping.config({
  11122. lazySink: sharedBackstage.getSink,
  11123. tooltipDom: {
  11124. tag: 'div',
  11125. classes: ['tox-tooltip-worker-container']
  11126. },
  11127. tooltipComponents: [],
  11128. anchor: function (comp) {
  11129. return {
  11130. type: 'submenu',
  11131. item: comp,
  11132. overrides: { maxHeightFunction: expandable$1 }
  11133. };
  11134. },
  11135. mode: 'follow-highlight',
  11136. onShow: function (component, _tooltip) {
  11137. tooltipWorker(function (elm) {
  11138. Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]);
  11139. });
  11140. }
  11141. })];
  11142. }).getOr([]);
  11143. };
  11144. var encodeText = function (text) {
  11145. return global$c.DOM.encode(text);
  11146. };
  11147. var replaceText = function (text, matchText) {
  11148. var translated = global$f.translate(text);
  11149. var encoded = encodeText(translated);
  11150. if (matchText.length > 0) {
  11151. var escapedMatchRegex = new RegExp(escape(matchText), 'gi');
  11152. return encoded.replace(escapedMatchRegex, function (match) {
  11153. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  11154. });
  11155. } else {
  11156. return encoded;
  11157. }
  11158. };
  11159. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  11160. if (renderIcons === void 0) {
  11161. renderIcons = true;
  11162. }
  11163. var structure = renderItemStructure({
  11164. presets: presets,
  11165. textContent: Optional.none(),
  11166. htmlContent: useText ? spec.text.map(function (text) {
  11167. return replaceText(text, matchText);
  11168. }) : Optional.none(),
  11169. ariaLabel: spec.text,
  11170. iconContent: spec.icon,
  11171. shortcutContent: Optional.none(),
  11172. checkMark: Optional.none(),
  11173. caret: Optional.none(),
  11174. value: spec.value
  11175. }, sharedBackstage.providers, renderIcons, spec.icon);
  11176. return renderCommonItem({
  11177. data: buildData(spec),
  11178. disabled: spec.disabled,
  11179. getApi: constant$1({}),
  11180. onAction: function (_api) {
  11181. return onItemValueHandler(spec.value, spec.meta);
  11182. },
  11183. onSetup: constant$1(noop),
  11184. triggersSubmenu: false,
  11185. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  11186. }, structure, itemResponse, sharedBackstage.providers);
  11187. };
  11188. var render$2 = function (items, extras) {
  11189. return map$2(items, function (item) {
  11190. switch (item.type) {
  11191. case 'cardcontainer':
  11192. return renderContainer(item, render$2(item.items, extras));
  11193. case 'cardimage':
  11194. return renderImage(item.src, item.classes, item.alt);
  11195. case 'cardtext':
  11196. var shouldHighlight = item.name.exists(function (name) {
  11197. return contains$2(extras.cardText.highlightOn, name);
  11198. });
  11199. var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr('') : '';
  11200. return renderHtml(replaceText(item.text, matchText), item.classes);
  11201. }
  11202. });
  11203. };
  11204. var renderCardMenuItem = function (spec, itemResponse, sharedBackstage, extras) {
  11205. var getApi = function (component) {
  11206. return {
  11207. isDisabled: function () {
  11208. return Disabling.isDisabled(component);
  11209. },
  11210. setDisabled: function (state) {
  11211. Disabling.set(component, state);
  11212. each$1(descendants(component.element, '*'), function (elm) {
  11213. component.getSystem().getByDom(elm).each(function (comp) {
  11214. if (comp.hasConfigured(Disabling)) {
  11215. Disabling.set(comp, state);
  11216. }
  11217. });
  11218. });
  11219. }
  11220. };
  11221. };
  11222. var structure = {
  11223. dom: renderItemDomStructure(spec.label),
  11224. optComponents: [Optional.some({
  11225. dom: {
  11226. tag: 'div',
  11227. classes: [
  11228. containerClass,
  11229. containerRowClass
  11230. ]
  11231. },
  11232. components: render$2(spec.items, extras)
  11233. })]
  11234. };
  11235. return renderCommonItem({
  11236. data: buildData(__assign({ text: Optional.none() }, spec)),
  11237. disabled: spec.disabled,
  11238. getApi: getApi,
  11239. onAction: spec.onAction,
  11240. onSetup: spec.onSetup,
  11241. triggersSubmenu: false,
  11242. itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
  11243. }, structure, itemResponse, sharedBackstage.providers);
  11244. };
  11245. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
  11246. if (renderIcons === void 0) {
  11247. renderIcons = true;
  11248. }
  11249. var getApi = function (component) {
  11250. return {
  11251. setActive: function (state) {
  11252. Toggling.set(component, state);
  11253. },
  11254. isActive: function () {
  11255. return Toggling.isOn(component);
  11256. },
  11257. isDisabled: function () {
  11258. return Disabling.isDisabled(component);
  11259. },
  11260. setDisabled: function (state) {
  11261. return Disabling.set(component, state);
  11262. }
  11263. };
  11264. };
  11265. var structure = renderItemStructure({
  11266. presets: presets,
  11267. textContent: useText ? spec.text : Optional.none(),
  11268. htmlContent: Optional.none(),
  11269. ariaLabel: spec.text,
  11270. iconContent: spec.icon,
  11271. shortcutContent: useText ? spec.shortcut : Optional.none(),
  11272. checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
  11273. caret: Optional.none(),
  11274. value: spec.value
  11275. }, providersBackstage, renderIcons);
  11276. return deepMerge(renderCommonItem({
  11277. data: buildData(spec),
  11278. disabled: spec.disabled,
  11279. getApi: getApi,
  11280. onAction: function (_api) {
  11281. return onItemValueHandler(spec.value);
  11282. },
  11283. onSetup: function (api) {
  11284. api.setActive(isSelected);
  11285. return noop;
  11286. },
  11287. triggersSubmenu: false,
  11288. itemBehaviours: []
  11289. }, structure, itemResponse, providersBackstage), {
  11290. toggling: {
  11291. toggleClass: tickedClass,
  11292. toggleOnExecute: false,
  11293. selected: spec.active
  11294. }
  11295. });
  11296. };
  11297. var parts$f = generate$3(owner$2(), parts$h());
  11298. var hexColour = function (value) {
  11299. return { value: value };
  11300. };
  11301. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  11302. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  11303. var isHexString = function (hex) {
  11304. return shorthandRegex.test(hex) || longformRegex.test(hex);
  11305. };
  11306. var normalizeHex = function (hex) {
  11307. return removeLeading(hex, '#').toUpperCase();
  11308. };
  11309. var fromString$1 = function (hex) {
  11310. return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  11311. };
  11312. var getLongForm = function (hex) {
  11313. var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) {
  11314. return r + r + g + g + b + b;
  11315. });
  11316. return { value: hexString };
  11317. };
  11318. var extractValues = function (hex) {
  11319. var longForm = getLongForm(hex);
  11320. var splitForm = longformRegex.exec(longForm.value);
  11321. return splitForm === null ? [
  11322. 'FFFFFF',
  11323. 'FF',
  11324. 'FF',
  11325. 'FF'
  11326. ] : splitForm;
  11327. };
  11328. var toHex = function (component) {
  11329. var hex = component.toString(16);
  11330. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  11331. };
  11332. var fromRgba = function (rgbaColour) {
  11333. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  11334. return hexColour(value);
  11335. };
  11336. var min = Math.min;
  11337. var max = Math.max;
  11338. var round$1 = Math.round;
  11339. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  11340. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  11341. var rgbaColour = function (red, green, blue, alpha) {
  11342. return {
  11343. red: red,
  11344. green: green,
  11345. blue: blue,
  11346. alpha: alpha
  11347. };
  11348. };
  11349. var isRgbaComponent = function (value) {
  11350. var num = parseInt(value, 10);
  11351. return num.toString() === value && num >= 0 && num <= 255;
  11352. };
  11353. var fromHsv = function (hsv) {
  11354. var r;
  11355. var g;
  11356. var b;
  11357. var hue = (hsv.hue || 0) % 360;
  11358. var saturation = hsv.saturation / 100;
  11359. var brightness = hsv.value / 100;
  11360. saturation = max(0, min(saturation, 1));
  11361. brightness = max(0, min(brightness, 1));
  11362. if (saturation === 0) {
  11363. r = g = b = round$1(255 * brightness);
  11364. return rgbaColour(r, g, b, 1);
  11365. }
  11366. var side = hue / 60;
  11367. var chroma = brightness * saturation;
  11368. var x = chroma * (1 - Math.abs(side % 2 - 1));
  11369. var match = brightness - chroma;
  11370. switch (Math.floor(side)) {
  11371. case 0:
  11372. r = chroma;
  11373. g = x;
  11374. b = 0;
  11375. break;
  11376. case 1:
  11377. r = x;
  11378. g = chroma;
  11379. b = 0;
  11380. break;
  11381. case 2:
  11382. r = 0;
  11383. g = chroma;
  11384. b = x;
  11385. break;
  11386. case 3:
  11387. r = 0;
  11388. g = x;
  11389. b = chroma;
  11390. break;
  11391. case 4:
  11392. r = x;
  11393. g = 0;
  11394. b = chroma;
  11395. break;
  11396. case 5:
  11397. r = chroma;
  11398. g = 0;
  11399. b = x;
  11400. break;
  11401. default:
  11402. r = g = b = 0;
  11403. }
  11404. r = round$1(255 * (r + match));
  11405. g = round$1(255 * (g + match));
  11406. b = round$1(255 * (b + match));
  11407. return rgbaColour(r, g, b, 1);
  11408. };
  11409. var fromHex = function (hexColour) {
  11410. var result = extractValues(hexColour);
  11411. var red = parseInt(result[1], 16);
  11412. var green = parseInt(result[2], 16);
  11413. var blue = parseInt(result[3], 16);
  11414. return rgbaColour(red, green, blue, 1);
  11415. };
  11416. var fromStringValues = function (red, green, blue, alpha) {
  11417. var r = parseInt(red, 10);
  11418. var g = parseInt(green, 10);
  11419. var b = parseInt(blue, 10);
  11420. var a = parseFloat(alpha);
  11421. return rgbaColour(r, g, b, a);
  11422. };
  11423. var fromString = function (rgbaString) {
  11424. if (rgbaString === 'transparent') {
  11425. return Optional.some(rgbaColour(0, 0, 0, 0));
  11426. }
  11427. var rgbMatch = rgbRegex.exec(rgbaString);
  11428. if (rgbMatch !== null) {
  11429. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  11430. }
  11431. var rgbaMatch = rgbaRegex.exec(rgbaString);
  11432. if (rgbaMatch !== null) {
  11433. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  11434. }
  11435. return Optional.none();
  11436. };
  11437. var toString = function (rgba) {
  11438. return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')';
  11439. };
  11440. var red = rgbaColour(255, 0, 0, 1);
  11441. var fireSkinLoaded$1 = function (editor) {
  11442. return editor.fire('SkinLoaded');
  11443. };
  11444. var fireSkinLoadError$1 = function (editor, error) {
  11445. return editor.fire('SkinLoadError', error);
  11446. };
  11447. var fireResizeEditor = function (editor) {
  11448. return editor.fire('ResizeEditor');
  11449. };
  11450. var fireResizeContent = function (editor, e) {
  11451. return editor.fire('ResizeContent', e);
  11452. };
  11453. var fireScrollContent = function (editor, e) {
  11454. return editor.fire('ScrollContent', e);
  11455. };
  11456. var fireTextColorChange = function (editor, data) {
  11457. return editor.fire('TextColorChange', data);
  11458. };
  11459. var hsvColour = function (hue, saturation, value) {
  11460. return {
  11461. hue: hue,
  11462. saturation: saturation,
  11463. value: value
  11464. };
  11465. };
  11466. var fromRgb = function (rgbaColour) {
  11467. var h = 0;
  11468. var s = 0;
  11469. var v = 0;
  11470. var r = rgbaColour.red / 255;
  11471. var g = rgbaColour.green / 255;
  11472. var b = rgbaColour.blue / 255;
  11473. var minRGB = Math.min(r, Math.min(g, b));
  11474. var maxRGB = Math.max(r, Math.max(g, b));
  11475. if (minRGB === maxRGB) {
  11476. v = minRGB;
  11477. return hsvColour(0, 0, v * 100);
  11478. }
  11479. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  11480. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  11481. h = 60 * (h - d / (maxRGB - minRGB));
  11482. s = (maxRGB - minRGB) / maxRGB;
  11483. v = maxRGB;
  11484. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  11485. };
  11486. var hexToHsv = function (hex) {
  11487. return fromRgb(fromHex(hex));
  11488. };
  11489. var hsvToHex = function (hsv) {
  11490. return fromRgba(fromHsv(hsv));
  11491. };
  11492. var anyToHex = function (color) {
  11493. return fromString$1(color).orThunk(function () {
  11494. return fromString(color).map(fromRgba);
  11495. }).getOrThunk(function () {
  11496. var canvas = document.createElement('canvas');
  11497. canvas.height = 1;
  11498. canvas.width = 1;
  11499. var canvasContext = canvas.getContext('2d');
  11500. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  11501. canvasContext.fillStyle = '#FFFFFF';
  11502. canvasContext.fillStyle = color;
  11503. canvasContext.fillRect(0, 0, 1, 1);
  11504. var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  11505. var r = rgba[0];
  11506. var g = rgba[1];
  11507. var b = rgba[2];
  11508. var a = rgba[3];
  11509. return fromRgba(rgbaColour(r, g, b, a));
  11510. });
  11511. };
  11512. var global$9 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  11513. var storageName = 'tinymce-custom-colors';
  11514. function ColorCache (max) {
  11515. if (max === void 0) {
  11516. max = 10;
  11517. }
  11518. var storageString = global$9.getItem(storageName);
  11519. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  11520. var prune = function (list) {
  11521. var diff = max - list.length;
  11522. return diff < 0 ? list.slice(0, max) : list;
  11523. };
  11524. var cache = prune(localstorage);
  11525. var add = function (key) {
  11526. indexOf(cache, key).each(remove);
  11527. cache.unshift(key);
  11528. if (cache.length > max) {
  11529. cache.pop();
  11530. }
  11531. global$9.setItem(storageName, JSON.stringify(cache));
  11532. };
  11533. var remove = function (idx) {
  11534. cache.splice(idx, 1);
  11535. };
  11536. var state = function () {
  11537. return cache.slice(0);
  11538. };
  11539. return {
  11540. add: add,
  11541. state: state
  11542. };
  11543. }
  11544. var choiceItem = 'choiceitem';
  11545. var defaultColors = [
  11546. {
  11547. type: choiceItem,
  11548. text: 'Light Green',
  11549. value: '#BFEDD2'
  11550. },
  11551. {
  11552. type: choiceItem,
  11553. text: 'Light Yellow',
  11554. value: '#FBEEB8'
  11555. },
  11556. {
  11557. type: choiceItem,
  11558. text: 'Light Red',
  11559. value: '#F8CAC6'
  11560. },
  11561. {
  11562. type: choiceItem,
  11563. text: 'Light Purple',
  11564. value: '#ECCAFA'
  11565. },
  11566. {
  11567. type: choiceItem,
  11568. text: 'Light Blue',
  11569. value: '#C2E0F4'
  11570. },
  11571. {
  11572. type: choiceItem,
  11573. text: 'Green',
  11574. value: '#2DC26B'
  11575. },
  11576. {
  11577. type: choiceItem,
  11578. text: 'Yellow',
  11579. value: '#F1C40F'
  11580. },
  11581. {
  11582. type: choiceItem,
  11583. text: 'Red',
  11584. value: '#E03E2D'
  11585. },
  11586. {
  11587. type: choiceItem,
  11588. text: 'Purple',
  11589. value: '#B96AD9'
  11590. },
  11591. {
  11592. type: choiceItem,
  11593. text: 'Blue',
  11594. value: '#3598DB'
  11595. },
  11596. {
  11597. type: choiceItem,
  11598. text: 'Dark Turquoise',
  11599. value: '#169179'
  11600. },
  11601. {
  11602. type: choiceItem,
  11603. text: 'Orange',
  11604. value: '#E67E23'
  11605. },
  11606. {
  11607. type: choiceItem,
  11608. text: 'Dark Red',
  11609. value: '#BA372A'
  11610. },
  11611. {
  11612. type: choiceItem,
  11613. text: 'Dark Purple',
  11614. value: '#843FA1'
  11615. },
  11616. {
  11617. type: choiceItem,
  11618. text: 'Dark Blue',
  11619. value: '#236FA1'
  11620. },
  11621. {
  11622. type: choiceItem,
  11623. text: 'Light Gray',
  11624. value: '#ECF0F1'
  11625. },
  11626. {
  11627. type: choiceItem,
  11628. text: 'Medium Gray',
  11629. value: '#CED4D9'
  11630. },
  11631. {
  11632. type: choiceItem,
  11633. text: 'Gray',
  11634. value: '#95A5A6'
  11635. },
  11636. {
  11637. type: choiceItem,
  11638. text: 'Dark Gray',
  11639. value: '#7E8C8D'
  11640. },
  11641. {
  11642. type: choiceItem,
  11643. text: 'Navy Blue',
  11644. value: '#34495E'
  11645. },
  11646. {
  11647. type: choiceItem,
  11648. text: 'Black',
  11649. value: '#000000'
  11650. },
  11651. {
  11652. type: choiceItem,
  11653. text: 'White',
  11654. value: '#ffffff'
  11655. }
  11656. ];
  11657. var colorCache = ColorCache(10);
  11658. var mapColors = function (colorMap) {
  11659. var colors = [];
  11660. for (var i = 0; i < colorMap.length; i += 2) {
  11661. colors.push({
  11662. text: colorMap[i + 1],
  11663. value: '#' + anyToHex(colorMap[i]).value,
  11664. type: 'choiceitem'
  11665. });
  11666. }
  11667. return colors;
  11668. };
  11669. var getColorCols$2 = function (editor, defaultCols) {
  11670. return editor.getParam('color_cols', defaultCols, 'number');
  11671. };
  11672. var hasCustomColors$1 = function (editor) {
  11673. return editor.getParam('custom_colors') !== false;
  11674. };
  11675. var getColorMap = function (editor) {
  11676. return editor.getParam('color_map');
  11677. };
  11678. var getColors$2 = function (editor) {
  11679. var unmapped = getColorMap(editor);
  11680. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  11681. };
  11682. var getCurrentColors = function () {
  11683. return map$2(colorCache.state(), function (color) {
  11684. return {
  11685. type: choiceItem,
  11686. text: color,
  11687. value: color
  11688. };
  11689. });
  11690. };
  11691. var addColor = function (color) {
  11692. colorCache.add(color);
  11693. };
  11694. var getCurrentColor = function (editor, format) {
  11695. var color;
  11696. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  11697. var value;
  11698. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  11699. color = color ? color : value;
  11700. }
  11701. });
  11702. return color;
  11703. };
  11704. var applyFormat = function (editor, format, value) {
  11705. editor.undoManager.transact(function () {
  11706. editor.focus();
  11707. editor.formatter.apply(format, { value: value });
  11708. editor.nodeChanged();
  11709. });
  11710. };
  11711. var removeFormat = function (editor, format) {
  11712. editor.undoManager.transact(function () {
  11713. editor.focus();
  11714. editor.formatter.remove(format, { value: null }, null, true);
  11715. editor.nodeChanged();
  11716. });
  11717. };
  11718. var registerCommands = function (editor) {
  11719. editor.addCommand('mceApplyTextcolor', function (format, value) {
  11720. applyFormat(editor, format, value);
  11721. });
  11722. editor.addCommand('mceRemoveTextcolor', function (format) {
  11723. removeFormat(editor, format);
  11724. });
  11725. };
  11726. var calcCols = function (colors) {
  11727. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  11728. };
  11729. var getColorCols$1 = function (editor) {
  11730. var colors = getColors$2(editor);
  11731. var defaultCols = calcCols(colors.length);
  11732. return getColorCols$2(editor, defaultCols);
  11733. };
  11734. var getAdditionalColors = function (hasCustom) {
  11735. var type = 'choiceitem';
  11736. var remove = {
  11737. type: type,
  11738. text: 'Remove color',
  11739. icon: 'color-swatch-remove-color',
  11740. value: 'remove'
  11741. };
  11742. var custom = {
  11743. type: type,
  11744. text: 'Custom color',
  11745. icon: 'color-picker',
  11746. value: 'custom'
  11747. };
  11748. return hasCustom ? [
  11749. remove,
  11750. custom
  11751. ] : [remove];
  11752. };
  11753. var applyColor = function (editor, format, value, onChoice) {
  11754. if (value === 'custom') {
  11755. var dialog = colorPickerDialog(editor);
  11756. dialog(function (colorOpt) {
  11757. colorOpt.each(function (color) {
  11758. addColor(color);
  11759. editor.execCommand('mceApplyTextcolor', format, color);
  11760. onChoice(color);
  11761. });
  11762. }, '#000000');
  11763. } else if (value === 'remove') {
  11764. onChoice('');
  11765. editor.execCommand('mceRemoveTextcolor', format);
  11766. } else {
  11767. onChoice(value);
  11768. editor.execCommand('mceApplyTextcolor', format, value);
  11769. }
  11770. };
  11771. var getColors$1 = function (colors, hasCustom) {
  11772. return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  11773. };
  11774. var getFetch$1 = function (colors, hasCustom) {
  11775. return function (callback) {
  11776. callback(getColors$1(colors, hasCustom));
  11777. };
  11778. };
  11779. var setIconColor = function (splitButtonApi, name, newColor) {
  11780. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  11781. splitButtonApi.setIconFill(id, newColor);
  11782. };
  11783. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  11784. editor.ui.registry.addSplitButton(name, {
  11785. tooltip: tooltip,
  11786. presets: 'color',
  11787. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11788. select: function (value) {
  11789. var optCurrentRgb = Optional.from(getCurrentColor(editor, format));
  11790. return optCurrentRgb.bind(function (currentRgb) {
  11791. return fromString(currentRgb).map(function (rgba) {
  11792. var currentHex = fromRgba(rgba).value;
  11793. return contains$1(value.toLowerCase(), currentHex);
  11794. });
  11795. }).getOr(false);
  11796. },
  11797. columns: getColorCols$1(editor),
  11798. fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
  11799. onAction: function (_splitButtonApi) {
  11800. if (lastColor.get() !== null) {
  11801. applyColor(editor, format, lastColor.get(), noop);
  11802. }
  11803. },
  11804. onItemAction: function (_splitButtonApi, value) {
  11805. applyColor(editor, format, value, function (newColor) {
  11806. lastColor.set(newColor);
  11807. fireTextColorChange(editor, {
  11808. name: name,
  11809. color: newColor
  11810. });
  11811. });
  11812. },
  11813. onSetup: function (splitButtonApi) {
  11814. if (lastColor.get() !== null) {
  11815. setIconColor(splitButtonApi, name, lastColor.get());
  11816. }
  11817. var handler = function (e) {
  11818. if (e.name === name) {
  11819. setIconColor(splitButtonApi, e.name, e.color);
  11820. }
  11821. };
  11822. editor.on('TextColorChange', handler);
  11823. return function () {
  11824. editor.off('TextColorChange', handler);
  11825. };
  11826. }
  11827. });
  11828. };
  11829. var registerTextColorMenuItem = function (editor, name, format, text) {
  11830. editor.ui.registry.addNestedMenuItem(name, {
  11831. text: text,
  11832. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11833. getSubmenuItems: function () {
  11834. return [{
  11835. type: 'fancymenuitem',
  11836. fancytype: 'colorswatch',
  11837. onAction: function (data) {
  11838. applyColor(editor, format, data.value, noop);
  11839. }
  11840. }];
  11841. }
  11842. });
  11843. };
  11844. var colorPickerDialog = function (editor) {
  11845. return function (callback, value) {
  11846. var isValid = false;
  11847. var onSubmit = function (api) {
  11848. var data = api.getData();
  11849. var hex = data.colorpicker;
  11850. if (isValid) {
  11851. callback(Optional.from(hex));
  11852. api.close();
  11853. } else {
  11854. editor.windowManager.alert(editor.translate([
  11855. 'Invalid hex color code: {0}',
  11856. hex
  11857. ]));
  11858. }
  11859. };
  11860. var onAction = function (_api, details) {
  11861. if (details.name === 'hex-valid') {
  11862. isValid = details.value;
  11863. }
  11864. };
  11865. var initialData = { colorpicker: value };
  11866. editor.windowManager.open({
  11867. title: 'Color Picker',
  11868. size: 'normal',
  11869. body: {
  11870. type: 'panel',
  11871. items: [{
  11872. type: 'colorpicker',
  11873. name: 'colorpicker',
  11874. label: 'Color'
  11875. }]
  11876. },
  11877. buttons: [
  11878. {
  11879. type: 'cancel',
  11880. name: 'cancel',
  11881. text: 'Cancel'
  11882. },
  11883. {
  11884. type: 'submit',
  11885. name: 'save',
  11886. text: 'Save',
  11887. primary: true
  11888. }
  11889. ],
  11890. initialData: initialData,
  11891. onAction: onAction,
  11892. onSubmit: onSubmit,
  11893. onClose: noop,
  11894. onCancel: function () {
  11895. callback(Optional.none());
  11896. }
  11897. });
  11898. };
  11899. };
  11900. var register$a = function (editor) {
  11901. registerCommands(editor);
  11902. var lastForeColor = Cell(null);
  11903. var lastBackColor = Cell(null);
  11904. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  11905. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  11906. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  11907. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  11908. };
  11909. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11910. var hasIcons = menuHasIcons(items);
  11911. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11912. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11913. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11914. };
  11915. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11916. return cat(map$2(items, function (item) {
  11917. if (item.type === 'choiceitem') {
  11918. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11919. return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items)));
  11920. });
  11921. } else {
  11922. return Optional.none();
  11923. }
  11924. }));
  11925. };
  11926. var deriveMenuMovement = function (columns, presets) {
  11927. var menuMarkers = markers(presets);
  11928. if (columns === 1) {
  11929. return {
  11930. mode: 'menu',
  11931. moveOnTab: true
  11932. };
  11933. } else if (columns === 'auto') {
  11934. return {
  11935. mode: 'grid',
  11936. selector: '.' + menuMarkers.item,
  11937. initSize: {
  11938. numColumns: 1,
  11939. numRows: 1
  11940. }
  11941. };
  11942. } else {
  11943. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11944. return {
  11945. mode: 'matrix',
  11946. rowSelector: '.' + rowClass
  11947. };
  11948. }
  11949. };
  11950. var deriveCollectionMovement = function (columns, presets) {
  11951. if (columns === 1) {
  11952. return {
  11953. mode: 'menu',
  11954. moveOnTab: false,
  11955. selector: '.tox-collection__item'
  11956. };
  11957. } else if (columns === 'auto') {
  11958. return {
  11959. mode: 'flatgrid',
  11960. selector: '.' + 'tox-collection__item',
  11961. initSize: {
  11962. numColumns: 1,
  11963. numRows: 1
  11964. }
  11965. };
  11966. } else {
  11967. return {
  11968. mode: 'matrix',
  11969. selectors: {
  11970. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11971. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11972. }
  11973. };
  11974. }
  11975. };
  11976. var renderColorSwatchItem = function (spec, backstage) {
  11977. var items = getColorItems(spec, backstage);
  11978. var columns = backstage.colorinput.getColorCols();
  11979. var presets = 'color';
  11980. var menuSpec = createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  11981. spec.onAction({ value: value });
  11982. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
  11983. var widgetSpec = __assign(__assign({}, menuSpec), {
  11984. markers: markers(presets),
  11985. movement: deriveMenuMovement(columns, presets)
  11986. });
  11987. return {
  11988. type: 'widget',
  11989. data: { value: generate$6('widget-id') },
  11990. dom: {
  11991. tag: 'div',
  11992. classes: ['tox-fancymenuitem']
  11993. },
  11994. autofocus: true,
  11995. components: [parts$f.widget(Menu.sketch(widgetSpec))]
  11996. };
  11997. };
  11998. var getColorItems = function (spec, backstage) {
  11999. var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
  12000. return spec.initData.colors.fold(function () {
  12001. return getColors$1(backstage.colorinput.getColors(), useCustomColors);
  12002. }, function (colors) {
  12003. return colors.concat(getAdditionalColors(useCustomColors));
  12004. });
  12005. };
  12006. var cellOverEvent = generate$6('cell-over');
  12007. var cellExecuteEvent = generate$6('cell-execute');
  12008. var makeCell = function (row, col, labelId) {
  12009. var _a;
  12010. var emitCellOver = function (c) {
  12011. return emitWith(c, cellOverEvent, {
  12012. row: row,
  12013. col: col
  12014. });
  12015. };
  12016. var emitExecute = function (c) {
  12017. return emitWith(c, cellExecuteEvent, {
  12018. row: row,
  12019. col: col
  12020. });
  12021. };
  12022. var onClick = function (c, se) {
  12023. se.stop();
  12024. emitExecute(c);
  12025. };
  12026. return build$1({
  12027. dom: {
  12028. tag: 'div',
  12029. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  12030. },
  12031. behaviours: derive$1([
  12032. config('insert-table-picker-cell', [
  12033. run$1(mouseover(), Focusing.focus),
  12034. run$1(execute$5(), emitExecute),
  12035. run$1(click(), onClick),
  12036. run$1(tap(), onClick)
  12037. ]),
  12038. Toggling.config({
  12039. toggleClass: 'tox-insert-table-picker__selected',
  12040. toggleOnExecute: false
  12041. }),
  12042. Focusing.config({ onFocus: emitCellOver })
  12043. ])
  12044. });
  12045. };
  12046. var makeCells = function (labelId, numRows, numCols) {
  12047. var cells = [];
  12048. for (var i = 0; i < numRows; i++) {
  12049. var row = [];
  12050. for (var j = 0; j < numCols; j++) {
  12051. row.push(makeCell(i, j, labelId));
  12052. }
  12053. cells.push(row);
  12054. }
  12055. return cells;
  12056. };
  12057. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  12058. for (var i = 0; i < numRows; i++) {
  12059. for (var j = 0; j < numColumns; j++) {
  12060. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  12061. }
  12062. }
  12063. };
  12064. var makeComponents = function (cells) {
  12065. return bind$3(cells, function (cellRow) {
  12066. return map$2(cellRow, premade);
  12067. });
  12068. };
  12069. var makeLabelText = function (row, col) {
  12070. return text(col + 1 + 'x' + (row + 1));
  12071. };
  12072. var renderInsertTableMenuItem = function (spec) {
  12073. var numRows = 10;
  12074. var numColumns = 10;
  12075. var sizeLabelId = generate$6('size-label');
  12076. var cells = makeCells(sizeLabelId, numRows, numColumns);
  12077. var memLabel = record({
  12078. dom: {
  12079. tag: 'span',
  12080. classes: ['tox-insert-table-picker__label'],
  12081. attributes: { id: sizeLabelId }
  12082. },
  12083. components: [text('0x0')],
  12084. behaviours: derive$1([Replacing.config({})])
  12085. });
  12086. return {
  12087. type: 'widget',
  12088. data: { value: generate$6('widget-id') },
  12089. dom: {
  12090. tag: 'div',
  12091. classes: ['tox-fancymenuitem']
  12092. },
  12093. autofocus: true,
  12094. components: [parts$f.widget({
  12095. dom: {
  12096. tag: 'div',
  12097. classes: ['tox-insert-table-picker']
  12098. },
  12099. components: makeComponents(cells).concat(memLabel.asSpec()),
  12100. behaviours: derive$1([
  12101. config('insert-table-picker', [
  12102. runWithTarget(cellOverEvent, function (c, t, e) {
  12103. var row = e.event.row;
  12104. var col = e.event.col;
  12105. selectCells(cells, row, col, numRows, numColumns);
  12106. Replacing.set(memLabel.get(c), [makeLabelText(row, col)]);
  12107. }),
  12108. runWithTarget(cellExecuteEvent, function (c, _, e) {
  12109. spec.onAction({
  12110. numRows: e.event.row + 1,
  12111. numColumns: e.event.col + 1
  12112. });
  12113. emit(c, sandboxClose());
  12114. })
  12115. ]),
  12116. Keying.config({
  12117. initSize: {
  12118. numRows: numRows,
  12119. numColumns: numColumns
  12120. },
  12121. mode: 'flatgrid',
  12122. selector: '[role="button"]'
  12123. })
  12124. ])
  12125. })]
  12126. };
  12127. };
  12128. var fancyMenuItems = {
  12129. inserttable: renderInsertTableMenuItem,
  12130. colorswatch: renderColorSwatchItem
  12131. };
  12132. var renderFancyMenuItem = function (spec, backstage) {
  12133. return get$e(fancyMenuItems, spec.fancytype).map(function (render) {
  12134. return render(spec, backstage);
  12135. });
  12136. };
  12137. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  12138. if (renderIcons === void 0) {
  12139. renderIcons = true;
  12140. }
  12141. if (downwardsCaret === void 0) {
  12142. downwardsCaret = false;
  12143. }
  12144. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  12145. var getApi = function (component) {
  12146. return {
  12147. isDisabled: function () {
  12148. return Disabling.isDisabled(component);
  12149. },
  12150. setDisabled: function (state) {
  12151. return Disabling.set(component, state);
  12152. }
  12153. };
  12154. };
  12155. var structure = renderItemStructure({
  12156. presets: 'normal',
  12157. iconContent: spec.icon,
  12158. textContent: spec.text,
  12159. htmlContent: Optional.none(),
  12160. ariaLabel: spec.text,
  12161. caret: Optional.some(caret),
  12162. checkMark: Optional.none(),
  12163. shortcutContent: spec.shortcut
  12164. }, providersBackstage, renderIcons);
  12165. return renderCommonItem({
  12166. data: buildData(spec),
  12167. getApi: getApi,
  12168. disabled: spec.disabled,
  12169. onAction: noop,
  12170. onSetup: spec.onSetup,
  12171. triggersSubmenu: true,
  12172. itemBehaviours: []
  12173. }, structure, itemResponse, providersBackstage);
  12174. };
  12175. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  12176. if (renderIcons === void 0) {
  12177. renderIcons = true;
  12178. }
  12179. var getApi = function (component) {
  12180. return {
  12181. isDisabled: function () {
  12182. return Disabling.isDisabled(component);
  12183. },
  12184. setDisabled: function (state) {
  12185. return Disabling.set(component, state);
  12186. }
  12187. };
  12188. };
  12189. var structure = renderItemStructure({
  12190. presets: 'normal',
  12191. iconContent: spec.icon,
  12192. textContent: spec.text,
  12193. htmlContent: Optional.none(),
  12194. ariaLabel: spec.text,
  12195. caret: Optional.none(),
  12196. checkMark: Optional.none(),
  12197. shortcutContent: spec.shortcut
  12198. }, providersBackstage, renderIcons);
  12199. return renderCommonItem({
  12200. data: buildData(spec),
  12201. getApi: getApi,
  12202. disabled: spec.disabled,
  12203. onAction: spec.onAction,
  12204. onSetup: spec.onSetup,
  12205. triggersSubmenu: false,
  12206. itemBehaviours: []
  12207. }, structure, itemResponse, providersBackstage);
  12208. };
  12209. var renderSeparatorItem = function (spec) {
  12210. var innerHtml = spec.text.fold(function () {
  12211. return {};
  12212. }, function (text) {
  12213. return { innerHtml: text };
  12214. });
  12215. return {
  12216. type: 'separator',
  12217. dom: __assign({
  12218. tag: 'div',
  12219. classes: [
  12220. selectableClass,
  12221. groupHeadingClass
  12222. ]
  12223. }, innerHtml),
  12224. components: []
  12225. };
  12226. };
  12227. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  12228. if (renderIcons === void 0) {
  12229. renderIcons = true;
  12230. }
  12231. var getApi = function (component) {
  12232. return {
  12233. setActive: function (state) {
  12234. Toggling.set(component, state);
  12235. },
  12236. isActive: function () {
  12237. return Toggling.isOn(component);
  12238. },
  12239. isDisabled: function () {
  12240. return Disabling.isDisabled(component);
  12241. },
  12242. setDisabled: function (state) {
  12243. return Disabling.set(component, state);
  12244. }
  12245. };
  12246. };
  12247. var structure = renderItemStructure({
  12248. iconContent: spec.icon,
  12249. textContent: spec.text,
  12250. htmlContent: Optional.none(),
  12251. ariaLabel: spec.text,
  12252. checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
  12253. caret: Optional.none(),
  12254. shortcutContent: spec.shortcut,
  12255. presets: 'normal',
  12256. meta: spec.meta
  12257. }, providersBackstage, renderIcons);
  12258. return deepMerge(renderCommonItem({
  12259. data: buildData(spec),
  12260. disabled: spec.disabled,
  12261. getApi: getApi,
  12262. onAction: spec.onAction,
  12263. onSetup: spec.onSetup,
  12264. triggersSubmenu: false,
  12265. itemBehaviours: []
  12266. }, structure, itemResponse, providersBackstage), {
  12267. toggling: {
  12268. toggleClass: tickedClass,
  12269. toggleOnExecute: false,
  12270. selected: spec.active
  12271. }
  12272. });
  12273. };
  12274. var autocomplete = renderAutocompleteItem;
  12275. var separator$3 = renderSeparatorItem;
  12276. var normal = renderNormalItem;
  12277. var nested = renderNestedItem;
  12278. var toggle$1 = renderToggleMenuItem;
  12279. var fancy = renderFancyMenuItem;
  12280. var card = renderCardMenuItem;
  12281. var FocusMode;
  12282. (function (FocusMode) {
  12283. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  12284. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  12285. }(FocusMode || (FocusMode = {})));
  12286. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  12287. var providersBackstage = backstage.shared.providers;
  12288. var parseForHorizontalMenu = function (menuitem) {
  12289. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  12290. shortcut: Optional.none(),
  12291. icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
  12292. });
  12293. };
  12294. switch (item.type) {
  12295. case 'menuitem':
  12296. return createMenuItem(item).fold(handleError, function (d) {
  12297. return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  12298. });
  12299. case 'nestedmenuitem':
  12300. return createNestedMenuItem(item).fold(handleError, function (d) {
  12301. return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  12302. });
  12303. case 'togglemenuitem':
  12304. return createToggleMenuItem(item).fold(handleError, function (d) {
  12305. return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  12306. });
  12307. case 'separator':
  12308. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  12309. return Optional.some(separator$3(d));
  12310. });
  12311. case 'fancymenuitem':
  12312. return createFancyMenuItem(item).fold(handleError, function (d) {
  12313. return fancy(parseForHorizontalMenu(d), backstage);
  12314. });
  12315. default: {
  12316. console.error('Unknown item in general menu', item);
  12317. return Optional.none();
  12318. }
  12319. }
  12320. };
  12321. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) {
  12322. var renderText = columns === 1;
  12323. var renderIcons = !renderText || menuHasIcons(items);
  12324. return cat(map$2(items, function (item) {
  12325. switch (item.type) {
  12326. case 'separator':
  12327. return createSeparatorItem(item).fold(handleError, function (d) {
  12328. return Optional.some(separator$3(d));
  12329. });
  12330. case 'cardmenuitem':
  12331. return createCardMenuItem(item).fold(handleError, function (d) {
  12332. return Optional.some(card(__assign(__assign({}, d), {
  12333. onAction: function (api) {
  12334. d.onAction(api);
  12335. onItemValueHandler(d.value, d.meta);
  12336. }
  12337. }), itemResponse, sharedBackstage, {
  12338. itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage),
  12339. cardText: {
  12340. matchText: matchText,
  12341. highlightOn: highlightOn
  12342. }
  12343. }));
  12344. });
  12345. case 'autocompleteitem':
  12346. default:
  12347. return createAutocompleterItem(item).fold(handleError, function (d) {
  12348. return Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  12349. });
  12350. }
  12351. }));
  12352. };
  12353. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  12354. var hasIcons = menuHasIcons(items);
  12355. var alloyItems = cat(map$2(items, function (item) {
  12356. var itemHasIcon = function (i) {
  12357. return isHorizontalMenu ? !has$2(i, 'text') : hasIcons;
  12358. };
  12359. var createItem = function (i) {
  12360. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  12361. };
  12362. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  12363. return createItem(__assign(__assign({}, item), { disabled: true }));
  12364. } else {
  12365. return createItem(item);
  12366. }
  12367. }));
  12368. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  12369. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  12370. };
  12371. var createTieredDataFrom = function (partialMenu) {
  12372. return tieredMenu.singleData(partialMenu.value, partialMenu);
  12373. };
  12374. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  12375. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
  12376. var movement = deriveMenuMovement(columns, presets);
  12377. var menuMarkers = markers(presets);
  12378. return {
  12379. dom: partialMenu.dom,
  12380. components: partialMenu.components,
  12381. items: partialMenu.items,
  12382. value: partialMenu.value,
  12383. markers: {
  12384. selectedItem: menuMarkers.selectedItem,
  12385. item: menuMarkers.item
  12386. },
  12387. movement: movement,
  12388. fakeFocus: focusMode === FocusMode.ContentFocus,
  12389. focusManager: focusManager,
  12390. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  12391. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  12392. var numColumns = _a.numColumns, numRows = _a.numRows;
  12393. Keying.setGridSize(comp, numRows, numColumns);
  12394. });
  12395. })])
  12396. };
  12397. };
  12398. var register$9 = function (editor, sharedBackstage) {
  12399. var activeAutocompleter = value$1();
  12400. var processingAction = Cell(false);
  12401. var autocompleter = build$1(InlineView.sketch({
  12402. dom: {
  12403. tag: 'div',
  12404. classes: ['tox-autocompleter']
  12405. },
  12406. components: [],
  12407. fireDismissalEventInstead: {},
  12408. inlineBehaviours: derive$1([config('dismissAutocompleter', [run$1(dismissRequested(), function () {
  12409. return cancelIfNecessary();
  12410. })])]),
  12411. lazySink: sharedBackstage.getSink
  12412. }));
  12413. var isMenuOpen = function () {
  12414. return InlineView.isOpen(autocompleter);
  12415. };
  12416. var isActive = function () {
  12417. return activeAutocompleter.get().isSome();
  12418. };
  12419. var hideIfNecessary = function () {
  12420. if (isActive()) {
  12421. InlineView.hide(autocompleter);
  12422. }
  12423. };
  12424. var cancelIfNecessary = function () {
  12425. if (isActive()) {
  12426. var lastElement = activeAutocompleter.get().map(function (ac) {
  12427. return ac.element;
  12428. });
  12429. detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
  12430. hideIfNecessary();
  12431. activeAutocompleter.clear();
  12432. processingAction.set(false);
  12433. }
  12434. };
  12435. var getAutocompleters = cached(function () {
  12436. return register$b(editor);
  12437. });
  12438. var getCombinedItems = function (triggerChar, matches) {
  12439. var columns = findMap(matches, function (m) {
  12440. return Optional.from(m.columns);
  12441. }).getOr(1);
  12442. return bind$3(matches, function (match) {
  12443. var choices = match.items;
  12444. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  12445. var nr = editor.selection.getRng();
  12446. getContext(editor.dom, nr, triggerChar).fold(function () {
  12447. return console.error('Lost context. Cursor probably moved');
  12448. }, function (_a) {
  12449. var range = _a.range;
  12450. var autocompleterApi = {
  12451. hide: function () {
  12452. cancelIfNecessary();
  12453. },
  12454. reload: function (fetchOptions) {
  12455. hideIfNecessary();
  12456. load(fetchOptions);
  12457. }
  12458. };
  12459. processingAction.set(true);
  12460. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  12461. processingAction.set(false);
  12462. });
  12463. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn);
  12464. });
  12465. };
  12466. var commenceIfNecessary = function (context) {
  12467. if (!isActive()) {
  12468. var wrapper = create$4(editor, context.range);
  12469. activeAutocompleter.set({
  12470. triggerChar: context.triggerChar,
  12471. element: wrapper,
  12472. matchLength: context.text.length
  12473. });
  12474. processingAction.set(false);
  12475. }
  12476. };
  12477. var display = function (ac, context, lookupData, items) {
  12478. ac.matchLength = context.text.length;
  12479. var columns = findMap(lookupData, function (ld) {
  12480. return Optional.from(ld.columns);
  12481. }).getOr(1);
  12482. InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')), {
  12483. anchor: {
  12484. type: 'node',
  12485. root: SugarElement.fromDom(editor.getBody()),
  12486. node: Optional.from(ac.element)
  12487. }
  12488. });
  12489. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  12490. };
  12491. var doLookup = function (fetchOptions) {
  12492. return activeAutocompleter.get().map(function (ac) {
  12493. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  12494. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  12495. });
  12496. }).getOrThunk(function () {
  12497. return lookup$2(editor, getAutocompleters);
  12498. });
  12499. };
  12500. var load = function (fetchOptions) {
  12501. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  12502. commenceIfNecessary(lookupInfo.context);
  12503. lookupInfo.lookupData.then(function (lookupData) {
  12504. activeAutocompleter.get().map(function (ac) {
  12505. var context = lookupInfo.context;
  12506. if (ac.triggerChar === context.triggerChar) {
  12507. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  12508. if (combinedItems.length > 0) {
  12509. display(ac, context, lookupData, combinedItems);
  12510. } else if (context.text.length - ac.matchLength >= 10) {
  12511. cancelIfNecessary();
  12512. } else {
  12513. hideIfNecessary();
  12514. }
  12515. }
  12516. });
  12517. });
  12518. });
  12519. };
  12520. var onKeypress = last(function (e) {
  12521. if (e.which === 27) {
  12522. return;
  12523. }
  12524. load();
  12525. }, 50);
  12526. var autocompleterUiApi = {
  12527. onKeypress: onKeypress,
  12528. cancelIfNecessary: cancelIfNecessary,
  12529. isMenuOpen: isMenuOpen,
  12530. isActive: isActive,
  12531. isProcessingAction: processingAction.get,
  12532. getView: function () {
  12533. return InlineView.getContent(autocompleter);
  12534. }
  12535. };
  12536. if (editor.hasPlugin('rtc') === false) {
  12537. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  12538. }
  12539. };
  12540. var Autocompleter = { register: register$9 };
  12541. var closest = function (scope, selector, isRoot) {
  12542. return closest$1(scope, selector, isRoot).isSome();
  12543. };
  12544. var DelayedFunction = function (fun, delay) {
  12545. var ref = null;
  12546. var schedule = function () {
  12547. var args = [];
  12548. for (var _i = 0; _i < arguments.length; _i++) {
  12549. args[_i] = arguments[_i];
  12550. }
  12551. ref = setTimeout(function () {
  12552. fun.apply(null, args);
  12553. ref = null;
  12554. }, delay);
  12555. };
  12556. var cancel = function () {
  12557. if (ref !== null) {
  12558. clearTimeout(ref);
  12559. ref = null;
  12560. }
  12561. };
  12562. return {
  12563. cancel: cancel,
  12564. schedule: schedule
  12565. };
  12566. };
  12567. var SIGNIFICANT_MOVE = 5;
  12568. var LONGPRESS_DELAY = 400;
  12569. var getTouch = function (event) {
  12570. var raw = event.raw;
  12571. if (raw.touches === undefined || raw.touches.length !== 1) {
  12572. return Optional.none();
  12573. }
  12574. return Optional.some(raw.touches[0]);
  12575. };
  12576. var isFarEnough = function (touch, data) {
  12577. var distX = Math.abs(touch.clientX - data.x);
  12578. var distY = Math.abs(touch.clientY - data.y);
  12579. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  12580. };
  12581. var monitor = function (settings) {
  12582. var startData = value$1();
  12583. var longpressFired = Cell(false);
  12584. var longpress$1 = DelayedFunction(function (event) {
  12585. settings.triggerEvent(longpress(), event);
  12586. longpressFired.set(true);
  12587. }, LONGPRESS_DELAY);
  12588. var handleTouchstart = function (event) {
  12589. getTouch(event).each(function (touch) {
  12590. longpress$1.cancel();
  12591. var data = {
  12592. x: touch.clientX,
  12593. y: touch.clientY,
  12594. target: event.target
  12595. };
  12596. longpress$1.schedule(event);
  12597. longpressFired.set(false);
  12598. startData.set(data);
  12599. });
  12600. return Optional.none();
  12601. };
  12602. var handleTouchmove = function (event) {
  12603. longpress$1.cancel();
  12604. getTouch(event).each(function (touch) {
  12605. startData.on(function (data) {
  12606. if (isFarEnough(touch, data)) {
  12607. startData.clear();
  12608. }
  12609. });
  12610. });
  12611. return Optional.none();
  12612. };
  12613. var handleTouchend = function (event) {
  12614. longpress$1.cancel();
  12615. var isSame = function (data) {
  12616. return eq(data.target, event.target);
  12617. };
  12618. return startData.get().filter(isSame).map(function (_data) {
  12619. if (longpressFired.get()) {
  12620. event.prevent();
  12621. return false;
  12622. } else {
  12623. return settings.triggerEvent(tap(), event);
  12624. }
  12625. });
  12626. };
  12627. var handlers = wrapAll([
  12628. {
  12629. key: touchstart(),
  12630. value: handleTouchstart
  12631. },
  12632. {
  12633. key: touchmove(),
  12634. value: handleTouchmove
  12635. },
  12636. {
  12637. key: touchend(),
  12638. value: handleTouchend
  12639. }
  12640. ]);
  12641. var fireIfReady = function (event, type) {
  12642. return get$e(handlers, type).bind(function (handler) {
  12643. return handler(event);
  12644. });
  12645. };
  12646. return { fireIfReady: fireIfReady };
  12647. };
  12648. var isDangerous = function (event) {
  12649. var keyEv = event.raw;
  12650. return keyEv.which === BACKSPACE[0] && !contains$2([
  12651. 'input',
  12652. 'textarea'
  12653. ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]');
  12654. };
  12655. var isFirefox = function () {
  12656. return detect$1().browser.isFirefox();
  12657. };
  12658. var settingsSchema = objOfOnly([
  12659. requiredFunction('triggerEvent'),
  12660. defaulted('stopBackspace', true)
  12661. ]);
  12662. var bindFocus = function (container, handler) {
  12663. if (isFirefox()) {
  12664. return capture(container, 'focus', handler);
  12665. } else {
  12666. return bind(container, 'focusin', handler);
  12667. }
  12668. };
  12669. var bindBlur = function (container, handler) {
  12670. if (isFirefox()) {
  12671. return capture(container, 'blur', handler);
  12672. } else {
  12673. return bind(container, 'focusout', handler);
  12674. }
  12675. };
  12676. var setup$d = function (container, rawSettings) {
  12677. var settings = asRawOrDie$1('Getting GUI events settings', settingsSchema, rawSettings);
  12678. var pointerEvents = [
  12679. 'touchstart',
  12680. 'touchmove',
  12681. 'touchend',
  12682. 'touchcancel',
  12683. 'gesturestart',
  12684. 'mousedown',
  12685. 'mouseup',
  12686. 'mouseover',
  12687. 'mousemove',
  12688. 'mouseout',
  12689. 'click'
  12690. ];
  12691. var tapEvent = monitor(settings);
  12692. var simpleEvents = map$2(pointerEvents.concat([
  12693. 'selectstart',
  12694. 'input',
  12695. 'contextmenu',
  12696. 'change',
  12697. 'transitionend',
  12698. 'transitioncancel',
  12699. 'drag',
  12700. 'dragstart',
  12701. 'dragend',
  12702. 'dragenter',
  12703. 'dragleave',
  12704. 'dragover',
  12705. 'drop',
  12706. 'keyup'
  12707. ]), function (type) {
  12708. return bind(container, type, function (event) {
  12709. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  12710. if (tapStopped) {
  12711. event.kill();
  12712. }
  12713. });
  12714. var stopped = settings.triggerEvent(type, event);
  12715. if (stopped) {
  12716. event.kill();
  12717. }
  12718. });
  12719. });
  12720. var pasteTimeout = value$1();
  12721. var onPaste = bind(container, 'paste', function (event) {
  12722. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  12723. if (tapStopped) {
  12724. event.kill();
  12725. }
  12726. });
  12727. var stopped = settings.triggerEvent('paste', event);
  12728. if (stopped) {
  12729. event.kill();
  12730. }
  12731. pasteTimeout.set(setTimeout(function () {
  12732. settings.triggerEvent(postPaste(), event);
  12733. }, 0));
  12734. });
  12735. var onKeydown = bind(container, 'keydown', function (event) {
  12736. var stopped = settings.triggerEvent('keydown', event);
  12737. if (stopped) {
  12738. event.kill();
  12739. } else if (settings.stopBackspace === true && isDangerous(event)) {
  12740. event.prevent();
  12741. }
  12742. });
  12743. var onFocusIn = bindFocus(container, function (event) {
  12744. var stopped = settings.triggerEvent('focusin', event);
  12745. if (stopped) {
  12746. event.kill();
  12747. }
  12748. });
  12749. var focusoutTimeout = value$1();
  12750. var onFocusOut = bindBlur(container, function (event) {
  12751. var stopped = settings.triggerEvent('focusout', event);
  12752. if (stopped) {
  12753. event.kill();
  12754. }
  12755. focusoutTimeout.set(setTimeout(function () {
  12756. settings.triggerEvent(postBlur(), event);
  12757. }, 0));
  12758. });
  12759. var unbind = function () {
  12760. each$1(simpleEvents, function (e) {
  12761. e.unbind();
  12762. });
  12763. onKeydown.unbind();
  12764. onFocusIn.unbind();
  12765. onFocusOut.unbind();
  12766. onPaste.unbind();
  12767. pasteTimeout.on(clearTimeout);
  12768. focusoutTimeout.on(clearTimeout);
  12769. };
  12770. return { unbind: unbind };
  12771. };
  12772. var derive = function (rawEvent, rawTarget) {
  12773. var source = get$e(rawEvent, 'target').getOr(rawTarget);
  12774. return Cell(source);
  12775. };
  12776. var fromSource = function (event, source) {
  12777. var stopper = Cell(false);
  12778. var cutter = Cell(false);
  12779. var stop = function () {
  12780. stopper.set(true);
  12781. };
  12782. var cut = function () {
  12783. cutter.set(true);
  12784. };
  12785. return {
  12786. stop: stop,
  12787. cut: cut,
  12788. isStopped: stopper.get,
  12789. isCut: cutter.get,
  12790. event: event,
  12791. setSource: source.set,
  12792. getSource: source.get
  12793. };
  12794. };
  12795. var fromExternal = function (event) {
  12796. var stopper = Cell(false);
  12797. var stop = function () {
  12798. stopper.set(true);
  12799. };
  12800. return {
  12801. stop: stop,
  12802. cut: noop,
  12803. isStopped: stopper.get,
  12804. isCut: never,
  12805. event: event,
  12806. setSource: die('Cannot set source of a broadcasted event'),
  12807. getSource: die('Cannot get source of a broadcasted event')
  12808. };
  12809. };
  12810. var adt$1 = Adt.generate([
  12811. { stopped: [] },
  12812. { resume: ['element'] },
  12813. { complete: [] }
  12814. ]);
  12815. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  12816. var handler = lookup(eventType, target);
  12817. var simulatedEvent = fromSource(rawEvent, source);
  12818. return handler.fold(function () {
  12819. logger.logEventNoHandlers(eventType, target);
  12820. return adt$1.complete();
  12821. }, function (handlerInfo) {
  12822. var descHandler = handlerInfo.descHandler;
  12823. var eventHandler = getCurried(descHandler);
  12824. eventHandler(simulatedEvent);
  12825. if (simulatedEvent.isStopped()) {
  12826. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  12827. return adt$1.stopped();
  12828. } else if (simulatedEvent.isCut()) {
  12829. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  12830. return adt$1.complete();
  12831. } else {
  12832. return parent(handlerInfo.element).fold(function () {
  12833. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  12834. return adt$1.complete();
  12835. }, function (parent) {
  12836. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  12837. return adt$1.resume(parent);
  12838. });
  12839. }
  12840. });
  12841. };
  12842. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12843. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  12844. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12845. }, never);
  12846. };
  12847. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12848. var source = derive(rawEvent, target);
  12849. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12850. };
  12851. var broadcast = function (listeners, rawEvent, _logger) {
  12852. var simulatedEvent = fromExternal(rawEvent);
  12853. each$1(listeners, function (listener) {
  12854. var descHandler = listener.descHandler;
  12855. var handler = getCurried(descHandler);
  12856. handler(simulatedEvent);
  12857. });
  12858. return simulatedEvent.isStopped();
  12859. };
  12860. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12861. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  12862. };
  12863. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12864. var source = derive(rawEvent, rawTarget);
  12865. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12866. };
  12867. var eventHandler = function (element, descHandler) {
  12868. return {
  12869. element: element,
  12870. descHandler: descHandler
  12871. };
  12872. };
  12873. var broadcastHandler = function (id, handler) {
  12874. return {
  12875. id: id,
  12876. descHandler: handler
  12877. };
  12878. };
  12879. var EventRegistry = function () {
  12880. var registry = {};
  12881. var registerId = function (extraArgs, id, events) {
  12882. each(events, function (v, k) {
  12883. var handlers = registry[k] !== undefined ? registry[k] : {};
  12884. handlers[id] = curryArgs(v, extraArgs);
  12885. registry[k] = handlers;
  12886. });
  12887. };
  12888. var findHandler = function (handlers, elem) {
  12889. return read$1(elem).fold(function () {
  12890. return Optional.none();
  12891. }, function (id) {
  12892. return handlers.bind(function (h) {
  12893. return get$e(h, id);
  12894. }).map(function (descHandler) {
  12895. return eventHandler(elem, descHandler);
  12896. });
  12897. });
  12898. };
  12899. var filterByType = function (type) {
  12900. return get$e(registry, type).map(function (handlers) {
  12901. return mapToArray(handlers, function (f, id) {
  12902. return broadcastHandler(id, f);
  12903. });
  12904. }).getOr([]);
  12905. };
  12906. var find = function (isAboveRoot, type, target) {
  12907. var handlers = get$e(registry, type);
  12908. return closest$4(target, function (elem) {
  12909. return findHandler(handlers, elem);
  12910. }, isAboveRoot);
  12911. };
  12912. var unregisterId = function (id) {
  12913. each(registry, function (handlersById, _eventName) {
  12914. if (has$2(handlersById, id)) {
  12915. delete handlersById[id];
  12916. }
  12917. });
  12918. };
  12919. return {
  12920. registerId: registerId,
  12921. unregisterId: unregisterId,
  12922. filterByType: filterByType,
  12923. find: find
  12924. };
  12925. };
  12926. var Registry = function () {
  12927. var events = EventRegistry();
  12928. var components = {};
  12929. var readOrTag = function (component) {
  12930. var elem = component.element;
  12931. return read$1(elem).getOrThunk(function () {
  12932. return write('uid-', component.element);
  12933. });
  12934. };
  12935. var failOnDuplicate = function (component, tagId) {
  12936. var conflict = components[tagId];
  12937. if (conflict === component) {
  12938. unregister(component);
  12939. } else {
  12940. 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');
  12941. }
  12942. };
  12943. var register = function (component) {
  12944. var tagId = readOrTag(component);
  12945. if (hasNonNullableKey(components, tagId)) {
  12946. failOnDuplicate(component, tagId);
  12947. }
  12948. var extraArgs = [component];
  12949. events.registerId(extraArgs, tagId, component.events);
  12950. components[tagId] = component;
  12951. };
  12952. var unregister = function (component) {
  12953. read$1(component.element).each(function (tagId) {
  12954. delete components[tagId];
  12955. events.unregisterId(tagId);
  12956. });
  12957. };
  12958. var filter = function (type) {
  12959. return events.filterByType(type);
  12960. };
  12961. var find = function (isAboveRoot, type, target) {
  12962. return events.find(isAboveRoot, type, target);
  12963. };
  12964. var getById = function (id) {
  12965. return get$e(components, id);
  12966. };
  12967. return {
  12968. find: find,
  12969. filter: filter,
  12970. register: register,
  12971. unregister: unregister,
  12972. getById: getById
  12973. };
  12974. };
  12975. var factory$j = function (detail) {
  12976. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12977. return {
  12978. uid: detail.uid,
  12979. dom: __assign({
  12980. tag: 'div',
  12981. attributes: __assign({ role: 'presentation' }, attributes)
  12982. }, domWithoutAttributes),
  12983. components: detail.components,
  12984. behaviours: get$2(detail.containerBehaviours),
  12985. events: detail.events,
  12986. domModification: detail.domModification,
  12987. eventOrder: detail.eventOrder
  12988. };
  12989. };
  12990. var Container = single({
  12991. name: 'Container',
  12992. factory: factory$j,
  12993. configFields: [
  12994. defaulted('components', []),
  12995. field('containerBehaviours', []),
  12996. defaulted('events', {}),
  12997. defaulted('domModification', {}),
  12998. defaulted('eventOrder', {})
  12999. ]
  13000. });
  13001. var takeover = function (root) {
  13002. var isAboveRoot = function (el) {
  13003. return parent(root.element).fold(always, function (parent) {
  13004. return eq(el, parent);
  13005. });
  13006. };
  13007. var registry = Registry();
  13008. var lookup = function (eventName, target) {
  13009. return registry.find(isAboveRoot, eventName, target);
  13010. };
  13011. var domEvents = setup$d(root.element, {
  13012. triggerEvent: function (eventName, event) {
  13013. return monitorEvent(eventName, event.target, function (logger) {
  13014. return triggerUntilStopped(lookup, eventName, event, logger);
  13015. });
  13016. }
  13017. });
  13018. var systemApi = {
  13019. debugInfo: constant$1('real'),
  13020. triggerEvent: function (eventName, target, data) {
  13021. monitorEvent(eventName, target, function (logger) {
  13022. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  13023. });
  13024. },
  13025. triggerFocus: function (target, originator) {
  13026. read$1(target).fold(function () {
  13027. focus$3(target);
  13028. }, function (_alloyId) {
  13029. monitorEvent(focus$4(), target, function (logger) {
  13030. triggerHandler(lookup, focus$4(), {
  13031. originator: originator,
  13032. kill: noop,
  13033. prevent: noop,
  13034. target: target
  13035. }, target, logger);
  13036. return false;
  13037. });
  13038. });
  13039. },
  13040. triggerEscape: function (comp, simulatedEvent) {
  13041. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  13042. },
  13043. getByUid: function (uid) {
  13044. return getByUid(uid);
  13045. },
  13046. getByDom: function (elem) {
  13047. return getByDom(elem);
  13048. },
  13049. build: build$1,
  13050. addToGui: function (c) {
  13051. add(c);
  13052. },
  13053. removeFromGui: function (c) {
  13054. remove(c);
  13055. },
  13056. addToWorld: function (c) {
  13057. addToWorld(c);
  13058. },
  13059. removeFromWorld: function (c) {
  13060. removeFromWorld(c);
  13061. },
  13062. broadcast: function (message) {
  13063. broadcast$1(message);
  13064. },
  13065. broadcastOn: function (channels, message) {
  13066. broadcastOn(channels, message);
  13067. },
  13068. broadcastEvent: function (eventName, event) {
  13069. broadcastEvent(eventName, event);
  13070. },
  13071. isConnected: always
  13072. };
  13073. var addToWorld = function (component) {
  13074. component.connect(systemApi);
  13075. if (!isText$1(component.element)) {
  13076. registry.register(component);
  13077. each$1(component.components(), addToWorld);
  13078. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  13079. }
  13080. };
  13081. var removeFromWorld = function (component) {
  13082. if (!isText$1(component.element)) {
  13083. each$1(component.components(), removeFromWorld);
  13084. registry.unregister(component);
  13085. }
  13086. component.disconnect();
  13087. };
  13088. var add = function (component) {
  13089. attach(root, component);
  13090. };
  13091. var remove = function (component) {
  13092. detach(component);
  13093. };
  13094. var destroy = function () {
  13095. domEvents.unbind();
  13096. remove$7(root.element);
  13097. };
  13098. var broadcastData = function (data) {
  13099. var receivers = registry.filter(receive());
  13100. each$1(receivers, function (receiver) {
  13101. var descHandler = receiver.descHandler;
  13102. var handler = getCurried(descHandler);
  13103. handler(data);
  13104. });
  13105. };
  13106. var broadcast$1 = function (message) {
  13107. broadcastData({
  13108. universal: true,
  13109. data: message
  13110. });
  13111. };
  13112. var broadcastOn = function (channels, message) {
  13113. broadcastData({
  13114. universal: false,
  13115. channels: channels,
  13116. data: message
  13117. });
  13118. };
  13119. var broadcastEvent = function (eventName, event) {
  13120. var listeners = registry.filter(eventName);
  13121. return broadcast(listeners, event);
  13122. };
  13123. var getByUid = function (uid) {
  13124. return registry.getById(uid).fold(function () {
  13125. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  13126. }, Result.value);
  13127. };
  13128. var getByDom = function (elem) {
  13129. var uid = read$1(elem).getOr('not found');
  13130. return getByUid(uid);
  13131. };
  13132. addToWorld(root);
  13133. return {
  13134. root: root,
  13135. element: root.element,
  13136. destroy: destroy,
  13137. add: add,
  13138. remove: remove,
  13139. getByUid: getByUid,
  13140. getByDom: getByDom,
  13141. addToWorld: addToWorld,
  13142. removeFromWorld: removeFromWorld,
  13143. broadcast: broadcast$1,
  13144. broadcastOn: broadcastOn,
  13145. broadcastEvent: broadcastEvent
  13146. };
  13147. };
  13148. var renderBar = function (spec, backstage) {
  13149. return {
  13150. dom: {
  13151. tag: 'div',
  13152. classes: [
  13153. 'tox-bar',
  13154. 'tox-form__controls-h-stack'
  13155. ]
  13156. },
  13157. components: map$2(spec.items, backstage.interpreter)
  13158. };
  13159. };
  13160. var schema$l = constant$1([
  13161. defaulted('prefix', 'form-field'),
  13162. field('fieldBehaviours', [
  13163. Composing,
  13164. Representing
  13165. ])
  13166. ]);
  13167. var parts$e = constant$1([
  13168. optional({
  13169. schema: [required$1('dom')],
  13170. name: 'label'
  13171. }),
  13172. optional({
  13173. factory: {
  13174. sketch: function (spec) {
  13175. return {
  13176. uid: spec.uid,
  13177. dom: {
  13178. tag: 'span',
  13179. styles: { display: 'none' },
  13180. attributes: { 'aria-hidden': 'true' },
  13181. innerHtml: spec.text
  13182. }
  13183. };
  13184. }
  13185. },
  13186. schema: [required$1('text')],
  13187. name: 'aria-descriptor'
  13188. }),
  13189. required({
  13190. factory: {
  13191. sketch: function (spec) {
  13192. var excludeFactory = exclude(spec, ['factory']);
  13193. return spec.factory.sketch(excludeFactory);
  13194. }
  13195. },
  13196. schema: [required$1('factory')],
  13197. name: 'field'
  13198. })
  13199. ]);
  13200. var factory$i = function (detail, components, _spec, _externals) {
  13201. var behaviours = augment(detail.fieldBehaviours, [
  13202. Composing.config({
  13203. find: function (container) {
  13204. return getPart(container, detail, 'field');
  13205. }
  13206. }),
  13207. Representing.config({
  13208. store: {
  13209. mode: 'manual',
  13210. getValue: function (field) {
  13211. return Composing.getCurrent(field).bind(Representing.getValue);
  13212. },
  13213. setValue: function (field, value) {
  13214. Composing.getCurrent(field).each(function (current) {
  13215. Representing.setValue(current, value);
  13216. });
  13217. }
  13218. }
  13219. })
  13220. ]);
  13221. var events = derive$2([runOnAttached(function (component, _simulatedEvent) {
  13222. var ps = getParts(component, detail, [
  13223. 'label',
  13224. 'field',
  13225. 'aria-descriptor'
  13226. ]);
  13227. ps.field().each(function (field) {
  13228. var id = generate$6(detail.prefix);
  13229. ps.label().each(function (label) {
  13230. set$7(label.element, 'for', id);
  13231. set$7(field.element, 'id', id);
  13232. });
  13233. ps['aria-descriptor']().each(function (descriptor) {
  13234. var descriptorId = generate$6(detail.prefix);
  13235. set$7(descriptor.element, 'id', descriptorId);
  13236. set$7(field.element, 'aria-describedby', descriptorId);
  13237. });
  13238. });
  13239. })]);
  13240. var apis = {
  13241. getField: function (container) {
  13242. return getPart(container, detail, 'field');
  13243. },
  13244. getLabel: function (container) {
  13245. return getPart(container, detail, 'label');
  13246. }
  13247. };
  13248. return {
  13249. uid: detail.uid,
  13250. dom: detail.dom,
  13251. components: components,
  13252. behaviours: behaviours,
  13253. events: events,
  13254. apis: apis
  13255. };
  13256. };
  13257. var FormField = composite({
  13258. name: 'FormField',
  13259. configFields: schema$l(),
  13260. partFields: parts$e(),
  13261. factory: factory$i,
  13262. apis: {
  13263. getField: function (apis, comp) {
  13264. return apis.getField(comp);
  13265. },
  13266. getLabel: function (apis, comp) {
  13267. return apis.getLabel(comp);
  13268. }
  13269. }
  13270. });
  13271. var exhibit$2 = function (base, tabConfig) {
  13272. return nu$7({
  13273. attributes: wrapAll([{
  13274. key: tabConfig.tabAttr,
  13275. value: 'true'
  13276. }])
  13277. });
  13278. };
  13279. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  13280. __proto__: null,
  13281. exhibit: exhibit$2
  13282. });
  13283. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  13284. var Tabstopping = create$7({
  13285. fields: TabstopSchema,
  13286. name: 'tabstopping',
  13287. active: ActiveTabstopping
  13288. });
  13289. var global$8 = tinymce.util.Tools.resolve('tinymce.html.Entities');
  13290. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13291. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  13292. return FormField.sketch(spec);
  13293. };
  13294. var renderFormField = function (pLabel, pField) {
  13295. return renderFormFieldWith(pLabel, pField, [], []);
  13296. };
  13297. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13298. return {
  13299. dom: renderFormFieldDomWith(extraClasses),
  13300. components: pLabel.toArray().concat([pField]),
  13301. fieldBehaviours: derive$1(extraBehaviours)
  13302. };
  13303. };
  13304. var renderFormFieldDom = function () {
  13305. return renderFormFieldDomWith([]);
  13306. };
  13307. var renderFormFieldDomWith = function (extraClasses) {
  13308. return {
  13309. tag: 'div',
  13310. classes: ['tox-form__group'].concat(extraClasses)
  13311. };
  13312. };
  13313. var renderLabel$2 = function (label, providersBackstage) {
  13314. return FormField.parts.label({
  13315. dom: {
  13316. tag: 'label',
  13317. classes: ['tox-label'],
  13318. innerHtml: providersBackstage.translate(label)
  13319. }
  13320. });
  13321. };
  13322. var formChangeEvent = generate$6('form-component-change');
  13323. var formCloseEvent = generate$6('form-close');
  13324. var formCancelEvent = generate$6('form-cancel');
  13325. var formActionEvent = generate$6('form-action');
  13326. var formSubmitEvent = generate$6('form-submit');
  13327. var formBlockEvent = generate$6('form-block');
  13328. var formUnblockEvent = generate$6('form-unblock');
  13329. var formTabChangeEvent = generate$6('form-tabchange');
  13330. var formResizeEvent = generate$6('form-resize');
  13331. var renderCollection = function (spec, providersBackstage) {
  13332. var _a;
  13333. var pLabel = spec.label.map(function (label) {
  13334. return renderLabel$2(label, providersBackstage);
  13335. });
  13336. var runOnItem = function (f) {
  13337. return function (comp, se) {
  13338. closest$1(se.event.target, '[data-collection-item-value]').each(function (target) {
  13339. f(comp, se, target, get$c(target, 'data-collection-item-value'));
  13340. });
  13341. };
  13342. };
  13343. var setContents = function (comp, items) {
  13344. var htmlLines = map$2(items, function (item) {
  13345. var itemText = global$f.translate(item.text);
  13346. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  13347. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  13348. var mapItemName = {
  13349. '_': ' ',
  13350. ' - ': ' ',
  13351. '-': ' '
  13352. };
  13353. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  13354. return mapItemName[match];
  13355. });
  13356. var disabledClass = providersBackstage.isDisabled() ? ' tox-collection__item--state-disabled' : '';
  13357. return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$8.encodeAllRaw(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  13358. });
  13359. var chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
  13360. var html = map$2(chunks, function (ch) {
  13361. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  13362. });
  13363. set$8(comp.element, html.join(''));
  13364. };
  13365. var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  13366. se.stop();
  13367. if (!providersBackstage.isDisabled()) {
  13368. emitWith(comp, formActionEvent, {
  13369. name: spec.name,
  13370. value: itemValue
  13371. });
  13372. }
  13373. });
  13374. var collectionEvents = [
  13375. run$1(mouseover(), runOnItem(function (comp, se, tgt) {
  13376. focus$3(tgt);
  13377. })),
  13378. run$1(click(), onClick),
  13379. run$1(tap(), onClick),
  13380. run$1(focusin(), runOnItem(function (comp, se, tgt) {
  13381. descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  13382. remove$3(currentActive, activeClass);
  13383. });
  13384. add$2(tgt, activeClass);
  13385. })),
  13386. run$1(focusout(), runOnItem(function (comp) {
  13387. descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  13388. remove$3(currentActive, activeClass);
  13389. });
  13390. })),
  13391. runOnExecute$1(runOnItem(function (comp, se, tgt, itemValue) {
  13392. emitWith(comp, formActionEvent, {
  13393. name: spec.name,
  13394. value: itemValue
  13395. });
  13396. }))
  13397. ];
  13398. var iterCollectionItems = function (comp, applyAttributes) {
  13399. return map$2(descendants(comp.element, '.tox-collection__item'), applyAttributes);
  13400. };
  13401. var pField = FormField.parts.field({
  13402. dom: {
  13403. tag: 'div',
  13404. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  13405. },
  13406. components: [],
  13407. factory: { sketch: identity$1 },
  13408. behaviours: derive$1([
  13409. Disabling.config({
  13410. disabled: providersBackstage.isDisabled,
  13411. onDisabled: function (comp) {
  13412. iterCollectionItems(comp, function (childElm) {
  13413. add$2(childElm, 'tox-collection__item--state-disabled');
  13414. set$7(childElm, 'aria-disabled', true);
  13415. });
  13416. },
  13417. onEnabled: function (comp) {
  13418. iterCollectionItems(comp, function (childElm) {
  13419. remove$3(childElm, 'tox-collection__item--state-disabled');
  13420. remove$6(childElm, 'aria-disabled');
  13421. });
  13422. }
  13423. }),
  13424. receivingConfig(),
  13425. Replacing.config({}),
  13426. Representing.config({
  13427. store: {
  13428. mode: 'memory',
  13429. initialValue: []
  13430. },
  13431. onSetValue: function (comp, items) {
  13432. setContents(comp, items);
  13433. if (spec.columns === 'auto') {
  13434. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  13435. var numRows = _a.numRows, numColumns = _a.numColumns;
  13436. Keying.setGridSize(comp, numRows, numColumns);
  13437. });
  13438. }
  13439. emit(comp, formResizeEvent);
  13440. }
  13441. }),
  13442. Tabstopping.config({}),
  13443. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  13444. config('collection-events', collectionEvents)
  13445. ]),
  13446. eventOrder: (_a = {}, _a[execute$5()] = [
  13447. 'disabling',
  13448. 'alloy.base.behaviour',
  13449. 'collection-events'
  13450. ], _a)
  13451. });
  13452. var extraClasses = ['tox-form__group--collection'];
  13453. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  13454. };
  13455. var schema$k = constant$1([
  13456. option('data'),
  13457. defaulted('inputAttributes', {}),
  13458. defaulted('inputStyles', {}),
  13459. defaulted('tag', 'input'),
  13460. defaulted('inputClasses', []),
  13461. onHandler('onSetValue'),
  13462. defaulted('styles', {}),
  13463. defaulted('eventOrder', {}),
  13464. field('inputBehaviours', [
  13465. Representing,
  13466. Focusing
  13467. ]),
  13468. defaulted('selectOnFocus', true)
  13469. ]);
  13470. var focusBehaviours = function (detail) {
  13471. return derive$1([Focusing.config({
  13472. onFocus: !detail.selectOnFocus ? noop : function (component) {
  13473. var input = component.element;
  13474. var value = get$9(input);
  13475. input.dom.setSelectionRange(0, value.length);
  13476. }
  13477. })]);
  13478. };
  13479. var behaviours = function (detail) {
  13480. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  13481. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  13482. return { initialValue: data };
  13483. }).getOr({})), {
  13484. getValue: function (input) {
  13485. return get$9(input.element);
  13486. },
  13487. setValue: function (input, data) {
  13488. var current = get$9(input.element);
  13489. if (current !== data) {
  13490. set$5(input.element, data);
  13491. }
  13492. }
  13493. }),
  13494. onSetValue: detail.onSetValue
  13495. })]));
  13496. };
  13497. var dom = function (detail) {
  13498. return {
  13499. tag: detail.tag,
  13500. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  13501. styles: detail.inputStyles,
  13502. classes: detail.inputClasses
  13503. };
  13504. };
  13505. var factory$h = function (detail, _spec) {
  13506. return {
  13507. uid: detail.uid,
  13508. dom: dom(detail),
  13509. components: [],
  13510. behaviours: behaviours(detail),
  13511. eventOrder: detail.eventOrder
  13512. };
  13513. };
  13514. var Input = single({
  13515. name: 'Input',
  13516. configFields: schema$k(),
  13517. factory: factory$h
  13518. });
  13519. var exports$1 = {}, module = { exports: exports$1 };
  13520. (function (define, exports, module, require) {
  13521. (function (f) {
  13522. if (typeof exports === 'object' && typeof module !== 'undefined') {
  13523. module.exports = f();
  13524. } else if (typeof define === 'function' && define.amd) {
  13525. define([], f);
  13526. } else {
  13527. var g;
  13528. if (typeof window !== 'undefined') {
  13529. g = window;
  13530. } else if (typeof global !== 'undefined') {
  13531. g = global;
  13532. } else if (typeof self !== 'undefined') {
  13533. g = self;
  13534. } else {
  13535. g = this;
  13536. }
  13537. g.EphoxContactWrapper = f();
  13538. }
  13539. }(function () {
  13540. return function () {
  13541. function r(e, n, t) {
  13542. function o(i, f) {
  13543. if (!n[i]) {
  13544. if (!e[i]) {
  13545. var c = 'function' == typeof require && require;
  13546. if (!f && c)
  13547. return c(i, !0);
  13548. if (u)
  13549. return u(i, !0);
  13550. var a = new Error('Cannot find module \'' + i + '\'');
  13551. throw a.code = 'MODULE_NOT_FOUND', a;
  13552. }
  13553. var p = n[i] = { exports: {} };
  13554. e[i][0].call(p.exports, function (r) {
  13555. var n = e[i][1][r];
  13556. return o(n || r);
  13557. }, p, p.exports, r, e, n, t);
  13558. }
  13559. return n[i].exports;
  13560. }
  13561. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  13562. o(t[i]);
  13563. return o;
  13564. }
  13565. return r;
  13566. }()({
  13567. 1: [
  13568. function (require, module, exports) {
  13569. var process = module.exports = {};
  13570. var cachedSetTimeout;
  13571. var cachedClearTimeout;
  13572. function defaultSetTimout() {
  13573. throw new Error('setTimeout has not been defined');
  13574. }
  13575. function defaultClearTimeout() {
  13576. throw new Error('clearTimeout has not been defined');
  13577. }
  13578. (function () {
  13579. try {
  13580. if (typeof setTimeout === 'function') {
  13581. cachedSetTimeout = setTimeout;
  13582. } else {
  13583. cachedSetTimeout = defaultSetTimout;
  13584. }
  13585. } catch (e) {
  13586. cachedSetTimeout = defaultSetTimout;
  13587. }
  13588. try {
  13589. if (typeof clearTimeout === 'function') {
  13590. cachedClearTimeout = clearTimeout;
  13591. } else {
  13592. cachedClearTimeout = defaultClearTimeout;
  13593. }
  13594. } catch (e) {
  13595. cachedClearTimeout = defaultClearTimeout;
  13596. }
  13597. }());
  13598. function runTimeout(fun) {
  13599. if (cachedSetTimeout === setTimeout) {
  13600. return setTimeout(fun, 0);
  13601. }
  13602. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  13603. cachedSetTimeout = setTimeout;
  13604. return setTimeout(fun, 0);
  13605. }
  13606. try {
  13607. return cachedSetTimeout(fun, 0);
  13608. } catch (e) {
  13609. try {
  13610. return cachedSetTimeout.call(null, fun, 0);
  13611. } catch (e) {
  13612. return cachedSetTimeout.call(this, fun, 0);
  13613. }
  13614. }
  13615. }
  13616. function runClearTimeout(marker) {
  13617. if (cachedClearTimeout === clearTimeout) {
  13618. return clearTimeout(marker);
  13619. }
  13620. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  13621. cachedClearTimeout = clearTimeout;
  13622. return clearTimeout(marker);
  13623. }
  13624. try {
  13625. return cachedClearTimeout(marker);
  13626. } catch (e) {
  13627. try {
  13628. return cachedClearTimeout.call(null, marker);
  13629. } catch (e) {
  13630. return cachedClearTimeout.call(this, marker);
  13631. }
  13632. }
  13633. }
  13634. var queue = [];
  13635. var draining = false;
  13636. var currentQueue;
  13637. var queueIndex = -1;
  13638. function cleanUpNextTick() {
  13639. if (!draining || !currentQueue) {
  13640. return;
  13641. }
  13642. draining = false;
  13643. if (currentQueue.length) {
  13644. queue = currentQueue.concat(queue);
  13645. } else {
  13646. queueIndex = -1;
  13647. }
  13648. if (queue.length) {
  13649. drainQueue();
  13650. }
  13651. }
  13652. function drainQueue() {
  13653. if (draining) {
  13654. return;
  13655. }
  13656. var timeout = runTimeout(cleanUpNextTick);
  13657. draining = true;
  13658. var len = queue.length;
  13659. while (len) {
  13660. currentQueue = queue;
  13661. queue = [];
  13662. while (++queueIndex < len) {
  13663. if (currentQueue) {
  13664. currentQueue[queueIndex].run();
  13665. }
  13666. }
  13667. queueIndex = -1;
  13668. len = queue.length;
  13669. }
  13670. currentQueue = null;
  13671. draining = false;
  13672. runClearTimeout(timeout);
  13673. }
  13674. process.nextTick = function (fun) {
  13675. var args = new Array(arguments.length - 1);
  13676. if (arguments.length > 1) {
  13677. for (var i = 1; i < arguments.length; i++) {
  13678. args[i - 1] = arguments[i];
  13679. }
  13680. }
  13681. queue.push(new Item(fun, args));
  13682. if (queue.length === 1 && !draining) {
  13683. runTimeout(drainQueue);
  13684. }
  13685. };
  13686. function Item(fun, array) {
  13687. this.fun = fun;
  13688. this.array = array;
  13689. }
  13690. Item.prototype.run = function () {
  13691. this.fun.apply(null, this.array);
  13692. };
  13693. process.title = 'browser';
  13694. process.browser = true;
  13695. process.env = {};
  13696. process.argv = [];
  13697. process.version = '';
  13698. process.versions = {};
  13699. function noop() {
  13700. }
  13701. process.on = noop;
  13702. process.addListener = noop;
  13703. process.once = noop;
  13704. process.off = noop;
  13705. process.removeListener = noop;
  13706. process.removeAllListeners = noop;
  13707. process.emit = noop;
  13708. process.prependListener = noop;
  13709. process.prependOnceListener = noop;
  13710. process.listeners = function (name) {
  13711. return [];
  13712. };
  13713. process.binding = function (name) {
  13714. throw new Error('process.binding is not supported');
  13715. };
  13716. process.cwd = function () {
  13717. return '/';
  13718. };
  13719. process.chdir = function (dir) {
  13720. throw new Error('process.chdir is not supported');
  13721. };
  13722. process.umask = function () {
  13723. return 0;
  13724. };
  13725. },
  13726. {}
  13727. ],
  13728. 2: [
  13729. function (require, module, exports) {
  13730. (function (setImmediate) {
  13731. (function (root) {
  13732. var setTimeoutFunc = setTimeout;
  13733. function noop() {
  13734. }
  13735. function bind(fn, thisArg) {
  13736. return function () {
  13737. fn.apply(thisArg, arguments);
  13738. };
  13739. }
  13740. function Promise(fn) {
  13741. if (typeof this !== 'object')
  13742. throw new TypeError('Promises must be constructed via new');
  13743. if (typeof fn !== 'function')
  13744. throw new TypeError('not a function');
  13745. this._state = 0;
  13746. this._handled = false;
  13747. this._value = undefined;
  13748. this._deferreds = [];
  13749. doResolve(fn, this);
  13750. }
  13751. function handle(self, deferred) {
  13752. while (self._state === 3) {
  13753. self = self._value;
  13754. }
  13755. if (self._state === 0) {
  13756. self._deferreds.push(deferred);
  13757. return;
  13758. }
  13759. self._handled = true;
  13760. Promise._immediateFn(function () {
  13761. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  13762. if (cb === null) {
  13763. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  13764. return;
  13765. }
  13766. var ret;
  13767. try {
  13768. ret = cb(self._value);
  13769. } catch (e) {
  13770. reject(deferred.promise, e);
  13771. return;
  13772. }
  13773. resolve(deferred.promise, ret);
  13774. });
  13775. }
  13776. function resolve(self, newValue) {
  13777. try {
  13778. if (newValue === self)
  13779. throw new TypeError('A promise cannot be resolved with itself.');
  13780. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  13781. var then = newValue.then;
  13782. if (newValue instanceof Promise) {
  13783. self._state = 3;
  13784. self._value = newValue;
  13785. finale(self);
  13786. return;
  13787. } else if (typeof then === 'function') {
  13788. doResolve(bind(then, newValue), self);
  13789. return;
  13790. }
  13791. }
  13792. self._state = 1;
  13793. self._value = newValue;
  13794. finale(self);
  13795. } catch (e) {
  13796. reject(self, e);
  13797. }
  13798. }
  13799. function reject(self, newValue) {
  13800. self._state = 2;
  13801. self._value = newValue;
  13802. finale(self);
  13803. }
  13804. function finale(self) {
  13805. if (self._state === 2 && self._deferreds.length === 0) {
  13806. Promise._immediateFn(function () {
  13807. if (!self._handled) {
  13808. Promise._unhandledRejectionFn(self._value);
  13809. }
  13810. });
  13811. }
  13812. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  13813. handle(self, self._deferreds[i]);
  13814. }
  13815. self._deferreds = null;
  13816. }
  13817. function Handler(onFulfilled, onRejected, promise) {
  13818. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  13819. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  13820. this.promise = promise;
  13821. }
  13822. function doResolve(fn, self) {
  13823. var done = false;
  13824. try {
  13825. fn(function (value) {
  13826. if (done)
  13827. return;
  13828. done = true;
  13829. resolve(self, value);
  13830. }, function (reason) {
  13831. if (done)
  13832. return;
  13833. done = true;
  13834. reject(self, reason);
  13835. });
  13836. } catch (ex) {
  13837. if (done)
  13838. return;
  13839. done = true;
  13840. reject(self, ex);
  13841. }
  13842. }
  13843. Promise.prototype['catch'] = function (onRejected) {
  13844. return this.then(null, onRejected);
  13845. };
  13846. Promise.prototype.then = function (onFulfilled, onRejected) {
  13847. var prom = new this.constructor(noop);
  13848. handle(this, new Handler(onFulfilled, onRejected, prom));
  13849. return prom;
  13850. };
  13851. Promise.all = function (arr) {
  13852. var args = Array.prototype.slice.call(arr);
  13853. return new Promise(function (resolve, reject) {
  13854. if (args.length === 0)
  13855. return resolve([]);
  13856. var remaining = args.length;
  13857. function res(i, val) {
  13858. try {
  13859. if (val && (typeof val === 'object' || typeof val === 'function')) {
  13860. var then = val.then;
  13861. if (typeof then === 'function') {
  13862. then.call(val, function (val) {
  13863. res(i, val);
  13864. }, reject);
  13865. return;
  13866. }
  13867. }
  13868. args[i] = val;
  13869. if (--remaining === 0) {
  13870. resolve(args);
  13871. }
  13872. } catch (ex) {
  13873. reject(ex);
  13874. }
  13875. }
  13876. for (var i = 0; i < args.length; i++) {
  13877. res(i, args[i]);
  13878. }
  13879. });
  13880. };
  13881. Promise.resolve = function (value) {
  13882. if (value && typeof value === 'object' && value.constructor === Promise) {
  13883. return value;
  13884. }
  13885. return new Promise(function (resolve) {
  13886. resolve(value);
  13887. });
  13888. };
  13889. Promise.reject = function (value) {
  13890. return new Promise(function (resolve, reject) {
  13891. reject(value);
  13892. });
  13893. };
  13894. Promise.race = function (values) {
  13895. return new Promise(function (resolve, reject) {
  13896. for (var i = 0, len = values.length; i < len; i++) {
  13897. values[i].then(resolve, reject);
  13898. }
  13899. });
  13900. };
  13901. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  13902. setImmediate(fn);
  13903. } : function (fn) {
  13904. setTimeoutFunc(fn, 0);
  13905. };
  13906. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  13907. if (typeof console !== 'undefined' && console) {
  13908. console.warn('Possible Unhandled Promise Rejection:', err);
  13909. }
  13910. };
  13911. Promise._setImmediateFn = function _setImmediateFn(fn) {
  13912. Promise._immediateFn = fn;
  13913. };
  13914. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  13915. Promise._unhandledRejectionFn = fn;
  13916. };
  13917. if (typeof module !== 'undefined' && module.exports) {
  13918. module.exports = Promise;
  13919. } else if (!root.Promise) {
  13920. root.Promise = Promise;
  13921. }
  13922. }(this));
  13923. }.call(this, require('timers').setImmediate));
  13924. },
  13925. { 'timers': 3 }
  13926. ],
  13927. 3: [
  13928. function (require, module, exports) {
  13929. (function (setImmediate, clearImmediate) {
  13930. var nextTick = require('process/browser.js').nextTick;
  13931. var apply = Function.prototype.apply;
  13932. var slice = Array.prototype.slice;
  13933. var immediateIds = {};
  13934. var nextImmediateId = 0;
  13935. exports.setTimeout = function () {
  13936. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  13937. };
  13938. exports.setInterval = function () {
  13939. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  13940. };
  13941. exports.clearTimeout = exports.clearInterval = function (timeout) {
  13942. timeout.close();
  13943. };
  13944. function Timeout(id, clearFn) {
  13945. this._id = id;
  13946. this._clearFn = clearFn;
  13947. }
  13948. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  13949. };
  13950. Timeout.prototype.close = function () {
  13951. this._clearFn.call(window, this._id);
  13952. };
  13953. exports.enroll = function (item, msecs) {
  13954. clearTimeout(item._idleTimeoutId);
  13955. item._idleTimeout = msecs;
  13956. };
  13957. exports.unenroll = function (item) {
  13958. clearTimeout(item._idleTimeoutId);
  13959. item._idleTimeout = -1;
  13960. };
  13961. exports._unrefActive = exports.active = function (item) {
  13962. clearTimeout(item._idleTimeoutId);
  13963. var msecs = item._idleTimeout;
  13964. if (msecs >= 0) {
  13965. item._idleTimeoutId = setTimeout(function onTimeout() {
  13966. if (item._onTimeout)
  13967. item._onTimeout();
  13968. }, msecs);
  13969. }
  13970. };
  13971. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  13972. var id = nextImmediateId++;
  13973. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13974. immediateIds[id] = true;
  13975. nextTick(function onNextTick() {
  13976. if (immediateIds[id]) {
  13977. if (args) {
  13978. fn.apply(null, args);
  13979. } else {
  13980. fn.call(null);
  13981. }
  13982. exports.clearImmediate(id);
  13983. }
  13984. });
  13985. return id;
  13986. };
  13987. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  13988. delete immediateIds[id];
  13989. };
  13990. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  13991. },
  13992. {
  13993. 'process/browser.js': 1,
  13994. 'timers': 3
  13995. }
  13996. ],
  13997. 4: [
  13998. function (require, module, exports) {
  13999. var promisePolyfill = require('promise-polyfill');
  14000. var Global = function () {
  14001. if (typeof window !== 'undefined') {
  14002. return window;
  14003. } else {
  14004. return Function('return this;')();
  14005. }
  14006. }();
  14007. module.exports = { boltExport: Global.Promise || promisePolyfill };
  14008. },
  14009. { 'promise-polyfill': 2 }
  14010. ]
  14011. }, {}, [4])(4);
  14012. }));
  14013. }(undefined, exports$1, module, undefined));
  14014. var Promise$2 = module.exports.boltExport;
  14015. var nu$3 = function (baseFn) {
  14016. var data = Optional.none();
  14017. var callbacks = [];
  14018. var map = function (f) {
  14019. return nu$3(function (nCallback) {
  14020. get(function (data) {
  14021. nCallback(f(data));
  14022. });
  14023. });
  14024. };
  14025. var get = function (nCallback) {
  14026. if (isReady()) {
  14027. call(nCallback);
  14028. } else {
  14029. callbacks.push(nCallback);
  14030. }
  14031. };
  14032. var set = function (x) {
  14033. if (!isReady()) {
  14034. data = Optional.some(x);
  14035. run(callbacks);
  14036. callbacks = [];
  14037. }
  14038. };
  14039. var isReady = function () {
  14040. return data.isSome();
  14041. };
  14042. var run = function (cbs) {
  14043. each$1(cbs, call);
  14044. };
  14045. var call = function (cb) {
  14046. data.each(function (x) {
  14047. setTimeout(function () {
  14048. cb(x);
  14049. }, 0);
  14050. });
  14051. };
  14052. baseFn(set);
  14053. return {
  14054. get: get,
  14055. map: map,
  14056. isReady: isReady
  14057. };
  14058. };
  14059. var pure$1 = function (a) {
  14060. return nu$3(function (callback) {
  14061. callback(a);
  14062. });
  14063. };
  14064. var LazyValue = {
  14065. nu: nu$3,
  14066. pure: pure$1
  14067. };
  14068. var errorReporter = function (err) {
  14069. setTimeout(function () {
  14070. throw err;
  14071. }, 0);
  14072. };
  14073. var make$5 = function (run) {
  14074. var get = function (callback) {
  14075. run().then(callback, errorReporter);
  14076. };
  14077. var map = function (fab) {
  14078. return make$5(function () {
  14079. return run().then(fab);
  14080. });
  14081. };
  14082. var bind = function (aFutureB) {
  14083. return make$5(function () {
  14084. return run().then(function (v) {
  14085. return aFutureB(v).toPromise();
  14086. });
  14087. });
  14088. };
  14089. var anonBind = function (futureB) {
  14090. return make$5(function () {
  14091. return run().then(function () {
  14092. return futureB.toPromise();
  14093. });
  14094. });
  14095. };
  14096. var toLazy = function () {
  14097. return LazyValue.nu(get);
  14098. };
  14099. var toCached = function () {
  14100. var cache = null;
  14101. return make$5(function () {
  14102. if (cache === null) {
  14103. cache = run();
  14104. }
  14105. return cache;
  14106. });
  14107. };
  14108. var toPromise = run;
  14109. return {
  14110. map: map,
  14111. bind: bind,
  14112. anonBind: anonBind,
  14113. toLazy: toLazy,
  14114. toCached: toCached,
  14115. toPromise: toPromise,
  14116. get: get
  14117. };
  14118. };
  14119. var nu$2 = function (baseFn) {
  14120. return make$5(function () {
  14121. return new Promise$2(baseFn);
  14122. });
  14123. };
  14124. var pure = function (a) {
  14125. return make$5(function () {
  14126. return Promise$2.resolve(a);
  14127. });
  14128. };
  14129. var Future = {
  14130. nu: nu$2,
  14131. pure: pure
  14132. };
  14133. var ariaElements = [
  14134. 'input',
  14135. 'textarea'
  14136. ];
  14137. var isAriaElement = function (elem) {
  14138. var name = name$2(elem);
  14139. return contains$2(ariaElements, name);
  14140. };
  14141. var markValid = function (component, invalidConfig) {
  14142. var elem = invalidConfig.getRoot(component).getOr(component.element);
  14143. remove$3(elem, invalidConfig.invalidClass);
  14144. invalidConfig.notify.each(function (notifyInfo) {
  14145. if (isAriaElement(component.element)) {
  14146. set$7(component.element, 'aria-invalid', false);
  14147. }
  14148. notifyInfo.getContainer(component).each(function (container) {
  14149. set$8(container, notifyInfo.validHtml);
  14150. });
  14151. notifyInfo.onValid(component);
  14152. });
  14153. };
  14154. var markInvalid = function (component, invalidConfig, invalidState, text) {
  14155. var elem = invalidConfig.getRoot(component).getOr(component.element);
  14156. add$2(elem, invalidConfig.invalidClass);
  14157. invalidConfig.notify.each(function (notifyInfo) {
  14158. if (isAriaElement(component.element)) {
  14159. set$7(component.element, 'aria-invalid', true);
  14160. }
  14161. notifyInfo.getContainer(component).each(function (container) {
  14162. set$8(container, text);
  14163. });
  14164. notifyInfo.onInvalid(component, text);
  14165. });
  14166. };
  14167. var query = function (component, invalidConfig, _invalidState) {
  14168. return invalidConfig.validator.fold(function () {
  14169. return Future.pure(Result.value(true));
  14170. }, function (validatorInfo) {
  14171. return validatorInfo.validate(component);
  14172. });
  14173. };
  14174. var run = function (component, invalidConfig, invalidState) {
  14175. invalidConfig.notify.each(function (notifyInfo) {
  14176. notifyInfo.onValidate(component);
  14177. });
  14178. return query(component, invalidConfig).map(function (valid) {
  14179. if (component.getSystem().isConnected()) {
  14180. return valid.fold(function (err) {
  14181. markInvalid(component, invalidConfig, invalidState, err);
  14182. return Result.error(err);
  14183. }, function (v) {
  14184. markValid(component, invalidConfig);
  14185. return Result.value(v);
  14186. });
  14187. } else {
  14188. return Result.error('No longer in system');
  14189. }
  14190. });
  14191. };
  14192. var isInvalid = function (component, invalidConfig) {
  14193. var elem = invalidConfig.getRoot(component).getOr(component.element);
  14194. return has(elem, invalidConfig.invalidClass);
  14195. };
  14196. var InvalidateApis = /*#__PURE__*/Object.freeze({
  14197. __proto__: null,
  14198. markValid: markValid,
  14199. markInvalid: markInvalid,
  14200. query: query,
  14201. run: run,
  14202. isInvalid: isInvalid
  14203. });
  14204. var events$8 = function (invalidConfig, invalidState) {
  14205. return invalidConfig.validator.map(function (validatorInfo) {
  14206. return derive$2([run$1(validatorInfo.onEvent, function (component) {
  14207. run(component, invalidConfig, invalidState).get(identity$1);
  14208. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  14209. run(component, invalidConfig, invalidState).get(noop);
  14210. })] : []));
  14211. }).getOr({});
  14212. };
  14213. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  14214. __proto__: null,
  14215. events: events$8
  14216. });
  14217. var InvalidateSchema = [
  14218. required$1('invalidClass'),
  14219. defaulted('getRoot', Optional.none),
  14220. optionObjOf('notify', [
  14221. defaulted('aria', 'alert'),
  14222. defaulted('getContainer', Optional.none),
  14223. defaulted('validHtml', ''),
  14224. onHandler('onValid'),
  14225. onHandler('onInvalid'),
  14226. onHandler('onValidate')
  14227. ]),
  14228. optionObjOf('validator', [
  14229. required$1('validate'),
  14230. defaulted('onEvent', 'input'),
  14231. defaulted('validateOnLoad', true)
  14232. ])
  14233. ];
  14234. var Invalidating = create$7({
  14235. fields: InvalidateSchema,
  14236. name: 'invalidating',
  14237. active: ActiveInvalidate,
  14238. apis: InvalidateApis,
  14239. extra: {
  14240. validation: function (validator) {
  14241. return function (component) {
  14242. var v = Representing.getValue(component);
  14243. return Future.pure(validator(v));
  14244. };
  14245. }
  14246. }
  14247. });
  14248. var getCoupled = function (component, coupleConfig, coupleState, name) {
  14249. return coupleState.getOrCreate(component, coupleConfig, name);
  14250. };
  14251. var CouplingApis = /*#__PURE__*/Object.freeze({
  14252. __proto__: null,
  14253. getCoupled: getCoupled
  14254. });
  14255. var CouplingSchema = [requiredOf('others', setOf(Result.value, anyValue()))];
  14256. var init$a = function () {
  14257. var coupled = {};
  14258. var getOrCreate = function (component, coupleConfig, name) {
  14259. var available = keys(coupleConfig.others);
  14260. if (!available) {
  14261. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  14262. } else {
  14263. return get$e(coupled, name).getOrThunk(function () {
  14264. var builder = get$e(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  14265. var spec = builder(component);
  14266. var built = component.getSystem().build(spec);
  14267. coupled[name] = built;
  14268. return built;
  14269. });
  14270. }
  14271. };
  14272. var readState = constant$1({});
  14273. return nu$8({
  14274. readState: readState,
  14275. getOrCreate: getOrCreate
  14276. });
  14277. };
  14278. var CouplingState = /*#__PURE__*/Object.freeze({
  14279. __proto__: null,
  14280. init: init$a
  14281. });
  14282. var Coupling = create$7({
  14283. fields: CouplingSchema,
  14284. name: 'coupling',
  14285. apis: CouplingApis,
  14286. state: CouplingState
  14287. });
  14288. var suffix = constant$1('sink');
  14289. var partType$1 = constant$1(optional({
  14290. name: suffix(),
  14291. overrides: constant$1({
  14292. dom: { tag: 'div' },
  14293. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  14294. events: derive$2([
  14295. cutter(keydown()),
  14296. cutter(mousedown()),
  14297. cutter(click())
  14298. ])
  14299. })
  14300. }));
  14301. var HighlightOnOpen;
  14302. (function (HighlightOnOpen) {
  14303. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  14304. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  14305. }(HighlightOnOpen || (HighlightOnOpen = {})));
  14306. var getAnchor = function (detail, component) {
  14307. var hotspot = detail.getHotspot(component).getOr(component);
  14308. var type = 'hotspot';
  14309. var overrides = detail.getAnchorOverrides();
  14310. return detail.layouts.fold(function () {
  14311. return {
  14312. type: type,
  14313. hotspot: hotspot,
  14314. overrides: overrides
  14315. };
  14316. }, function (layouts) {
  14317. return {
  14318. type: type,
  14319. hotspot: hotspot,
  14320. overrides: overrides,
  14321. layouts: layouts
  14322. };
  14323. });
  14324. };
  14325. var fetch = function (detail, mapFetch, component) {
  14326. var fetcher = detail.fetch;
  14327. return fetcher(component).map(mapFetch);
  14328. };
  14329. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  14330. var futureData = fetch(detail, mapFetch, component);
  14331. var getLazySink = getSink(component, detail);
  14332. return futureData.map(function (tdata) {
  14333. return tdata.bind(function (data) {
  14334. return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  14335. uid: generate$5(''),
  14336. data: data,
  14337. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  14338. onOpenMenu: function (tmenu, menu) {
  14339. var sink = getLazySink().getOrDie();
  14340. Positioning.position(sink, menu, { anchor: anchor });
  14341. Sandboxing.decloak(sandbox);
  14342. },
  14343. onOpenSubmenu: function (tmenu, item, submenu) {
  14344. var sink = getLazySink().getOrDie();
  14345. Positioning.position(sink, submenu, {
  14346. anchor: {
  14347. type: 'submenu',
  14348. item: item
  14349. }
  14350. });
  14351. Sandboxing.decloak(sandbox);
  14352. },
  14353. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  14354. var sink = getLazySink().getOrDie();
  14355. Positioning.position(sink, primaryMenu, { anchor: anchor });
  14356. each$1(submenuTriggers, function (st) {
  14357. Positioning.position(sink, st.triggeredMenu, {
  14358. anchor: {
  14359. type: 'submenu',
  14360. item: st.triggeringItem
  14361. }
  14362. });
  14363. });
  14364. },
  14365. onEscape: function () {
  14366. Focusing.focus(component);
  14367. Sandboxing.close(sandbox);
  14368. return Optional.some(true);
  14369. }
  14370. })));
  14371. });
  14372. });
  14373. };
  14374. var open = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  14375. var anchor = getAnchor(detail, hotspot);
  14376. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  14377. return processed.map(function (tdata) {
  14378. tdata.fold(function () {
  14379. if (Sandboxing.isOpen(sandbox)) {
  14380. Sandboxing.close(sandbox);
  14381. }
  14382. }, function (data) {
  14383. Sandboxing.cloak(sandbox);
  14384. Sandboxing.open(sandbox, data);
  14385. onOpenSync(sandbox);
  14386. });
  14387. return sandbox;
  14388. });
  14389. };
  14390. var close = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  14391. Sandboxing.close(sandbox);
  14392. return Future.pure(sandbox);
  14393. };
  14394. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  14395. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  14396. var showing = Sandboxing.isOpen(sandbox);
  14397. var action = showing ? close : open;
  14398. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  14399. };
  14400. var matchWidth = function (hotspot, container, useMinWidth) {
  14401. var menu = Composing.getCurrent(container).getOr(container);
  14402. var buttonWidth = get$7(hotspot.element);
  14403. if (useMinWidth) {
  14404. set$6(menu.element, 'min-width', buttonWidth + 'px');
  14405. } else {
  14406. set$4(menu.element, buttonWidth);
  14407. }
  14408. };
  14409. var getSink = function (anyInSystem, sinkDetail) {
  14410. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  14411. return function () {
  14412. return Result.value(internalSink);
  14413. };
  14414. }).getOrThunk(function () {
  14415. return sinkDetail.lazySink.fold(function () {
  14416. return function () {
  14417. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  14418. };
  14419. }, function (lazySinkFn) {
  14420. return function () {
  14421. return lazySinkFn(anyInSystem);
  14422. };
  14423. });
  14424. });
  14425. };
  14426. var doRepositionMenus = function (sandbox) {
  14427. Sandboxing.getState(sandbox).each(function (tmenu) {
  14428. tieredMenu.repositionMenus(tmenu);
  14429. });
  14430. };
  14431. var makeSandbox$1 = function (detail, hotspot, extras) {
  14432. var ariaOwner = manager();
  14433. var onOpen = function (component, menu) {
  14434. var anchor = getAnchor(detail, hotspot);
  14435. ariaOwner.link(hotspot.element);
  14436. if (detail.matchWidth) {
  14437. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  14438. }
  14439. detail.onOpen(anchor, component, menu);
  14440. if (extras !== undefined && extras.onOpen !== undefined) {
  14441. extras.onOpen(component, menu);
  14442. }
  14443. };
  14444. var onClose = function (component, menu) {
  14445. ariaOwner.unlink(hotspot.element);
  14446. if (extras !== undefined && extras.onClose !== undefined) {
  14447. extras.onClose(component, menu);
  14448. }
  14449. };
  14450. var lazySink = getSink(hotspot, detail);
  14451. return {
  14452. dom: {
  14453. tag: 'div',
  14454. classes: detail.sandboxClasses,
  14455. attributes: {
  14456. id: ariaOwner.id,
  14457. role: 'listbox'
  14458. }
  14459. },
  14460. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  14461. Representing.config({
  14462. store: {
  14463. mode: 'memory',
  14464. initialValue: hotspot
  14465. }
  14466. }),
  14467. Sandboxing.config({
  14468. onOpen: onOpen,
  14469. onClose: onClose,
  14470. isPartOf: function (container, data, queryElem) {
  14471. return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
  14472. },
  14473. getAttachPoint: function () {
  14474. return lazySink().getOrDie();
  14475. }
  14476. }),
  14477. Composing.config({
  14478. find: function (sandbox) {
  14479. return Sandboxing.getState(sandbox).bind(function (menu) {
  14480. return Composing.getCurrent(menu);
  14481. });
  14482. }
  14483. }),
  14484. Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) })
  14485. ])
  14486. };
  14487. };
  14488. var repositionMenus = function (comp) {
  14489. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  14490. doRepositionMenus(sandbox);
  14491. };
  14492. var sandboxFields = function () {
  14493. return [
  14494. defaulted('sandboxClasses', []),
  14495. SketchBehaviours.field('sandboxBehaviours', [
  14496. Composing,
  14497. Receiving,
  14498. Sandboxing,
  14499. Representing
  14500. ])
  14501. ];
  14502. };
  14503. var schema$j = constant$1([
  14504. required$1('dom'),
  14505. required$1('fetch'),
  14506. onHandler('onOpen'),
  14507. onKeyboardHandler('onExecute'),
  14508. defaulted('getHotspot', Optional.some),
  14509. defaulted('getAnchorOverrides', constant$1({})),
  14510. schema$y(),
  14511. field('dropdownBehaviours', [
  14512. Toggling,
  14513. Coupling,
  14514. Keying,
  14515. Focusing
  14516. ]),
  14517. required$1('toggleClass'),
  14518. defaulted('eventOrder', {}),
  14519. option('lazySink'),
  14520. defaulted('matchWidth', false),
  14521. defaulted('useMinWidth', false),
  14522. option('role')
  14523. ].concat(sandboxFields()));
  14524. var parts$d = constant$1([
  14525. external$1({
  14526. schema: [tieredMenuMarkers()],
  14527. name: 'menu',
  14528. defaults: function (detail) {
  14529. return { onExecute: detail.onExecute };
  14530. }
  14531. }),
  14532. partType$1()
  14533. ]);
  14534. var factory$g = function (detail, components, _spec, externals) {
  14535. var _a;
  14536. var lookupAttr = function (attr) {
  14537. return get$e(detail.dom, 'attributes').bind(function (attrs) {
  14538. return get$e(attrs, attr);
  14539. });
  14540. };
  14541. var switchToMenu = function (sandbox) {
  14542. Sandboxing.getState(sandbox).each(function (tmenu) {
  14543. tieredMenu.highlightPrimary(tmenu);
  14544. });
  14545. };
  14546. var action = function (component) {
  14547. var onOpenSync = switchToMenu;
  14548. togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  14549. };
  14550. var apis = {
  14551. expand: function (comp) {
  14552. if (!Toggling.isOn(comp)) {
  14553. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  14554. }
  14555. },
  14556. open: function (comp) {
  14557. if (!Toggling.isOn(comp)) {
  14558. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  14559. }
  14560. },
  14561. isOpen: Toggling.isOn,
  14562. close: function (comp) {
  14563. if (Toggling.isOn(comp)) {
  14564. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  14565. }
  14566. },
  14567. repositionMenus: function (comp) {
  14568. if (Toggling.isOn(comp)) {
  14569. repositionMenus(comp);
  14570. }
  14571. }
  14572. };
  14573. var triggerExecute = function (comp, _se) {
  14574. emitExecute(comp);
  14575. return Optional.some(true);
  14576. };
  14577. return {
  14578. uid: detail.uid,
  14579. dom: detail.dom,
  14580. components: components,
  14581. behaviours: augment(detail.dropdownBehaviours, [
  14582. Toggling.config({
  14583. toggleClass: detail.toggleClass,
  14584. aria: { mode: 'expanded' }
  14585. }),
  14586. Coupling.config({
  14587. others: {
  14588. sandbox: function (hotspot) {
  14589. return makeSandbox$1(detail, hotspot, {
  14590. onOpen: function () {
  14591. return Toggling.on(hotspot);
  14592. },
  14593. onClose: function () {
  14594. return Toggling.off(hotspot);
  14595. }
  14596. });
  14597. }
  14598. }
  14599. }),
  14600. Keying.config({
  14601. mode: 'special',
  14602. onSpace: triggerExecute,
  14603. onEnter: triggerExecute,
  14604. onDown: function (comp, _se) {
  14605. if (Dropdown.isOpen(comp)) {
  14606. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  14607. switchToMenu(sandbox);
  14608. } else {
  14609. Dropdown.open(comp);
  14610. }
  14611. return Optional.some(true);
  14612. },
  14613. onEscape: function (comp, _se) {
  14614. if (Dropdown.isOpen(comp)) {
  14615. Dropdown.close(comp);
  14616. return Optional.some(true);
  14617. } else {
  14618. return Optional.none();
  14619. }
  14620. }
  14621. }),
  14622. Focusing.config({})
  14623. ]),
  14624. events: events$a(Optional.some(action)),
  14625. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  14626. 'disabling',
  14627. 'toggling',
  14628. 'alloy.base.behaviour'
  14629. ], _a)),
  14630. apis: apis,
  14631. domModification: {
  14632. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  14633. return {};
  14634. }, function (role) {
  14635. return { role: role };
  14636. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  14637. }
  14638. };
  14639. };
  14640. var Dropdown = composite({
  14641. name: 'Dropdown',
  14642. configFields: schema$j(),
  14643. partFields: parts$d(),
  14644. factory: factory$g,
  14645. apis: {
  14646. open: function (apis, comp) {
  14647. return apis.open(comp);
  14648. },
  14649. expand: function (apis, comp) {
  14650. return apis.expand(comp);
  14651. },
  14652. close: function (apis, comp) {
  14653. return apis.close(comp);
  14654. },
  14655. isOpen: function (apis, comp) {
  14656. return apis.isOpen(comp);
  14657. },
  14658. repositionMenus: function (apis, comp) {
  14659. return apis.repositionMenus(comp);
  14660. }
  14661. }
  14662. });
  14663. var exhibit$1 = function () {
  14664. return nu$7({
  14665. styles: {
  14666. '-webkit-user-select': 'none',
  14667. 'user-select': 'none',
  14668. '-ms-user-select': 'none',
  14669. '-moz-user-select': '-moz-none'
  14670. },
  14671. attributes: { unselectable: 'on' }
  14672. });
  14673. };
  14674. var events$7 = function () {
  14675. return derive$2([abort(selectstart(), always)]);
  14676. };
  14677. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  14678. __proto__: null,
  14679. events: events$7,
  14680. exhibit: exhibit$1
  14681. });
  14682. var Unselecting = create$7({
  14683. fields: [],
  14684. name: 'unselecting',
  14685. active: ActiveUnselecting
  14686. });
  14687. var renderPanelButton = function (spec, sharedBackstage) {
  14688. return Dropdown.sketch({
  14689. dom: spec.dom,
  14690. components: spec.components,
  14691. toggleClass: 'mce-active',
  14692. dropdownBehaviours: derive$1([
  14693. DisablingConfigs.button(sharedBackstage.providers.isDisabled),
  14694. receivingConfig(),
  14695. Unselecting.config({}),
  14696. Tabstopping.config({})
  14697. ]),
  14698. layouts: spec.layouts,
  14699. sandboxClasses: ['tox-dialog__popups'],
  14700. lazySink: sharedBackstage.getSink,
  14701. fetch: function (comp) {
  14702. return Future.nu(function (callback) {
  14703. return spec.fetch(callback);
  14704. }).map(function (items) {
  14705. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  14706. spec.onItemAction(comp, value);
  14707. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  14708. });
  14709. },
  14710. parts: { menu: part(false, 1, spec.presets) }
  14711. });
  14712. };
  14713. var colorInputChangeEvent = generate$6('color-input-change');
  14714. var colorSwatchChangeEvent = generate$6('color-swatch-change');
  14715. var colorPickerCancelEvent = generate$6('color-picker-cancel');
  14716. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  14717. var pField = FormField.parts.field({
  14718. factory: Input,
  14719. inputClasses: ['tox-textfield'],
  14720. onSetValue: function (c) {
  14721. return Invalidating.run(c).get(noop);
  14722. },
  14723. inputBehaviours: derive$1([
  14724. Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
  14725. receivingConfig(),
  14726. Tabstopping.config({}),
  14727. Invalidating.config({
  14728. invalidClass: 'tox-textbox-field-invalid',
  14729. getRoot: function (comp) {
  14730. return parent(comp.element);
  14731. },
  14732. notify: {
  14733. onValid: function (comp) {
  14734. var val = Representing.getValue(comp);
  14735. emitWith(comp, colorInputChangeEvent, { color: val });
  14736. }
  14737. },
  14738. validator: {
  14739. validateOnLoad: false,
  14740. validate: function (input) {
  14741. var inputValue = Representing.getValue(input);
  14742. if (inputValue.length === 0) {
  14743. return Future.pure(Result.value(true));
  14744. } else {
  14745. var span = SugarElement.fromTag('span');
  14746. set$6(span, 'background-color', inputValue);
  14747. var res = getRaw(span, 'background-color').fold(function () {
  14748. return Result.error('blah');
  14749. }, function (_) {
  14750. return Result.value(inputValue);
  14751. });
  14752. return Future.pure(res);
  14753. }
  14754. }
  14755. }
  14756. })
  14757. ]),
  14758. selectOnFocus: false
  14759. });
  14760. var pLabel = spec.label.map(function (label) {
  14761. return renderLabel$2(label, sharedBackstage.providers);
  14762. });
  14763. var emitSwatchChange = function (colorBit, value) {
  14764. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  14765. };
  14766. var onItemAction = function (comp, value) {
  14767. memColorButton.getOpt(comp).each(function (colorBit) {
  14768. if (value === 'custom') {
  14769. colorInputBackstage.colorPicker(function (valueOpt) {
  14770. valueOpt.fold(function () {
  14771. return emit(colorBit, colorPickerCancelEvent);
  14772. }, function (value) {
  14773. emitSwatchChange(colorBit, value);
  14774. addColor(value);
  14775. });
  14776. }, '#ffffff');
  14777. } else if (value === 'remove') {
  14778. emitSwatchChange(colorBit, '');
  14779. } else {
  14780. emitSwatchChange(colorBit, value);
  14781. }
  14782. });
  14783. };
  14784. var memColorButton = record(renderPanelButton({
  14785. dom: {
  14786. tag: 'span',
  14787. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  14788. },
  14789. layouts: {
  14790. onRtl: function () {
  14791. return [
  14792. southwest$2,
  14793. southeast$2,
  14794. south$2
  14795. ];
  14796. },
  14797. onLtr: function () {
  14798. return [
  14799. southeast$2,
  14800. southwest$2,
  14801. south$2
  14802. ];
  14803. }
  14804. },
  14805. components: [],
  14806. fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  14807. columns: colorInputBackstage.getColorCols(),
  14808. presets: 'color',
  14809. onItemAction: onItemAction
  14810. }, sharedBackstage));
  14811. return FormField.sketch({
  14812. dom: {
  14813. tag: 'div',
  14814. classes: ['tox-form__group']
  14815. },
  14816. components: pLabel.toArray().concat([{
  14817. dom: {
  14818. tag: 'div',
  14819. classes: ['tox-color-input']
  14820. },
  14821. components: [
  14822. pField,
  14823. memColorButton.asSpec()
  14824. ]
  14825. }]),
  14826. fieldBehaviours: derive$1([config('form-field-events', [
  14827. run$1(colorInputChangeEvent, function (comp, se) {
  14828. memColorButton.getOpt(comp).each(function (colorButton) {
  14829. set$6(colorButton.element, 'background-color', se.event.color);
  14830. });
  14831. emitWith(comp, formChangeEvent, { name: spec.name });
  14832. }),
  14833. run$1(colorSwatchChangeEvent, function (comp, se) {
  14834. FormField.getField(comp).each(function (field) {
  14835. Representing.setValue(field, se.event.value);
  14836. Composing.getCurrent(comp).each(Focusing.focus);
  14837. });
  14838. }),
  14839. run$1(colorPickerCancelEvent, function (comp, _se) {
  14840. FormField.getField(comp).each(function (_field) {
  14841. Composing.getCurrent(comp).each(Focusing.focus);
  14842. });
  14843. })
  14844. ])])
  14845. });
  14846. };
  14847. var labelPart = optional({
  14848. schema: [required$1('dom')],
  14849. name: 'label'
  14850. });
  14851. var edgePart = function (name) {
  14852. return optional({
  14853. name: '' + name + '-edge',
  14854. overrides: function (detail) {
  14855. var action = detail.model.manager.edgeActions[name];
  14856. return action.fold(function () {
  14857. return {};
  14858. }, function (a) {
  14859. return {
  14860. events: derive$2([
  14861. runActionExtra(touchstart(), function (comp, se, d) {
  14862. return a(comp, d);
  14863. }, [detail]),
  14864. runActionExtra(mousedown(), function (comp, se, d) {
  14865. return a(comp, d);
  14866. }, [detail]),
  14867. runActionExtra(mousemove(), function (comp, se, det) {
  14868. if (det.mouseIsDown.get()) {
  14869. a(comp, det);
  14870. }
  14871. }, [detail])
  14872. ])
  14873. };
  14874. });
  14875. }
  14876. });
  14877. };
  14878. var tlEdgePart = edgePart('top-left');
  14879. var tedgePart = edgePart('top');
  14880. var trEdgePart = edgePart('top-right');
  14881. var redgePart = edgePart('right');
  14882. var brEdgePart = edgePart('bottom-right');
  14883. var bedgePart = edgePart('bottom');
  14884. var blEdgePart = edgePart('bottom-left');
  14885. var ledgePart = edgePart('left');
  14886. var thumbPart = required({
  14887. name: 'thumb',
  14888. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  14889. overrides: function (detail) {
  14890. return {
  14891. events: derive$2([
  14892. redirectToPart(touchstart(), detail, 'spectrum'),
  14893. redirectToPart(touchmove(), detail, 'spectrum'),
  14894. redirectToPart(touchend(), detail, 'spectrum'),
  14895. redirectToPart(mousedown(), detail, 'spectrum'),
  14896. redirectToPart(mousemove(), detail, 'spectrum'),
  14897. redirectToPart(mouseup(), detail, 'spectrum')
  14898. ])
  14899. };
  14900. }
  14901. });
  14902. var spectrumPart = required({
  14903. schema: [customField('mouseIsDown', function () {
  14904. return Cell(false);
  14905. })],
  14906. name: 'spectrum',
  14907. overrides: function (detail) {
  14908. var modelDetail = detail.model;
  14909. var model = modelDetail.manager;
  14910. var setValueFrom = function (component, simulatedEvent) {
  14911. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14912. return model.setValueFrom(component, detail, value);
  14913. });
  14914. };
  14915. return {
  14916. behaviours: derive$1([
  14917. Keying.config({
  14918. mode: 'special',
  14919. onLeft: function (spectrum) {
  14920. return model.onLeft(spectrum, detail);
  14921. },
  14922. onRight: function (spectrum) {
  14923. return model.onRight(spectrum, detail);
  14924. },
  14925. onUp: function (spectrum) {
  14926. return model.onUp(spectrum, detail);
  14927. },
  14928. onDown: function (spectrum) {
  14929. return model.onDown(spectrum, detail);
  14930. }
  14931. }),
  14932. Focusing.config({})
  14933. ]),
  14934. events: derive$2([
  14935. run$1(touchstart(), setValueFrom),
  14936. run$1(touchmove(), setValueFrom),
  14937. run$1(mousedown(), setValueFrom),
  14938. run$1(mousemove(), function (spectrum, se) {
  14939. if (detail.mouseIsDown.get()) {
  14940. setValueFrom(spectrum, se);
  14941. }
  14942. })
  14943. ])
  14944. };
  14945. }
  14946. });
  14947. var SliderParts = [
  14948. labelPart,
  14949. ledgePart,
  14950. redgePart,
  14951. tedgePart,
  14952. bedgePart,
  14953. tlEdgePart,
  14954. trEdgePart,
  14955. blEdgePart,
  14956. brEdgePart,
  14957. thumbPart,
  14958. spectrumPart
  14959. ];
  14960. var _sliderChangeEvent = 'slider.change.value';
  14961. var sliderChangeEvent = constant$1(_sliderChangeEvent);
  14962. var isTouchEvent$1 = function (evt) {
  14963. return evt.type.indexOf('touch') !== -1;
  14964. };
  14965. var getEventSource = function (simulatedEvent) {
  14966. var evt = simulatedEvent.event.raw;
  14967. if (isTouchEvent$1(evt)) {
  14968. var touchEvent = evt;
  14969. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  14970. return SugarPosition(t.clientX, t.clientY);
  14971. }) : Optional.none();
  14972. } else {
  14973. var mouseEvent = evt;
  14974. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  14975. return SugarPosition(me.clientX, me.clientY);
  14976. }) : Optional.none();
  14977. }
  14978. };
  14979. var t = 'top', r = 'right', b = 'bottom', l = 'left';
  14980. var minX = function (detail) {
  14981. return detail.model.minX;
  14982. };
  14983. var minY = function (detail) {
  14984. return detail.model.minY;
  14985. };
  14986. var min1X = function (detail) {
  14987. return detail.model.minX - 1;
  14988. };
  14989. var min1Y = function (detail) {
  14990. return detail.model.minY - 1;
  14991. };
  14992. var maxX = function (detail) {
  14993. return detail.model.maxX;
  14994. };
  14995. var maxY = function (detail) {
  14996. return detail.model.maxY;
  14997. };
  14998. var max1X = function (detail) {
  14999. return detail.model.maxX + 1;
  15000. };
  15001. var max1Y = function (detail) {
  15002. return detail.model.maxY + 1;
  15003. };
  15004. var range = function (detail, max, min) {
  15005. return max(detail) - min(detail);
  15006. };
  15007. var xRange = function (detail) {
  15008. return range(detail, maxX, minX);
  15009. };
  15010. var yRange = function (detail) {
  15011. return range(detail, maxY, minY);
  15012. };
  15013. var halfX = function (detail) {
  15014. return xRange(detail) / 2;
  15015. };
  15016. var halfY = function (detail) {
  15017. return yRange(detail) / 2;
  15018. };
  15019. var step = function (detail) {
  15020. return detail.stepSize;
  15021. };
  15022. var snap = function (detail) {
  15023. return detail.snapToGrid;
  15024. };
  15025. var snapStart = function (detail) {
  15026. return detail.snapStart;
  15027. };
  15028. var rounded = function (detail) {
  15029. return detail.rounded;
  15030. };
  15031. var hasEdge = function (detail, edgeName) {
  15032. return detail[edgeName + '-edge'] !== undefined;
  15033. };
  15034. var hasLEdge = function (detail) {
  15035. return hasEdge(detail, l);
  15036. };
  15037. var hasREdge = function (detail) {
  15038. return hasEdge(detail, r);
  15039. };
  15040. var hasTEdge = function (detail) {
  15041. return hasEdge(detail, t);
  15042. };
  15043. var hasBEdge = function (detail) {
  15044. return hasEdge(detail, b);
  15045. };
  15046. var currentValue = function (detail) {
  15047. return detail.model.value.get();
  15048. };
  15049. var xValue = function (x) {
  15050. return { x: x };
  15051. };
  15052. var yValue = function (y) {
  15053. return { y: y };
  15054. };
  15055. var xyValue = function (x, y) {
  15056. return {
  15057. x: x,
  15058. y: y
  15059. };
  15060. };
  15061. var fireSliderChange$3 = function (component, value) {
  15062. emitWith(component, sliderChangeEvent(), { value: value });
  15063. };
  15064. var setToTLEdgeXY = function (edge, detail) {
  15065. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  15066. };
  15067. var setToTEdge = function (edge, detail) {
  15068. fireSliderChange$3(edge, yValue(min1Y(detail)));
  15069. };
  15070. var setToTEdgeXY = function (edge, detail) {
  15071. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  15072. };
  15073. var setToTREdgeXY = function (edge, detail) {
  15074. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  15075. };
  15076. var setToREdge = function (edge, detail) {
  15077. fireSliderChange$3(edge, xValue(max1X(detail)));
  15078. };
  15079. var setToREdgeXY = function (edge, detail) {
  15080. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  15081. };
  15082. var setToBREdgeXY = function (edge, detail) {
  15083. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  15084. };
  15085. var setToBEdge = function (edge, detail) {
  15086. fireSliderChange$3(edge, yValue(max1Y(detail)));
  15087. };
  15088. var setToBEdgeXY = function (edge, detail) {
  15089. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  15090. };
  15091. var setToBLEdgeXY = function (edge, detail) {
  15092. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  15093. };
  15094. var setToLEdge = function (edge, detail) {
  15095. fireSliderChange$3(edge, xValue(min1X(detail)));
  15096. };
  15097. var setToLEdgeXY = function (edge, detail) {
  15098. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  15099. };
  15100. var reduceBy = function (value, min, max, step) {
  15101. if (value < min) {
  15102. return value;
  15103. } else if (value > max) {
  15104. return max;
  15105. } else if (value === min) {
  15106. return min - 1;
  15107. } else {
  15108. return Math.max(min, value - step);
  15109. }
  15110. };
  15111. var increaseBy = function (value, min, max, step) {
  15112. if (value > max) {
  15113. return value;
  15114. } else if (value < min) {
  15115. return min;
  15116. } else if (value === max) {
  15117. return max + 1;
  15118. } else {
  15119. return Math.min(max, value + step);
  15120. }
  15121. };
  15122. var capValue = function (value, min, max) {
  15123. return Math.max(min, Math.min(max, value));
  15124. };
  15125. var snapValueOf = function (value, min, max, step, snapStart) {
  15126. return snapStart.fold(function () {
  15127. var initValue = value - min;
  15128. var extraValue = Math.round(initValue / step) * step;
  15129. return capValue(min + extraValue, min - 1, max + 1);
  15130. }, function (start) {
  15131. var remainder = (value - start) % step;
  15132. var adjustment = Math.round(remainder / step);
  15133. var rawSteps = Math.floor((value - start) / step);
  15134. var maxSteps = Math.floor((max - start) / step);
  15135. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  15136. var r = start + numSteps * step;
  15137. return Math.max(start, r);
  15138. });
  15139. };
  15140. var findOffsetOf = function (value, min, max) {
  15141. return Math.min(max, Math.max(value, min)) - min;
  15142. };
  15143. var findValueOf = function (args) {
  15144. var min = args.min, max = args.max, range = args.range, value = args.value, step = args.step, snap = args.snap, snapStart = args.snapStart, rounded = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
  15145. var capMin = hasMinEdge ? min - 1 : min;
  15146. var capMax = hasMaxEdge ? max + 1 : max;
  15147. if (value < minBound) {
  15148. return capMin;
  15149. } else if (value > maxBound) {
  15150. return capMax;
  15151. } else {
  15152. var offset = findOffsetOf(value, minBound, maxBound);
  15153. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  15154. if (snap && newValue >= min && newValue <= max) {
  15155. return snapValueOf(newValue, min, max, step, snapStart);
  15156. } else if (rounded) {
  15157. return Math.round(newValue);
  15158. } else {
  15159. return newValue;
  15160. }
  15161. }
  15162. };
  15163. var findOffsetOfValue$2 = function (args) {
  15164. var min = args.min, max = args.max, range = args.range, value = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
  15165. if (value < min) {
  15166. return hasMinEdge ? 0 : centerMinEdge;
  15167. } else if (value > max) {
  15168. return hasMaxEdge ? maxBound : centerMaxEdge;
  15169. } else {
  15170. return (value - min) / range * maxOffset;
  15171. }
  15172. };
  15173. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  15174. var getBounds = function (component) {
  15175. return component.element.dom.getBoundingClientRect();
  15176. };
  15177. var getBoundsProperty = function (bounds, property) {
  15178. return bounds[property];
  15179. };
  15180. var getMinXBounds = function (component) {
  15181. var bounds = getBounds(component);
  15182. return getBoundsProperty(bounds, left);
  15183. };
  15184. var getMaxXBounds = function (component) {
  15185. var bounds = getBounds(component);
  15186. return getBoundsProperty(bounds, right);
  15187. };
  15188. var getMinYBounds = function (component) {
  15189. var bounds = getBounds(component);
  15190. return getBoundsProperty(bounds, top);
  15191. };
  15192. var getMaxYBounds = function (component) {
  15193. var bounds = getBounds(component);
  15194. return getBoundsProperty(bounds, bottom);
  15195. };
  15196. var getXScreenRange = function (component) {
  15197. var bounds = getBounds(component);
  15198. return getBoundsProperty(bounds, width);
  15199. };
  15200. var getYScreenRange = function (component) {
  15201. var bounds = getBounds(component);
  15202. return getBoundsProperty(bounds, height);
  15203. };
  15204. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  15205. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  15206. };
  15207. var getXCenterOffSetOf = function (component, spectrum) {
  15208. var componentBounds = getBounds(component);
  15209. var spectrumBounds = getBounds(spectrum);
  15210. var componentMinEdge = getBoundsProperty(componentBounds, left);
  15211. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  15212. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  15213. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  15214. };
  15215. var getYCenterOffSetOf = function (component, spectrum) {
  15216. var componentBounds = getBounds(component);
  15217. var spectrumBounds = getBounds(spectrum);
  15218. var componentMinEdge = getBoundsProperty(componentBounds, top);
  15219. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  15220. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  15221. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  15222. };
  15223. var fireSliderChange$2 = function (spectrum, value) {
  15224. emitWith(spectrum, sliderChangeEvent(), { value: value });
  15225. };
  15226. var sliderValue$2 = function (x) {
  15227. return { x: x };
  15228. };
  15229. var findValueOfOffset$1 = function (spectrum, detail, left) {
  15230. var args = {
  15231. min: minX(detail),
  15232. max: maxX(detail),
  15233. range: xRange(detail),
  15234. value: left,
  15235. step: step(detail),
  15236. snap: snap(detail),
  15237. snapStart: snapStart(detail),
  15238. rounded: rounded(detail),
  15239. hasMinEdge: hasLEdge(detail),
  15240. hasMaxEdge: hasREdge(detail),
  15241. minBound: getMinXBounds(spectrum),
  15242. maxBound: getMaxXBounds(spectrum),
  15243. screenRange: getXScreenRange(spectrum)
  15244. };
  15245. return findValueOf(args);
  15246. };
  15247. var setValueFrom$2 = function (spectrum, detail, value) {
  15248. var xValue = findValueOfOffset$1(spectrum, detail, value);
  15249. var sliderVal = sliderValue$2(xValue);
  15250. fireSliderChange$2(spectrum, sliderVal);
  15251. return xValue;
  15252. };
  15253. var setToMin$2 = function (spectrum, detail) {
  15254. var min = minX(detail);
  15255. fireSliderChange$2(spectrum, sliderValue$2(min));
  15256. };
  15257. var setToMax$2 = function (spectrum, detail) {
  15258. var max = maxX(detail);
  15259. fireSliderChange$2(spectrum, sliderValue$2(max));
  15260. };
  15261. var moveBy$2 = function (direction, spectrum, detail) {
  15262. var f = direction > 0 ? increaseBy : reduceBy;
  15263. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  15264. fireSliderChange$2(spectrum, sliderValue$2(xValue));
  15265. return Optional.some(xValue);
  15266. };
  15267. var handleMovement$2 = function (direction) {
  15268. return function (spectrum, detail) {
  15269. return moveBy$2(direction, spectrum, detail).map(always);
  15270. };
  15271. };
  15272. var getValueFromEvent$2 = function (simulatedEvent) {
  15273. var pos = getEventSource(simulatedEvent);
  15274. return pos.map(function (p) {
  15275. return p.left;
  15276. });
  15277. };
  15278. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  15279. var minOffset = 0;
  15280. var maxOffset = getXScreenRange(spectrum);
  15281. var centerMinEdge = minEdge.bind(function (edge) {
  15282. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  15283. }).getOr(minOffset);
  15284. var centerMaxEdge = maxEdge.bind(function (edge) {
  15285. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  15286. }).getOr(maxOffset);
  15287. var args = {
  15288. min: minX(detail),
  15289. max: maxX(detail),
  15290. range: xRange(detail),
  15291. value: value,
  15292. hasMinEdge: hasLEdge(detail),
  15293. hasMaxEdge: hasREdge(detail),
  15294. minBound: getMinXBounds(spectrum),
  15295. minOffset: minOffset,
  15296. maxBound: getMaxXBounds(spectrum),
  15297. maxOffset: maxOffset,
  15298. centerMinEdge: centerMinEdge,
  15299. centerMaxEdge: centerMaxEdge
  15300. };
  15301. return findOffsetOfValue$2(args);
  15302. };
  15303. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  15304. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  15305. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  15306. };
  15307. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  15308. var value = currentValue(detail);
  15309. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  15310. var thumbRadius = get$7(thumb.element) / 2;
  15311. set$6(thumb.element, 'left', pos - thumbRadius + 'px');
  15312. };
  15313. var onLeft$2 = handleMovement$2(-1);
  15314. var onRight$2 = handleMovement$2(1);
  15315. var onUp$2 = Optional.none;
  15316. var onDown$2 = Optional.none;
  15317. var edgeActions$2 = {
  15318. 'top-left': Optional.none(),
  15319. 'top': Optional.none(),
  15320. 'top-right': Optional.none(),
  15321. 'right': Optional.some(setToREdge),
  15322. 'bottom-right': Optional.none(),
  15323. 'bottom': Optional.none(),
  15324. 'bottom-left': Optional.none(),
  15325. 'left': Optional.some(setToLEdge)
  15326. };
  15327. var HorizontalModel = /*#__PURE__*/Object.freeze({
  15328. __proto__: null,
  15329. setValueFrom: setValueFrom$2,
  15330. setToMin: setToMin$2,
  15331. setToMax: setToMax$2,
  15332. findValueOfOffset: findValueOfOffset$1,
  15333. getValueFromEvent: getValueFromEvent$2,
  15334. findPositionOfValue: findPositionOfValue$1,
  15335. setPositionFromValue: setPositionFromValue$2,
  15336. onLeft: onLeft$2,
  15337. onRight: onRight$2,
  15338. onUp: onUp$2,
  15339. onDown: onDown$2,
  15340. edgeActions: edgeActions$2
  15341. });
  15342. var fireSliderChange$1 = function (spectrum, value) {
  15343. emitWith(spectrum, sliderChangeEvent(), { value: value });
  15344. };
  15345. var sliderValue$1 = function (y) {
  15346. return { y: y };
  15347. };
  15348. var findValueOfOffset = function (spectrum, detail, top) {
  15349. var args = {
  15350. min: minY(detail),
  15351. max: maxY(detail),
  15352. range: yRange(detail),
  15353. value: top,
  15354. step: step(detail),
  15355. snap: snap(detail),
  15356. snapStart: snapStart(detail),
  15357. rounded: rounded(detail),
  15358. hasMinEdge: hasTEdge(detail),
  15359. hasMaxEdge: hasBEdge(detail),
  15360. minBound: getMinYBounds(spectrum),
  15361. maxBound: getMaxYBounds(spectrum),
  15362. screenRange: getYScreenRange(spectrum)
  15363. };
  15364. return findValueOf(args);
  15365. };
  15366. var setValueFrom$1 = function (spectrum, detail, value) {
  15367. var yValue = findValueOfOffset(spectrum, detail, value);
  15368. var sliderVal = sliderValue$1(yValue);
  15369. fireSliderChange$1(spectrum, sliderVal);
  15370. return yValue;
  15371. };
  15372. var setToMin$1 = function (spectrum, detail) {
  15373. var min = minY(detail);
  15374. fireSliderChange$1(spectrum, sliderValue$1(min));
  15375. };
  15376. var setToMax$1 = function (spectrum, detail) {
  15377. var max = maxY(detail);
  15378. fireSliderChange$1(spectrum, sliderValue$1(max));
  15379. };
  15380. var moveBy$1 = function (direction, spectrum, detail) {
  15381. var f = direction > 0 ? increaseBy : reduceBy;
  15382. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  15383. fireSliderChange$1(spectrum, sliderValue$1(yValue));
  15384. return Optional.some(yValue);
  15385. };
  15386. var handleMovement$1 = function (direction) {
  15387. return function (spectrum, detail) {
  15388. return moveBy$1(direction, spectrum, detail).map(always);
  15389. };
  15390. };
  15391. var getValueFromEvent$1 = function (simulatedEvent) {
  15392. var pos = getEventSource(simulatedEvent);
  15393. return pos.map(function (p) {
  15394. return p.top;
  15395. });
  15396. };
  15397. var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  15398. var minOffset = 0;
  15399. var maxOffset = getYScreenRange(spectrum);
  15400. var centerMinEdge = minEdge.bind(function (edge) {
  15401. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  15402. }).getOr(minOffset);
  15403. var centerMaxEdge = maxEdge.bind(function (edge) {
  15404. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  15405. }).getOr(maxOffset);
  15406. var args = {
  15407. min: minY(detail),
  15408. max: maxY(detail),
  15409. range: yRange(detail),
  15410. value: value,
  15411. hasMinEdge: hasTEdge(detail),
  15412. hasMaxEdge: hasBEdge(detail),
  15413. minBound: getMinYBounds(spectrum),
  15414. minOffset: minOffset,
  15415. maxBound: getMaxYBounds(spectrum),
  15416. maxOffset: maxOffset,
  15417. centerMinEdge: centerMinEdge,
  15418. centerMaxEdge: centerMaxEdge
  15419. };
  15420. return findOffsetOfValue$2(args);
  15421. };
  15422. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  15423. var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  15424. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  15425. };
  15426. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  15427. var value = currentValue(detail);
  15428. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  15429. var thumbRadius = get$8(thumb.element) / 2;
  15430. set$6(thumb.element, 'top', pos - thumbRadius + 'px');
  15431. };
  15432. var onLeft$1 = Optional.none;
  15433. var onRight$1 = Optional.none;
  15434. var onUp$1 = handleMovement$1(-1);
  15435. var onDown$1 = handleMovement$1(1);
  15436. var edgeActions$1 = {
  15437. 'top-left': Optional.none(),
  15438. 'top': Optional.some(setToTEdge),
  15439. 'top-right': Optional.none(),
  15440. 'right': Optional.none(),
  15441. 'bottom-right': Optional.none(),
  15442. 'bottom': Optional.some(setToBEdge),
  15443. 'bottom-left': Optional.none(),
  15444. 'left': Optional.none()
  15445. };
  15446. var VerticalModel = /*#__PURE__*/Object.freeze({
  15447. __proto__: null,
  15448. setValueFrom: setValueFrom$1,
  15449. setToMin: setToMin$1,
  15450. setToMax: setToMax$1,
  15451. findValueOfOffset: findValueOfOffset,
  15452. getValueFromEvent: getValueFromEvent$1,
  15453. findPositionOfValue: findPositionOfValue,
  15454. setPositionFromValue: setPositionFromValue$1,
  15455. onLeft: onLeft$1,
  15456. onRight: onRight$1,
  15457. onUp: onUp$1,
  15458. onDown: onDown$1,
  15459. edgeActions: edgeActions$1
  15460. });
  15461. var fireSliderChange = function (spectrum, value) {
  15462. emitWith(spectrum, sliderChangeEvent(), { value: value });
  15463. };
  15464. var sliderValue = function (x, y) {
  15465. return {
  15466. x: x,
  15467. y: y
  15468. };
  15469. };
  15470. var setValueFrom = function (spectrum, detail, value) {
  15471. var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  15472. var yValue = findValueOfOffset(spectrum, detail, value.top);
  15473. var val = sliderValue(xValue, yValue);
  15474. fireSliderChange(spectrum, val);
  15475. return val;
  15476. };
  15477. var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  15478. var f = direction > 0 ? increaseBy : reduceBy;
  15479. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  15480. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  15481. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  15482. return Optional.some(xValue);
  15483. };
  15484. var handleMovement = function (direction, isVerticalMovement) {
  15485. return function (spectrum, detail) {
  15486. return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  15487. };
  15488. };
  15489. var setToMin = function (spectrum, detail) {
  15490. var mX = minX(detail);
  15491. var mY = minY(detail);
  15492. fireSliderChange(spectrum, sliderValue(mX, mY));
  15493. };
  15494. var setToMax = function (spectrum, detail) {
  15495. var mX = maxX(detail);
  15496. var mY = maxY(detail);
  15497. fireSliderChange(spectrum, sliderValue(mX, mY));
  15498. };
  15499. var getValueFromEvent = function (simulatedEvent) {
  15500. return getEventSource(simulatedEvent);
  15501. };
  15502. var setPositionFromValue = function (slider, thumb, detail, edges) {
  15503. var value = currentValue(detail);
  15504. var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  15505. var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  15506. var thumbXRadius = get$7(thumb.element) / 2;
  15507. var thumbYRadius = get$8(thumb.element) / 2;
  15508. set$6(thumb.element, 'left', xPos - thumbXRadius + 'px');
  15509. set$6(thumb.element, 'top', yPos - thumbYRadius + 'px');
  15510. };
  15511. var onLeft = handleMovement(-1, false);
  15512. var onRight = handleMovement(1, false);
  15513. var onUp = handleMovement(-1, true);
  15514. var onDown = handleMovement(1, true);
  15515. var edgeActions = {
  15516. 'top-left': Optional.some(setToTLEdgeXY),
  15517. 'top': Optional.some(setToTEdgeXY),
  15518. 'top-right': Optional.some(setToTREdgeXY),
  15519. 'right': Optional.some(setToREdgeXY),
  15520. 'bottom-right': Optional.some(setToBREdgeXY),
  15521. 'bottom': Optional.some(setToBEdgeXY),
  15522. 'bottom-left': Optional.some(setToBLEdgeXY),
  15523. 'left': Optional.some(setToLEdgeXY)
  15524. };
  15525. var TwoDModel = /*#__PURE__*/Object.freeze({
  15526. __proto__: null,
  15527. setValueFrom: setValueFrom,
  15528. setToMin: setToMin,
  15529. setToMax: setToMax,
  15530. getValueFromEvent: getValueFromEvent,
  15531. setPositionFromValue: setPositionFromValue,
  15532. onLeft: onLeft,
  15533. onRight: onRight,
  15534. onUp: onUp,
  15535. onDown: onDown,
  15536. edgeActions: edgeActions
  15537. });
  15538. var SliderSchema = [
  15539. defaulted('stepSize', 1),
  15540. defaulted('onChange', noop),
  15541. defaulted('onChoose', noop),
  15542. defaulted('onInit', noop),
  15543. defaulted('onDragStart', noop),
  15544. defaulted('onDragEnd', noop),
  15545. defaulted('snapToGrid', false),
  15546. defaulted('rounded', true),
  15547. option('snapStart'),
  15548. requiredOf('model', choose$1('mode', {
  15549. x: [
  15550. defaulted('minX', 0),
  15551. defaulted('maxX', 100),
  15552. customField('value', function (spec) {
  15553. return Cell(spec.mode.minX);
  15554. }),
  15555. required$1('getInitialValue'),
  15556. output$1('manager', HorizontalModel)
  15557. ],
  15558. y: [
  15559. defaulted('minY', 0),
  15560. defaulted('maxY', 100),
  15561. customField('value', function (spec) {
  15562. return Cell(spec.mode.minY);
  15563. }),
  15564. required$1('getInitialValue'),
  15565. output$1('manager', VerticalModel)
  15566. ],
  15567. xy: [
  15568. defaulted('minX', 0),
  15569. defaulted('maxX', 100),
  15570. defaulted('minY', 0),
  15571. defaulted('maxY', 100),
  15572. customField('value', function (spec) {
  15573. return Cell({
  15574. x: spec.mode.minX,
  15575. y: spec.mode.minY
  15576. });
  15577. }),
  15578. required$1('getInitialValue'),
  15579. output$1('manager', TwoDModel)
  15580. ]
  15581. })),
  15582. field('sliderBehaviours', [
  15583. Keying,
  15584. Representing
  15585. ]),
  15586. customField('mouseIsDown', function () {
  15587. return Cell(false);
  15588. })
  15589. ];
  15590. var sketch$2 = function (detail, components, _spec, _externals) {
  15591. var _a;
  15592. var getThumb = function (component) {
  15593. return getPartOrDie(component, detail, 'thumb');
  15594. };
  15595. var getSpectrum = function (component) {
  15596. return getPartOrDie(component, detail, 'spectrum');
  15597. };
  15598. var getLeftEdge = function (component) {
  15599. return getPart(component, detail, 'left-edge');
  15600. };
  15601. var getRightEdge = function (component) {
  15602. return getPart(component, detail, 'right-edge');
  15603. };
  15604. var getTopEdge = function (component) {
  15605. return getPart(component, detail, 'top-edge');
  15606. };
  15607. var getBottomEdge = function (component) {
  15608. return getPart(component, detail, 'bottom-edge');
  15609. };
  15610. var modelDetail = detail.model;
  15611. var model = modelDetail.manager;
  15612. var refresh = function (slider, thumb) {
  15613. model.setPositionFromValue(slider, thumb, detail, {
  15614. getLeftEdge: getLeftEdge,
  15615. getRightEdge: getRightEdge,
  15616. getTopEdge: getTopEdge,
  15617. getBottomEdge: getBottomEdge,
  15618. getSpectrum: getSpectrum
  15619. });
  15620. };
  15621. var setValue = function (slider, newValue) {
  15622. modelDetail.value.set(newValue);
  15623. var thumb = getThumb(slider);
  15624. refresh(slider, thumb);
  15625. };
  15626. var changeValue = function (slider, newValue) {
  15627. setValue(slider, newValue);
  15628. var thumb = getThumb(slider);
  15629. detail.onChange(slider, thumb, newValue);
  15630. return Optional.some(true);
  15631. };
  15632. var resetToMin = function (slider) {
  15633. model.setToMin(slider, detail);
  15634. };
  15635. var resetToMax = function (slider) {
  15636. model.setToMax(slider, detail);
  15637. };
  15638. var choose = function (slider) {
  15639. var fireOnChoose = function () {
  15640. getPart(slider, detail, 'thumb').each(function (thumb) {
  15641. var value = modelDetail.value.get();
  15642. detail.onChoose(slider, thumb, value);
  15643. });
  15644. };
  15645. var wasDown = detail.mouseIsDown.get();
  15646. detail.mouseIsDown.set(false);
  15647. if (wasDown) {
  15648. fireOnChoose();
  15649. }
  15650. };
  15651. var onDragStart = function (slider, simulatedEvent) {
  15652. simulatedEvent.stop();
  15653. detail.mouseIsDown.set(true);
  15654. detail.onDragStart(slider, getThumb(slider));
  15655. };
  15656. var onDragEnd = function (slider, simulatedEvent) {
  15657. simulatedEvent.stop();
  15658. detail.onDragEnd(slider, getThumb(slider));
  15659. choose(slider);
  15660. };
  15661. return {
  15662. uid: detail.uid,
  15663. dom: detail.dom,
  15664. components: components,
  15665. behaviours: augment(detail.sliderBehaviours, [
  15666. Keying.config({
  15667. mode: 'special',
  15668. focusIn: function (slider) {
  15669. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  15670. }
  15671. }),
  15672. Representing.config({
  15673. store: {
  15674. mode: 'manual',
  15675. getValue: function (_) {
  15676. return modelDetail.value.get();
  15677. }
  15678. }
  15679. }),
  15680. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  15681. ]),
  15682. events: derive$2([
  15683. run$1(sliderChangeEvent(), function (slider, simulatedEvent) {
  15684. changeValue(slider, simulatedEvent.event.value);
  15685. }),
  15686. runOnAttached(function (slider, _simulatedEvent) {
  15687. var getInitial = modelDetail.getInitialValue();
  15688. modelDetail.value.set(getInitial);
  15689. var thumb = getThumb(slider);
  15690. refresh(slider, thumb);
  15691. var spectrum = getSpectrum(slider);
  15692. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  15693. }),
  15694. run$1(touchstart(), onDragStart),
  15695. run$1(touchend(), onDragEnd),
  15696. run$1(mousedown(), onDragStart),
  15697. run$1(mouseup(), onDragEnd)
  15698. ]),
  15699. apis: {
  15700. resetToMin: resetToMin,
  15701. resetToMax: resetToMax,
  15702. setValue: setValue,
  15703. refresh: refresh
  15704. },
  15705. domModification: { styles: { position: 'relative' } }
  15706. };
  15707. };
  15708. var Slider = composite({
  15709. name: 'Slider',
  15710. configFields: SliderSchema,
  15711. partFields: SliderParts,
  15712. factory: sketch$2,
  15713. apis: {
  15714. setValue: function (apis, slider, value) {
  15715. apis.setValue(slider, value);
  15716. },
  15717. resetToMin: function (apis, slider) {
  15718. apis.resetToMin(slider);
  15719. },
  15720. resetToMax: function (apis, slider) {
  15721. apis.resetToMax(slider);
  15722. },
  15723. refresh: function (apis, slider) {
  15724. apis.refresh(slider);
  15725. }
  15726. }
  15727. });
  15728. var fieldsUpdate = generate$6('rgb-hex-update');
  15729. var sliderUpdate = generate$6('slider-update');
  15730. var paletteUpdate = generate$6('palette-update');
  15731. var sliderFactory = function (translate, getClass) {
  15732. var spectrum = Slider.parts.spectrum({
  15733. dom: {
  15734. tag: 'div',
  15735. classes: [getClass('hue-slider-spectrum')],
  15736. attributes: { role: 'presentation' }
  15737. }
  15738. });
  15739. var thumb = Slider.parts.thumb({
  15740. dom: {
  15741. tag: 'div',
  15742. classes: [getClass('hue-slider-thumb')],
  15743. attributes: { role: 'presentation' }
  15744. }
  15745. });
  15746. return Slider.sketch({
  15747. dom: {
  15748. tag: 'div',
  15749. classes: [getClass('hue-slider')],
  15750. attributes: { role: 'presentation' }
  15751. },
  15752. rounded: false,
  15753. model: {
  15754. mode: 'y',
  15755. getInitialValue: constant$1({ y: 0 })
  15756. },
  15757. components: [
  15758. spectrum,
  15759. thumb
  15760. ],
  15761. sliderBehaviours: derive$1([Focusing.config({})]),
  15762. onChange: function (slider, _thumb, value) {
  15763. emitWith(slider, sliderUpdate, { value: value });
  15764. }
  15765. });
  15766. };
  15767. var owner$1 = 'form';
  15768. var schema$i = [field('formBehaviours', [Representing])];
  15769. var getPartName$1 = function (name) {
  15770. return '<alloy.field.' + name + '>';
  15771. };
  15772. var sketch$1 = function (fSpec) {
  15773. var parts = function () {
  15774. var record = [];
  15775. var field = function (name, config) {
  15776. record.push(name);
  15777. return generateOne$1(owner$1, getPartName$1(name), config);
  15778. };
  15779. return {
  15780. field: field,
  15781. record: constant$1(record)
  15782. };
  15783. }();
  15784. var spec = fSpec(parts);
  15785. var partNames = parts.record();
  15786. var fieldParts = map$2(partNames, function (n) {
  15787. return required({
  15788. name: n,
  15789. pname: getPartName$1(n)
  15790. });
  15791. });
  15792. return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
  15793. };
  15794. var toResult = function (o, e) {
  15795. return o.fold(function () {
  15796. return Result.error(e);
  15797. }, Result.value);
  15798. };
  15799. var make$4 = function (detail, components) {
  15800. return {
  15801. uid: detail.uid,
  15802. dom: detail.dom,
  15803. components: components,
  15804. behaviours: augment(detail.formBehaviours, [Representing.config({
  15805. store: {
  15806. mode: 'manual',
  15807. getValue: function (form) {
  15808. var resPs = getAllParts(form, detail);
  15809. return map(resPs, function (resPThunk, pName) {
  15810. return resPThunk().bind(function (v) {
  15811. var opt = Composing.getCurrent(v);
  15812. return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  15813. }).map(Representing.getValue);
  15814. });
  15815. },
  15816. setValue: function (form, values) {
  15817. each(values, function (newValue, key) {
  15818. getPart(form, detail, key).each(function (wrapper) {
  15819. Composing.getCurrent(wrapper).each(function (field) {
  15820. Representing.setValue(field, newValue);
  15821. });
  15822. });
  15823. });
  15824. }
  15825. }
  15826. })]),
  15827. apis: {
  15828. getField: function (form, key) {
  15829. return getPart(form, detail, key).bind(Composing.getCurrent);
  15830. }
  15831. }
  15832. };
  15833. };
  15834. var Form = {
  15835. getField: makeApi(function (apis, component, key) {
  15836. return apis.getField(component, key);
  15837. }),
  15838. sketch: sketch$1
  15839. };
  15840. var validInput = generate$6('valid-input');
  15841. var invalidInput = generate$6('invalid-input');
  15842. var validatingInput = generate$6('validating-input');
  15843. var translatePrefix = 'colorcustom.rgb.';
  15844. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  15845. var invalidation = function (label, isValid) {
  15846. return Invalidating.config({
  15847. invalidClass: getClass('invalid'),
  15848. notify: {
  15849. onValidate: function (comp) {
  15850. emitWith(comp, validatingInput, { type: label });
  15851. },
  15852. onValid: function (comp) {
  15853. emitWith(comp, validInput, {
  15854. type: label,
  15855. value: Representing.getValue(comp)
  15856. });
  15857. },
  15858. onInvalid: function (comp) {
  15859. emitWith(comp, invalidInput, {
  15860. type: label,
  15861. value: Representing.getValue(comp)
  15862. });
  15863. }
  15864. },
  15865. validator: {
  15866. validate: function (comp) {
  15867. var value = Representing.getValue(comp);
  15868. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  15869. return Future.pure(res);
  15870. },
  15871. validateOnLoad: false
  15872. }
  15873. });
  15874. };
  15875. var renderTextField = function (isValid, name, label, description, data) {
  15876. var helptext = translate(translatePrefix + 'range');
  15877. var pLabel = FormField.parts.label({
  15878. dom: {
  15879. tag: 'label',
  15880. innerHtml: label,
  15881. attributes: { 'aria-label': description }
  15882. }
  15883. });
  15884. var pField = FormField.parts.field({
  15885. data: data,
  15886. factory: Input,
  15887. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15888. inputClasses: [getClass('textfield')],
  15889. inputBehaviours: derive$1([
  15890. invalidation(name, isValid),
  15891. Tabstopping.config({})
  15892. ]),
  15893. onSetValue: function (input) {
  15894. if (Invalidating.isInvalid(input)) {
  15895. var run = Invalidating.run(input);
  15896. run.get(noop);
  15897. }
  15898. }
  15899. });
  15900. var comps = [
  15901. pLabel,
  15902. pField
  15903. ];
  15904. var concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : [];
  15905. var components = comps.concat(concats);
  15906. return {
  15907. dom: {
  15908. tag: 'div',
  15909. attributes: { role: 'presentation' }
  15910. },
  15911. components: components
  15912. };
  15913. };
  15914. var copyRgbToHex = function (form, rgba) {
  15915. var hex = fromRgba(rgba);
  15916. Form.getField(form, 'hex').each(function (hexField) {
  15917. if (!Focusing.isFocused(hexField)) {
  15918. Representing.setValue(form, { hex: hex.value });
  15919. }
  15920. });
  15921. return hex;
  15922. };
  15923. var copyRgbToForm = function (form, rgb) {
  15924. var red = rgb.red;
  15925. var green = rgb.green;
  15926. var blue = rgb.blue;
  15927. Representing.setValue(form, {
  15928. red: red,
  15929. green: green,
  15930. blue: blue
  15931. });
  15932. };
  15933. var memPreview = record({
  15934. dom: {
  15935. tag: 'div',
  15936. classes: [getClass('rgba-preview')],
  15937. styles: { 'background-color': 'white' },
  15938. attributes: { role: 'presentation' }
  15939. }
  15940. });
  15941. var updatePreview = function (anyInSystem, hex) {
  15942. memPreview.getOpt(anyInSystem).each(function (preview) {
  15943. set$6(preview.element, 'background-color', '#' + hex.value);
  15944. });
  15945. };
  15946. var factory = function () {
  15947. var state = {
  15948. red: Cell(Optional.some(255)),
  15949. green: Cell(Optional.some(255)),
  15950. blue: Cell(Optional.some(255)),
  15951. hex: Cell(Optional.some('ffffff'))
  15952. };
  15953. var copyHexToRgb = function (form, hex) {
  15954. var rgb = fromHex(hex);
  15955. copyRgbToForm(form, rgb);
  15956. setValueRgb(rgb);
  15957. };
  15958. var get = function (prop) {
  15959. return state[prop].get();
  15960. };
  15961. var set = function (prop, value) {
  15962. state[prop].set(value);
  15963. };
  15964. var getValueRgb = function () {
  15965. return get('red').bind(function (red) {
  15966. return get('green').bind(function (green) {
  15967. return get('blue').map(function (blue) {
  15968. return rgbaColour(red, green, blue, 1);
  15969. });
  15970. });
  15971. });
  15972. };
  15973. var setValueRgb = function (rgb) {
  15974. var red = rgb.red;
  15975. var green = rgb.green;
  15976. var blue = rgb.blue;
  15977. set('red', Optional.some(red));
  15978. set('green', Optional.some(green));
  15979. set('blue', Optional.some(blue));
  15980. };
  15981. var onInvalidInput = function (form, simulatedEvent) {
  15982. var data = simulatedEvent.event;
  15983. if (data.type !== 'hex') {
  15984. set(data.type, Optional.none());
  15985. } else {
  15986. onInvalidHexx(form);
  15987. }
  15988. };
  15989. var onValidHex = function (form, value) {
  15990. onValidHexx(form);
  15991. var hex = hexColour(value);
  15992. set('hex', Optional.some(value));
  15993. var rgb = fromHex(hex);
  15994. copyRgbToForm(form, rgb);
  15995. setValueRgb(rgb);
  15996. emitWith(form, fieldsUpdate, { hex: hex });
  15997. updatePreview(form, hex);
  15998. };
  15999. var onValidRgb = function (form, prop, value) {
  16000. var val = parseInt(value, 10);
  16001. set(prop, Optional.some(val));
  16002. getValueRgb().each(function (rgb) {
  16003. var hex = copyRgbToHex(form, rgb);
  16004. emitWith(form, fieldsUpdate, { hex: hex });
  16005. updatePreview(form, hex);
  16006. });
  16007. };
  16008. var isHexInputEvent = function (data) {
  16009. return data.type === 'hex';
  16010. };
  16011. var onValidInput = function (form, simulatedEvent) {
  16012. var data = simulatedEvent.event;
  16013. if (isHexInputEvent(data)) {
  16014. onValidHex(form, data.value);
  16015. } else {
  16016. onValidRgb(form, data.type, data.value);
  16017. }
  16018. };
  16019. var formPartStrings = function (key) {
  16020. return {
  16021. label: translate(translatePrefix + key + '.label'),
  16022. description: translate(translatePrefix + key + '.description')
  16023. };
  16024. };
  16025. var redStrings = formPartStrings('red');
  16026. var greenStrings = formPartStrings('green');
  16027. var blueStrings = formPartStrings('blue');
  16028. var hexStrings = formPartStrings('hex');
  16029. return deepMerge(Form.sketch(function (parts) {
  16030. return {
  16031. dom: {
  16032. tag: 'form',
  16033. classes: [getClass('rgb-form')],
  16034. attributes: { 'aria-label': translate('aria.color.picker') }
  16035. },
  16036. components: [
  16037. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  16038. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  16039. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  16040. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  16041. memPreview.asSpec()
  16042. ],
  16043. formBehaviours: derive$1([
  16044. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  16045. config('rgb-form-events', [
  16046. run$1(validInput, onValidInput),
  16047. run$1(invalidInput, onInvalidInput),
  16048. run$1(validatingInput, onInvalidInput)
  16049. ])
  16050. ])
  16051. };
  16052. }), {
  16053. apis: {
  16054. updateHex: function (form, hex) {
  16055. Representing.setValue(form, { hex: hex.value });
  16056. copyHexToRgb(form, hex);
  16057. updatePreview(form, hex);
  16058. }
  16059. }
  16060. });
  16061. };
  16062. var rgbFormSketcher = single({
  16063. factory: factory,
  16064. name: 'RgbForm',
  16065. configFields: [],
  16066. apis: {
  16067. updateHex: function (apis, form, hex) {
  16068. apis.updateHex(form, hex);
  16069. }
  16070. },
  16071. extraApis: {}
  16072. });
  16073. return rgbFormSketcher;
  16074. };
  16075. var paletteFactory = function (_translate, getClass) {
  16076. var spectrumPart = Slider.parts.spectrum({
  16077. dom: {
  16078. tag: 'canvas',
  16079. attributes: { role: 'presentation' },
  16080. classes: [getClass('sv-palette-spectrum')]
  16081. }
  16082. });
  16083. var thumbPart = Slider.parts.thumb({
  16084. dom: {
  16085. tag: 'div',
  16086. attributes: { role: 'presentation' },
  16087. classes: [getClass('sv-palette-thumb')],
  16088. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  16089. }
  16090. });
  16091. var setColour = function (canvas, rgba) {
  16092. var width = canvas.width, height = canvas.height;
  16093. var ctx = canvas.getContext('2d');
  16094. if (ctx === null) {
  16095. return;
  16096. }
  16097. ctx.fillStyle = rgba;
  16098. ctx.fillRect(0, 0, width, height);
  16099. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  16100. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  16101. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  16102. ctx.fillStyle = grdWhite;
  16103. ctx.fillRect(0, 0, width, height);
  16104. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  16105. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  16106. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  16107. ctx.fillStyle = grdBlack;
  16108. ctx.fillRect(0, 0, width, height);
  16109. };
  16110. var setPaletteHue = function (slider, hue) {
  16111. var canvas = slider.components()[0].element.dom;
  16112. var hsv = hsvColour(hue, 100, 100);
  16113. var rgba = fromHsv(hsv);
  16114. setColour(canvas, toString(rgba));
  16115. };
  16116. var setPaletteThumb = function (slider, hex) {
  16117. var hsv = fromRgb(fromHex(hex));
  16118. Slider.setValue(slider, {
  16119. x: hsv.saturation,
  16120. y: 100 - hsv.value
  16121. });
  16122. };
  16123. var factory = function (_detail) {
  16124. var getInitialValue = constant$1({
  16125. x: 0,
  16126. y: 0
  16127. });
  16128. var onChange = function (slider, _thumb, value) {
  16129. emitWith(slider, paletteUpdate, { value: value });
  16130. };
  16131. var onInit = function (_slider, _thumb, spectrum, _value) {
  16132. setColour(spectrum.element.dom, toString(red));
  16133. };
  16134. var sliderBehaviours = derive$1([
  16135. Composing.config({ find: Optional.some }),
  16136. Focusing.config({})
  16137. ]);
  16138. return Slider.sketch({
  16139. dom: {
  16140. tag: 'div',
  16141. attributes: { role: 'presentation' },
  16142. classes: [getClass('sv-palette')]
  16143. },
  16144. model: {
  16145. mode: 'xy',
  16146. getInitialValue: getInitialValue
  16147. },
  16148. rounded: false,
  16149. components: [
  16150. spectrumPart,
  16151. thumbPart
  16152. ],
  16153. onChange: onChange,
  16154. onInit: onInit,
  16155. sliderBehaviours: sliderBehaviours
  16156. });
  16157. };
  16158. var saturationBrightnessPaletteSketcher = single({
  16159. factory: factory,
  16160. name: 'SaturationBrightnessPalette',
  16161. configFields: [],
  16162. apis: {
  16163. setHue: function (_apis, slider, hue) {
  16164. setPaletteHue(slider, hue);
  16165. },
  16166. setThumb: function (_apis, slider, hex) {
  16167. setPaletteThumb(slider, hex);
  16168. }
  16169. },
  16170. extraApis: {}
  16171. });
  16172. return saturationBrightnessPaletteSketcher;
  16173. };
  16174. var makeFactory = function (translate, getClass) {
  16175. var factory = function (detail) {
  16176. var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  16177. var sbPalette = paletteFactory(translate, getClass);
  16178. var hueSliderToDegrees = function (hue) {
  16179. return (100 - hue) / 100 * 360;
  16180. };
  16181. var hueDegreesToSlider = function (hue) {
  16182. return 100 - hue / 360 * 100;
  16183. };
  16184. var state = {
  16185. paletteRgba: Cell(red),
  16186. paletteHue: Cell(0)
  16187. };
  16188. var memSlider = record(sliderFactory(translate, getClass));
  16189. var memPalette = record(sbPalette.sketch({}));
  16190. var memRgb = record(rgbForm.sketch({}));
  16191. var updatePalette = function (anyInSystem, _hex, hue) {
  16192. memPalette.getOpt(anyInSystem).each(function (palette) {
  16193. sbPalette.setHue(palette, hue);
  16194. });
  16195. };
  16196. var updateFields = function (anyInSystem, hex) {
  16197. memRgb.getOpt(anyInSystem).each(function (form) {
  16198. rgbForm.updateHex(form, hex);
  16199. });
  16200. };
  16201. var updateSlider = function (anyInSystem, _hex, hue) {
  16202. memSlider.getOpt(anyInSystem).each(function (slider) {
  16203. Slider.setValue(slider, { y: hueDegreesToSlider(hue) });
  16204. });
  16205. };
  16206. var updatePaletteThumb = function (anyInSystem, hex) {
  16207. memPalette.getOpt(anyInSystem).each(function (palette) {
  16208. sbPalette.setThumb(palette, hex);
  16209. });
  16210. };
  16211. var updateState = function (hex, hue) {
  16212. var rgba = fromHex(hex);
  16213. state.paletteRgba.set(rgba);
  16214. state.paletteHue.set(hue);
  16215. };
  16216. var runUpdates = function (anyInSystem, hex, hue, updates) {
  16217. updateState(hex, hue);
  16218. each$1(updates, function (update) {
  16219. update(anyInSystem, hex, hue);
  16220. });
  16221. };
  16222. var onPaletteUpdate = function () {
  16223. var updates = [updateFields];
  16224. return function (form, simulatedEvent) {
  16225. var value = simulatedEvent.event.value;
  16226. var oldHue = state.paletteHue.get();
  16227. var newHsv = hsvColour(oldHue, value.x, 100 - value.y);
  16228. var newHex = hsvToHex(newHsv);
  16229. runUpdates(form, newHex, oldHue, updates);
  16230. };
  16231. };
  16232. var onSliderUpdate = function () {
  16233. var updates = [
  16234. updatePalette,
  16235. updateFields
  16236. ];
  16237. return function (form, simulatedEvent) {
  16238. var hue = hueSliderToDegrees(simulatedEvent.event.value.y);
  16239. var oldRgb = state.paletteRgba.get();
  16240. var oldHsv = fromRgb(oldRgb);
  16241. var newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value);
  16242. var newHex = hsvToHex(newHsv);
  16243. runUpdates(form, newHex, hue, updates);
  16244. };
  16245. };
  16246. var onFieldsUpdate = function () {
  16247. var updates = [
  16248. updatePalette,
  16249. updateSlider,
  16250. updatePaletteThumb
  16251. ];
  16252. return function (form, simulatedEvent) {
  16253. var hex = simulatedEvent.event.hex;
  16254. var hsv = hexToHsv(hex);
  16255. runUpdates(form, hex, hsv.hue, updates);
  16256. };
  16257. };
  16258. return {
  16259. uid: detail.uid,
  16260. dom: detail.dom,
  16261. components: [
  16262. memPalette.asSpec(),
  16263. memSlider.asSpec(),
  16264. memRgb.asSpec()
  16265. ],
  16266. behaviours: derive$1([
  16267. config('colour-picker-events', [
  16268. run$1(fieldsUpdate, onFieldsUpdate()),
  16269. run$1(paletteUpdate, onPaletteUpdate()),
  16270. run$1(sliderUpdate, onSliderUpdate())
  16271. ]),
  16272. Composing.config({
  16273. find: function (comp) {
  16274. return memRgb.getOpt(comp);
  16275. }
  16276. }),
  16277. Keying.config({ mode: 'acyclic' })
  16278. ])
  16279. };
  16280. };
  16281. var colourPickerSketcher = single({
  16282. name: 'ColourPicker',
  16283. configFields: [
  16284. required$1('dom'),
  16285. defaulted('onValidHex', noop),
  16286. defaulted('onInvalidHex', noop)
  16287. ],
  16288. factory: factory
  16289. });
  16290. return colourPickerSketcher;
  16291. };
  16292. var self$1 = function () {
  16293. return Composing.config({ find: Optional.some });
  16294. };
  16295. var memento$1 = function (mem) {
  16296. return Composing.config({ find: mem.getOpt });
  16297. };
  16298. var childAt = function (index) {
  16299. return Composing.config({
  16300. find: function (comp) {
  16301. return child$2(comp.element, index).bind(function (element) {
  16302. return comp.getSystem().getByDom(element).toOptional();
  16303. });
  16304. }
  16305. });
  16306. };
  16307. var ComposingConfigs = {
  16308. self: self$1,
  16309. memento: memento$1,
  16310. childAt: childAt
  16311. };
  16312. var english = {
  16313. 'colorcustom.rgb.red.label': 'R',
  16314. 'colorcustom.rgb.red.description': 'Red component',
  16315. 'colorcustom.rgb.green.label': 'G',
  16316. 'colorcustom.rgb.green.description': 'Green component',
  16317. 'colorcustom.rgb.blue.label': 'B',
  16318. 'colorcustom.rgb.blue.description': 'Blue component',
  16319. 'colorcustom.rgb.hex.label': '#',
  16320. 'colorcustom.rgb.hex.description': 'Hex color code',
  16321. 'colorcustom.rgb.range': 'Range 0 to 255',
  16322. 'colorcustom.sb.saturation': 'Saturation',
  16323. 'colorcustom.sb.brightness': 'Brightness',
  16324. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  16325. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  16326. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  16327. 'colorcustom.hue.hue': 'Hue',
  16328. 'colorcustom.hue.slider': 'Hue Slider',
  16329. 'colorcustom.hue.palette': 'Hue Palette',
  16330. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  16331. 'aria.color.picker': 'Color Picker',
  16332. 'aria.input.invalid': 'Invalid input'
  16333. };
  16334. var getEnglishText = function (key) {
  16335. return english[key];
  16336. };
  16337. var translate$1 = function (key) {
  16338. return getEnglishText(key);
  16339. };
  16340. var renderColorPicker = function (_spec) {
  16341. var getClass = function (key) {
  16342. return 'tox-' + key;
  16343. };
  16344. var colourPickerFactory = makeFactory(translate$1, getClass);
  16345. var onValidHex = function (form) {
  16346. emitWith(form, formActionEvent, {
  16347. name: 'hex-valid',
  16348. value: true
  16349. });
  16350. };
  16351. var onInvalidHex = function (form) {
  16352. emitWith(form, formActionEvent, {
  16353. name: 'hex-valid',
  16354. value: false
  16355. });
  16356. };
  16357. var memPicker = record(colourPickerFactory.sketch({
  16358. dom: {
  16359. tag: 'div',
  16360. classes: [getClass('color-picker-container')],
  16361. attributes: { role: 'presentation' }
  16362. },
  16363. onValidHex: onValidHex,
  16364. onInvalidHex: onInvalidHex
  16365. }));
  16366. return {
  16367. dom: { tag: 'div' },
  16368. components: [memPicker.asSpec()],
  16369. behaviours: derive$1([
  16370. Representing.config({
  16371. store: {
  16372. mode: 'manual',
  16373. getValue: function (comp) {
  16374. var picker = memPicker.get(comp);
  16375. var optRgbForm = Composing.getCurrent(picker);
  16376. var optHex = optRgbForm.bind(function (rgbForm) {
  16377. var formValues = Representing.getValue(rgbForm);
  16378. return formValues.hex;
  16379. });
  16380. return optHex.map(function (hex) {
  16381. return '#' + hex;
  16382. }).getOr('');
  16383. },
  16384. setValue: function (comp, newValue) {
  16385. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  16386. var m = pattern.exec(newValue);
  16387. var picker = memPicker.get(comp);
  16388. var optRgbForm = Composing.getCurrent(picker);
  16389. optRgbForm.fold(function () {
  16390. console.log('Can not find form');
  16391. }, function (rgbForm) {
  16392. Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') });
  16393. Form.getField(rgbForm, 'hex').each(function (hexField) {
  16394. emit(hexField, input());
  16395. });
  16396. });
  16397. }
  16398. }
  16399. }),
  16400. ComposingConfigs.self()
  16401. ])
  16402. };
  16403. };
  16404. var global$7 = tinymce.util.Tools.resolve('tinymce.Resource');
  16405. var isOldCustomEditor = function (spec) {
  16406. return has$2(spec, 'init');
  16407. };
  16408. var renderCustomEditor = function (spec) {
  16409. var editorApi = value$1();
  16410. var memReplaced = record({ dom: { tag: spec.tag } });
  16411. var initialValue = value$1();
  16412. return {
  16413. dom: {
  16414. tag: 'div',
  16415. classes: ['tox-custom-editor']
  16416. },
  16417. behaviours: derive$1([
  16418. config('custom-editor-events', [runOnAttached(function (component) {
  16419. memReplaced.getOpt(component).each(function (ta) {
  16420. (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$7.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  16421. return init(ta.element.dom, spec.settings);
  16422. })).then(function (ea) {
  16423. initialValue.on(function (cvalue) {
  16424. ea.setValue(cvalue);
  16425. });
  16426. initialValue.clear();
  16427. editorApi.set(ea);
  16428. });
  16429. });
  16430. })]),
  16431. Representing.config({
  16432. store: {
  16433. mode: 'manual',
  16434. getValue: function () {
  16435. return editorApi.get().fold(function () {
  16436. return initialValue.get().getOr('');
  16437. }, function (ed) {
  16438. return ed.getValue();
  16439. });
  16440. },
  16441. setValue: function (component, value) {
  16442. editorApi.get().fold(function () {
  16443. initialValue.set(value);
  16444. }, function (ed) {
  16445. return ed.setValue(value);
  16446. });
  16447. }
  16448. }
  16449. }),
  16450. ComposingConfigs.self()
  16451. ]),
  16452. components: [memReplaced.asSpec()]
  16453. };
  16454. };
  16455. var global$6 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  16456. var processors = objOf([
  16457. defaulted('preprocess', identity$1),
  16458. defaulted('postprocess', identity$1)
  16459. ]);
  16460. var memento = function (mem, rawProcessors) {
  16461. var ps = asRawOrDie$1('RepresentingConfigs.memento processors', processors, rawProcessors);
  16462. return Representing.config({
  16463. store: {
  16464. mode: 'manual',
  16465. getValue: function (comp) {
  16466. var other = mem.get(comp);
  16467. var rawValue = Representing.getValue(other);
  16468. return ps.postprocess(rawValue);
  16469. },
  16470. setValue: function (comp, rawValue) {
  16471. var newValue = ps.preprocess(rawValue);
  16472. var other = mem.get(comp);
  16473. Representing.setValue(other, newValue);
  16474. }
  16475. }
  16476. });
  16477. };
  16478. var withComp = function (optInitialValue, getter, setter) {
  16479. return Representing.config(deepMerge({
  16480. store: {
  16481. mode: 'manual',
  16482. getValue: getter,
  16483. setValue: setter
  16484. }
  16485. }, optInitialValue.map(function (initialValue) {
  16486. return { store: { initialValue: initialValue } };
  16487. }).getOr({})));
  16488. };
  16489. var withElement = function (initialValue, getter, setter) {
  16490. return withComp(initialValue, function (c) {
  16491. return getter(c.element);
  16492. }, function (c, v) {
  16493. return setter(c.element, v);
  16494. });
  16495. };
  16496. var domValue = function (optInitialValue) {
  16497. return withElement(optInitialValue, get$9, set$5);
  16498. };
  16499. var domHtml = function (optInitialValue) {
  16500. return withElement(optInitialValue, get$d, set$8);
  16501. };
  16502. var memory = function (initialValue) {
  16503. return Representing.config({
  16504. store: {
  16505. mode: 'memory',
  16506. initialValue: initialValue
  16507. }
  16508. });
  16509. };
  16510. var RepresentingConfigs = {
  16511. memento: memento,
  16512. withElement: withElement,
  16513. withComp: withComp,
  16514. domValue: domValue,
  16515. domHtml: domHtml,
  16516. memory: memory
  16517. };
  16518. var defaultImageFileTypes = 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp';
  16519. var filterByExtension = function (files, providersBackstage) {
  16520. var allowedImageFileTypes = global$6.explode(providersBackstage.getSetting('images_file_types', defaultImageFileTypes, 'string'));
  16521. var isFileInAllowedTypes = function (file) {
  16522. return exists(allowedImageFileTypes, function (type) {
  16523. return endsWith(file.name.toLowerCase(), '.' + type.toLowerCase());
  16524. });
  16525. };
  16526. return filter$2(from(files), isFileInAllowedTypes);
  16527. };
  16528. var renderDropZone = function (spec, providersBackstage) {
  16529. var stopper = function (_, se) {
  16530. se.stop();
  16531. };
  16532. var sequence = function (actions) {
  16533. return function (comp, se) {
  16534. each$1(actions, function (a) {
  16535. a(comp, se);
  16536. });
  16537. };
  16538. };
  16539. var onDrop = function (comp, se) {
  16540. if (!Disabling.isDisabled(comp)) {
  16541. var transferEvent = se.event.raw;
  16542. handleFiles(comp, transferEvent.dataTransfer.files);
  16543. }
  16544. };
  16545. var onSelect = function (component, simulatedEvent) {
  16546. var input = simulatedEvent.event.raw.target;
  16547. handleFiles(component, input.files);
  16548. };
  16549. var handleFiles = function (component, files) {
  16550. Representing.setValue(component, filterByExtension(files, providersBackstage));
  16551. emitWith(component, formChangeEvent, { name: spec.name });
  16552. };
  16553. var memInput = record({
  16554. dom: {
  16555. tag: 'input',
  16556. attributes: {
  16557. type: 'file',
  16558. accept: 'image/*'
  16559. },
  16560. styles: { display: 'none' }
  16561. },
  16562. behaviours: derive$1([config('input-file-events', [
  16563. cutter(click()),
  16564. cutter(tap())
  16565. ])])
  16566. });
  16567. var renderField = function (s) {
  16568. return {
  16569. uid: s.uid,
  16570. dom: {
  16571. tag: 'div',
  16572. classes: ['tox-dropzone-container']
  16573. },
  16574. behaviours: derive$1([
  16575. RepresentingConfigs.memory([]),
  16576. ComposingConfigs.self(),
  16577. Disabling.config({}),
  16578. Toggling.config({
  16579. toggleClass: 'dragenter',
  16580. toggleOnExecute: false
  16581. }),
  16582. config('dropzone-events', [
  16583. run$1('dragenter', sequence([
  16584. stopper,
  16585. Toggling.toggle
  16586. ])),
  16587. run$1('dragleave', sequence([
  16588. stopper,
  16589. Toggling.toggle
  16590. ])),
  16591. run$1('dragover', stopper),
  16592. run$1('drop', sequence([
  16593. stopper,
  16594. onDrop
  16595. ])),
  16596. run$1(change(), onSelect)
  16597. ])
  16598. ]),
  16599. components: [{
  16600. dom: {
  16601. tag: 'div',
  16602. classes: ['tox-dropzone'],
  16603. styles: {}
  16604. },
  16605. components: [
  16606. {
  16607. dom: {
  16608. tag: 'p',
  16609. innerHtml: providersBackstage.translate('Drop an image here')
  16610. }
  16611. },
  16612. Button.sketch({
  16613. dom: {
  16614. tag: 'button',
  16615. innerHtml: providersBackstage.translate('Browse for an image'),
  16616. styles: { position: 'relative' },
  16617. classes: [
  16618. 'tox-button',
  16619. 'tox-button--secondary'
  16620. ]
  16621. },
  16622. components: [memInput.asSpec()],
  16623. action: function (comp) {
  16624. var inputComp = memInput.get(comp);
  16625. inputComp.element.dom.click();
  16626. },
  16627. buttonBehaviours: derive$1([
  16628. Tabstopping.config({}),
  16629. DisablingConfigs.button(providersBackstage.isDisabled),
  16630. receivingConfig()
  16631. ])
  16632. })
  16633. ]
  16634. }]
  16635. };
  16636. };
  16637. var pLabel = spec.label.map(function (label) {
  16638. return renderLabel$2(label, providersBackstage);
  16639. });
  16640. var pField = FormField.parts.field({ factory: { sketch: renderField } });
  16641. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16642. };
  16643. var renderGrid = function (spec, backstage) {
  16644. return {
  16645. dom: {
  16646. tag: 'div',
  16647. classes: [
  16648. 'tox-form__grid',
  16649. 'tox-form__grid--' + spec.columns + 'col'
  16650. ]
  16651. },
  16652. components: map$2(spec.items, backstage.interpreter)
  16653. };
  16654. };
  16655. var beforeObject = generate$6('alloy-fake-before-tabstop');
  16656. var afterObject = generate$6('alloy-fake-after-tabstop');
  16657. var craftWithClasses = function (classes) {
  16658. return {
  16659. dom: {
  16660. tag: 'div',
  16661. styles: {
  16662. width: '1px',
  16663. height: '1px',
  16664. outline: 'none'
  16665. },
  16666. attributes: { tabindex: '0' },
  16667. classes: classes
  16668. },
  16669. behaviours: derive$1([
  16670. Focusing.config({ ignore: true }),
  16671. Tabstopping.config({})
  16672. ])
  16673. };
  16674. };
  16675. var craft = function (spec) {
  16676. return {
  16677. dom: {
  16678. tag: 'div',
  16679. classes: ['tox-navobj']
  16680. },
  16681. components: [
  16682. craftWithClasses([beforeObject]),
  16683. spec,
  16684. craftWithClasses([afterObject])
  16685. ],
  16686. behaviours: derive$1([ComposingConfigs.childAt(1)])
  16687. };
  16688. };
  16689. var triggerTab = function (placeholder, shiftKey) {
  16690. emitWith(placeholder, keydown(), {
  16691. raw: {
  16692. which: 9,
  16693. shiftKey: shiftKey
  16694. }
  16695. });
  16696. };
  16697. var onFocus = function (container, targetComp) {
  16698. var target = targetComp.element;
  16699. if (has(target, beforeObject)) {
  16700. triggerTab(container, true);
  16701. } else if (has(target, afterObject)) {
  16702. triggerTab(container, false);
  16703. }
  16704. };
  16705. var isPseudoStop = function (element) {
  16706. return closest(element, [
  16707. '.' + beforeObject,
  16708. '.' + afterObject
  16709. ].join(','), never);
  16710. };
  16711. var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge());
  16712. var getDynamicSource = function (isSandbox) {
  16713. var cachedValue = Cell('');
  16714. return {
  16715. getValue: function (_frameComponent) {
  16716. return cachedValue.get();
  16717. },
  16718. setValue: function (frameComponent, html) {
  16719. if (!isSandbox) {
  16720. set$7(frameComponent.element, 'src', 'javascript:\'\'');
  16721. var doc = frameComponent.element.dom.contentWindow.document;
  16722. doc.open();
  16723. doc.write(html);
  16724. doc.close();
  16725. } else {
  16726. set$7(frameComponent.element, 'srcdoc', html);
  16727. }
  16728. cachedValue.set(html);
  16729. }
  16730. };
  16731. };
  16732. var renderIFrame = function (spec, providersBackstage) {
  16733. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  16734. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  16735. return { title: title };
  16736. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  16737. var sourcing = getDynamicSource(isSandbox);
  16738. var pLabel = spec.label.map(function (label) {
  16739. return renderLabel$2(label, providersBackstage);
  16740. });
  16741. var factory = function (newSpec) {
  16742. return craft({
  16743. uid: newSpec.uid,
  16744. dom: {
  16745. tag: 'iframe',
  16746. attributes: attributes
  16747. },
  16748. behaviours: derive$1([
  16749. Tabstopping.config({}),
  16750. Focusing.config({}),
  16751. RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
  16752. ])
  16753. });
  16754. };
  16755. var pField = FormField.parts.field({ factory: { sketch: factory } });
  16756. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16757. };
  16758. var create$3 = function (width, height) {
  16759. return resize$3(document.createElement('canvas'), width, height);
  16760. };
  16761. var clone = function (canvas) {
  16762. var tCanvas = create$3(canvas.width, canvas.height);
  16763. var ctx = get2dContext(tCanvas);
  16764. ctx.drawImage(canvas, 0, 0);
  16765. return tCanvas;
  16766. };
  16767. var get2dContext = function (canvas) {
  16768. return canvas.getContext('2d');
  16769. };
  16770. var resize$3 = function (canvas, width, height) {
  16771. canvas.width = width;
  16772. canvas.height = height;
  16773. return canvas;
  16774. };
  16775. var getWidth$1 = function (image) {
  16776. return image.naturalWidth || image.width;
  16777. };
  16778. var getHeight$1 = function (image) {
  16779. return image.naturalHeight || image.height;
  16780. };
  16781. var promise = function () {
  16782. var Promise = function (fn) {
  16783. if (typeof this !== 'object') {
  16784. throw new TypeError('Promises must be constructed via new');
  16785. }
  16786. if (typeof fn !== 'function') {
  16787. throw new TypeError('not a function');
  16788. }
  16789. this._state = null;
  16790. this._value = null;
  16791. this._deferreds = [];
  16792. doResolve(fn, bind(resolve, this), bind(reject, this));
  16793. };
  16794. var anyWindow = window;
  16795. var asap = Promise.immediateFn || typeof anyWindow.setImmediate === 'function' && anyWindow.setImmediate || function (fn) {
  16796. return setTimeout(fn, 1);
  16797. };
  16798. var bind = function (fn, thisArg) {
  16799. return function () {
  16800. var args = [];
  16801. for (var _i = 0; _i < arguments.length; _i++) {
  16802. args[_i] = arguments[_i];
  16803. }
  16804. return fn.apply(thisArg, args);
  16805. };
  16806. };
  16807. var isArray = Array.isArray || function (value) {
  16808. return Object.prototype.toString.call(value) === '[object Array]';
  16809. };
  16810. function handle(deferred) {
  16811. var me = this;
  16812. if (this._state === null) {
  16813. this._deferreds.push(deferred);
  16814. return;
  16815. }
  16816. asap(function () {
  16817. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  16818. if (cb === null) {
  16819. (me._state ? deferred.resolve : deferred.reject)(me._value);
  16820. return;
  16821. }
  16822. var ret;
  16823. try {
  16824. ret = cb(me._value);
  16825. } catch (e) {
  16826. deferred.reject(e);
  16827. return;
  16828. }
  16829. deferred.resolve(ret);
  16830. });
  16831. }
  16832. function resolve(newValue) {
  16833. try {
  16834. if (newValue === this) {
  16835. throw new TypeError('A promise cannot be resolved with itself.');
  16836. }
  16837. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  16838. var then = newValue.then;
  16839. if (typeof then === 'function') {
  16840. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  16841. return;
  16842. }
  16843. }
  16844. this._state = true;
  16845. this._value = newValue;
  16846. finale.call(this);
  16847. } catch (e) {
  16848. reject.call(this, e);
  16849. }
  16850. }
  16851. function reject(newValue) {
  16852. this._state = false;
  16853. this._value = newValue;
  16854. finale.call(this);
  16855. }
  16856. function finale() {
  16857. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  16858. var deferred = _a[_i];
  16859. handle.call(this, deferred);
  16860. }
  16861. this._deferreds = [];
  16862. }
  16863. function Handler(onFulfilled, onRejected, resolve, reject) {
  16864. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  16865. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  16866. this.resolve = resolve;
  16867. this.reject = reject;
  16868. }
  16869. var doResolve = function (fn, onFulfilled, onRejected) {
  16870. var done = false;
  16871. try {
  16872. fn(function (value) {
  16873. if (done) {
  16874. return;
  16875. }
  16876. done = true;
  16877. onFulfilled(value);
  16878. }, function (reason) {
  16879. if (done) {
  16880. return;
  16881. }
  16882. done = true;
  16883. onRejected(reason);
  16884. });
  16885. } catch (ex) {
  16886. if (done) {
  16887. return;
  16888. }
  16889. done = true;
  16890. onRejected(ex);
  16891. }
  16892. };
  16893. Promise.prototype.catch = function (onRejected) {
  16894. return this.then(null, onRejected);
  16895. };
  16896. Promise.prototype.then = function (onFulfilled, onRejected) {
  16897. var me = this;
  16898. return new Promise(function (resolve, reject) {
  16899. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  16900. });
  16901. };
  16902. Promise.all = function () {
  16903. var values = [];
  16904. for (var _i = 0; _i < arguments.length; _i++) {
  16905. values[_i] = arguments[_i];
  16906. }
  16907. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  16908. return new Promise(function (resolve, reject) {
  16909. if (args.length === 0) {
  16910. return resolve([]);
  16911. }
  16912. var remaining = args.length;
  16913. var res = function (i, val) {
  16914. try {
  16915. if (val && (typeof val === 'object' || typeof val === 'function')) {
  16916. var then = val.then;
  16917. if (typeof then === 'function') {
  16918. then.call(val, function (val) {
  16919. res(i, val);
  16920. }, reject);
  16921. return;
  16922. }
  16923. }
  16924. args[i] = val;
  16925. if (--remaining === 0) {
  16926. resolve(args);
  16927. }
  16928. } catch (ex) {
  16929. reject(ex);
  16930. }
  16931. };
  16932. for (var i = 0; i < args.length; i++) {
  16933. res(i, args[i]);
  16934. }
  16935. });
  16936. };
  16937. Promise.resolve = function (value) {
  16938. if (value && typeof value === 'object' && value.constructor === Promise) {
  16939. return value;
  16940. }
  16941. return new Promise(function (resolve) {
  16942. resolve(value);
  16943. });
  16944. };
  16945. Promise.reject = function (reason) {
  16946. return new Promise(function (resolve, reject) {
  16947. reject(reason);
  16948. });
  16949. };
  16950. Promise.race = function (values) {
  16951. return new Promise(function (resolve, reject) {
  16952. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  16953. var value = values_1[_i];
  16954. value.then(resolve, reject);
  16955. }
  16956. });
  16957. };
  16958. return Promise;
  16959. };
  16960. var Promise$1 = window.Promise ? window.Promise : promise();
  16961. var blobToImage = function (blob) {
  16962. return new Promise$1(function (resolve, reject) {
  16963. var blobUrl = URL.createObjectURL(blob);
  16964. var image = new Image();
  16965. var removeListeners = function () {
  16966. image.removeEventListener('load', loaded);
  16967. image.removeEventListener('error', error);
  16968. };
  16969. var loaded = function () {
  16970. removeListeners();
  16971. resolve(image);
  16972. };
  16973. var error = function () {
  16974. removeListeners();
  16975. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16976. };
  16977. image.addEventListener('load', loaded);
  16978. image.addEventListener('error', error);
  16979. image.src = blobUrl;
  16980. if (image.complete) {
  16981. setTimeout(loaded, 0);
  16982. }
  16983. });
  16984. };
  16985. var dataUriToBlobSync = function (uri) {
  16986. var data = uri.split(',');
  16987. var matches = /data:([^;]+)/.exec(data[0]);
  16988. if (!matches) {
  16989. return Optional.none();
  16990. }
  16991. var mimetype = matches[1];
  16992. var base64 = data[1];
  16993. var sliceSize = 1024;
  16994. var byteCharacters = atob(base64);
  16995. var bytesLength = byteCharacters.length;
  16996. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16997. var byteArrays = new Array(slicesCount);
  16998. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16999. var begin = sliceIndex * sliceSize;
  17000. var end = Math.min(begin + sliceSize, bytesLength);
  17001. var bytes = new Array(end - begin);
  17002. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  17003. bytes[i] = byteCharacters[offset].charCodeAt(0);
  17004. }
  17005. byteArrays[sliceIndex] = new Uint8Array(bytes);
  17006. }
  17007. return Optional.some(new Blob(byteArrays, { type: mimetype }));
  17008. };
  17009. var dataUriToBlob = function (uri) {
  17010. return new Promise$1(function (resolve, reject) {
  17011. dataUriToBlobSync(uri).fold(function () {
  17012. reject('uri is not base64: ' + uri);
  17013. }, resolve);
  17014. });
  17015. };
  17016. var canvasToBlob = function (canvas, type, quality) {
  17017. type = type || 'image/png';
  17018. if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
  17019. return new Promise$1(function (resolve, reject) {
  17020. canvas.toBlob(function (blob) {
  17021. if (blob) {
  17022. resolve(blob);
  17023. } else {
  17024. reject();
  17025. }
  17026. }, type, quality);
  17027. });
  17028. } else {
  17029. return dataUriToBlob(canvas.toDataURL(type, quality));
  17030. }
  17031. };
  17032. var canvasToDataURL = function (canvas, type, quality) {
  17033. type = type || 'image/png';
  17034. return canvas.toDataURL(type, quality);
  17035. };
  17036. var blobToCanvas = function (blob) {
  17037. return blobToImage(blob).then(function (image) {
  17038. revokeImageUrl(image);
  17039. var canvas = create$3(getWidth$1(image), getHeight$1(image));
  17040. var context = get2dContext(canvas);
  17041. context.drawImage(image, 0, 0);
  17042. return canvas;
  17043. });
  17044. };
  17045. var blobToDataUri = function (blob) {
  17046. return new Promise$1(function (resolve) {
  17047. var reader = new FileReader();
  17048. reader.onloadend = function () {
  17049. resolve(reader.result);
  17050. };
  17051. reader.readAsDataURL(blob);
  17052. });
  17053. };
  17054. var revokeImageUrl = function (image) {
  17055. URL.revokeObjectURL(image.src);
  17056. };
  17057. var create$2 = function (getCanvas, blob, uri) {
  17058. var initialType = blob.type;
  17059. var getType = constant$1(initialType);
  17060. var toBlob = function () {
  17061. return Promise$1.resolve(blob);
  17062. };
  17063. var toDataURL = constant$1(uri);
  17064. var toBase64 = function () {
  17065. return uri.split(',')[1];
  17066. };
  17067. var toAdjustedBlob = function (type, quality) {
  17068. return getCanvas.then(function (canvas) {
  17069. return canvasToBlob(canvas, type, quality);
  17070. });
  17071. };
  17072. var toAdjustedDataURL = function (type, quality) {
  17073. return getCanvas.then(function (canvas) {
  17074. return canvasToDataURL(canvas, type, quality);
  17075. });
  17076. };
  17077. var toAdjustedBase64 = function (type, quality) {
  17078. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  17079. return dataurl.split(',')[1];
  17080. });
  17081. };
  17082. var toCanvas = function () {
  17083. return getCanvas.then(clone);
  17084. };
  17085. return {
  17086. getType: getType,
  17087. toBlob: toBlob,
  17088. toDataURL: toDataURL,
  17089. toBase64: toBase64,
  17090. toAdjustedBlob: toAdjustedBlob,
  17091. toAdjustedDataURL: toAdjustedDataURL,
  17092. toAdjustedBase64: toAdjustedBase64,
  17093. toCanvas: toCanvas
  17094. };
  17095. };
  17096. var fromBlob = function (blob) {
  17097. return blobToDataUri(blob).then(function (uri) {
  17098. return create$2(blobToCanvas(blob), blob, uri);
  17099. });
  17100. };
  17101. var fromCanvas = function (canvas, type) {
  17102. return canvasToBlob(canvas, type).then(function (blob) {
  17103. return create$2(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  17104. });
  17105. };
  17106. var blobToImageResult = function (blob) {
  17107. return fromBlob(blob);
  17108. };
  17109. var clamp = function (value, min, max) {
  17110. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  17111. if (parsedValue > max) {
  17112. parsedValue = max;
  17113. } else if (parsedValue < min) {
  17114. parsedValue = min;
  17115. }
  17116. return parsedValue;
  17117. };
  17118. var identity = function () {
  17119. return [
  17120. 1,
  17121. 0,
  17122. 0,
  17123. 0,
  17124. 0,
  17125. 0,
  17126. 1,
  17127. 0,
  17128. 0,
  17129. 0,
  17130. 0,
  17131. 0,
  17132. 1,
  17133. 0,
  17134. 0,
  17135. 0,
  17136. 0,
  17137. 0,
  17138. 1,
  17139. 0,
  17140. 0,
  17141. 0,
  17142. 0,
  17143. 0,
  17144. 1
  17145. ];
  17146. };
  17147. var DELTA_INDEX = [
  17148. 0,
  17149. 0.01,
  17150. 0.02,
  17151. 0.04,
  17152. 0.05,
  17153. 0.06,
  17154. 0.07,
  17155. 0.08,
  17156. 0.1,
  17157. 0.11,
  17158. 0.12,
  17159. 0.14,
  17160. 0.15,
  17161. 0.16,
  17162. 0.17,
  17163. 0.18,
  17164. 0.2,
  17165. 0.21,
  17166. 0.22,
  17167. 0.24,
  17168. 0.25,
  17169. 0.27,
  17170. 0.28,
  17171. 0.3,
  17172. 0.32,
  17173. 0.34,
  17174. 0.36,
  17175. 0.38,
  17176. 0.4,
  17177. 0.42,
  17178. 0.44,
  17179. 0.46,
  17180. 0.48,
  17181. 0.5,
  17182. 0.53,
  17183. 0.56,
  17184. 0.59,
  17185. 0.62,
  17186. 0.65,
  17187. 0.68,
  17188. 0.71,
  17189. 0.74,
  17190. 0.77,
  17191. 0.8,
  17192. 0.83,
  17193. 0.86,
  17194. 0.89,
  17195. 0.92,
  17196. 0.95,
  17197. 0.98,
  17198. 1,
  17199. 1.06,
  17200. 1.12,
  17201. 1.18,
  17202. 1.24,
  17203. 1.3,
  17204. 1.36,
  17205. 1.42,
  17206. 1.48,
  17207. 1.54,
  17208. 1.6,
  17209. 1.66,
  17210. 1.72,
  17211. 1.78,
  17212. 1.84,
  17213. 1.9,
  17214. 1.96,
  17215. 2,
  17216. 2.12,
  17217. 2.25,
  17218. 2.37,
  17219. 2.5,
  17220. 2.62,
  17221. 2.75,
  17222. 2.87,
  17223. 3,
  17224. 3.2,
  17225. 3.4,
  17226. 3.6,
  17227. 3.8,
  17228. 4,
  17229. 4.3,
  17230. 4.7,
  17231. 4.9,
  17232. 5,
  17233. 5.5,
  17234. 6,
  17235. 6.5,
  17236. 6.8,
  17237. 7,
  17238. 7.3,
  17239. 7.5,
  17240. 7.8,
  17241. 8,
  17242. 8.4,
  17243. 8.7,
  17244. 9,
  17245. 9.4,
  17246. 9.6,
  17247. 9.8,
  17248. 10
  17249. ];
  17250. var multiply = function (matrix1, matrix2) {
  17251. var col = [];
  17252. var out = new Array(25);
  17253. var val;
  17254. for (var i = 0; i < 5; i++) {
  17255. for (var j = 0; j < 5; j++) {
  17256. col[j] = matrix2[j + i * 5];
  17257. }
  17258. for (var j = 0; j < 5; j++) {
  17259. val = 0;
  17260. for (var k = 0; k < 5; k++) {
  17261. val += matrix1[j + k * 5] * col[k];
  17262. }
  17263. out[j + i * 5] = val;
  17264. }
  17265. }
  17266. return out;
  17267. };
  17268. var adjustContrast = function (matrix, value) {
  17269. var x;
  17270. value = clamp(value, -1, 1);
  17271. value *= 100;
  17272. if (value < 0) {
  17273. x = 127 + value / 100 * 127;
  17274. } else {
  17275. x = value % 1;
  17276. if (x === 0) {
  17277. x = DELTA_INDEX[value];
  17278. } else {
  17279. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  17280. }
  17281. x = x * 127 + 127;
  17282. }
  17283. return multiply(matrix, [
  17284. x / 127,
  17285. 0,
  17286. 0,
  17287. 0,
  17288. 0.5 * (127 - x),
  17289. 0,
  17290. x / 127,
  17291. 0,
  17292. 0,
  17293. 0.5 * (127 - x),
  17294. 0,
  17295. 0,
  17296. x / 127,
  17297. 0,
  17298. 0.5 * (127 - x),
  17299. 0,
  17300. 0,
  17301. 0,
  17302. 1,
  17303. 0,
  17304. 0,
  17305. 0,
  17306. 0,
  17307. 0,
  17308. 1
  17309. ]);
  17310. };
  17311. var adjustBrightness = function (matrix, value) {
  17312. value = clamp(255 * value, -255, 255);
  17313. return multiply(matrix, [
  17314. 1,
  17315. 0,
  17316. 0,
  17317. 0,
  17318. value,
  17319. 0,
  17320. 1,
  17321. 0,
  17322. 0,
  17323. value,
  17324. 0,
  17325. 0,
  17326. 1,
  17327. 0,
  17328. value,
  17329. 0,
  17330. 0,
  17331. 0,
  17332. 1,
  17333. 0,
  17334. 0,
  17335. 0,
  17336. 0,
  17337. 0,
  17338. 1
  17339. ]);
  17340. };
  17341. var adjustColors = function (matrix, adjustR, adjustG, adjustB) {
  17342. adjustR = clamp(adjustR, 0, 2);
  17343. adjustG = clamp(adjustG, 0, 2);
  17344. adjustB = clamp(adjustB, 0, 2);
  17345. return multiply(matrix, [
  17346. adjustR,
  17347. 0,
  17348. 0,
  17349. 0,
  17350. 0,
  17351. 0,
  17352. adjustG,
  17353. 0,
  17354. 0,
  17355. 0,
  17356. 0,
  17357. 0,
  17358. adjustB,
  17359. 0,
  17360. 0,
  17361. 0,
  17362. 0,
  17363. 0,
  17364. 1,
  17365. 0,
  17366. 0,
  17367. 0,
  17368. 0,
  17369. 0,
  17370. 1
  17371. ]);
  17372. };
  17373. var colorFilter = function (ir, matrix) {
  17374. return ir.toCanvas().then(function (canvas) {
  17375. return applyColorFilter(canvas, ir.getType(), matrix);
  17376. });
  17377. };
  17378. var applyColorFilter = function (canvas, type, matrix) {
  17379. var context = get2dContext(canvas);
  17380. var applyMatrix = function (pixelsData, m) {
  17381. var r, g, b, a;
  17382. var data = pixelsData.data, m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8], m9 = m[9], m10 = m[10], m11 = m[11], m12 = m[12], m13 = m[13], m14 = m[14], m15 = m[15], m16 = m[16], m17 = m[17], m18 = m[18], m19 = m[19];
  17383. for (var i = 0; i < data.length; i += 4) {
  17384. r = data[i];
  17385. g = data[i + 1];
  17386. b = data[i + 2];
  17387. a = data[i + 3];
  17388. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  17389. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  17390. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  17391. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  17392. }
  17393. return pixelsData;
  17394. };
  17395. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  17396. context.putImageData(pixels, 0, 0);
  17397. return fromCanvas(canvas, type);
  17398. };
  17399. var convoluteFilter = function (ir, matrix) {
  17400. return ir.toCanvas().then(function (canvas) {
  17401. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  17402. });
  17403. };
  17404. var applyConvoluteFilter = function (canvas, type, matrix) {
  17405. var context = get2dContext(canvas);
  17406. var applyMatrix = function (pIn, pOut, aMatrix) {
  17407. var clamp = function (value, min, max) {
  17408. if (value > max) {
  17409. value = max;
  17410. } else if (value < min) {
  17411. value = min;
  17412. }
  17413. return value;
  17414. };
  17415. var side = Math.round(Math.sqrt(aMatrix.length));
  17416. var halfSide = Math.floor(side / 2);
  17417. var rgba = pIn.data;
  17418. var drgba = pOut.data;
  17419. var w = pIn.width;
  17420. var h = pIn.height;
  17421. for (var y = 0; y < h; y++) {
  17422. for (var x = 0; x < w; x++) {
  17423. var r = 0;
  17424. var g = 0;
  17425. var b = 0;
  17426. for (var cy = 0; cy < side; cy++) {
  17427. for (var cx = 0; cx < side; cx++) {
  17428. var scx = clamp(x + cx - halfSide, 0, w - 1);
  17429. var scy = clamp(y + cy - halfSide, 0, h - 1);
  17430. var innerOffset = (scy * w + scx) * 4;
  17431. var wt = aMatrix[cy * side + cx];
  17432. r += rgba[innerOffset] * wt;
  17433. g += rgba[innerOffset + 1] * wt;
  17434. b += rgba[innerOffset + 2] * wt;
  17435. }
  17436. }
  17437. var offset = (y * w + x) * 4;
  17438. drgba[offset] = clamp(r, 0, 255);
  17439. drgba[offset + 1] = clamp(g, 0, 255);
  17440. drgba[offset + 2] = clamp(b, 0, 255);
  17441. }
  17442. }
  17443. return pOut;
  17444. };
  17445. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  17446. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  17447. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  17448. context.putImageData(pixelsOut, 0, 0);
  17449. return fromCanvas(canvas, type);
  17450. };
  17451. var functionColorFilter = function (colorFn) {
  17452. var filterImpl = function (canvas, type, value) {
  17453. var context = get2dContext(canvas);
  17454. var lookup = new Array(256);
  17455. var applyLookup = function (pixelsData, lookupData) {
  17456. var data = pixelsData.data;
  17457. for (var i = 0; i < data.length; i += 4) {
  17458. data[i] = lookupData[data[i]];
  17459. data[i + 1] = lookupData[data[i + 1]];
  17460. data[i + 2] = lookupData[data[i + 2]];
  17461. }
  17462. return pixelsData;
  17463. };
  17464. for (var i = 0; i < lookup.length; i++) {
  17465. lookup[i] = colorFn(i, value);
  17466. }
  17467. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  17468. context.putImageData(pixels, 0, 0);
  17469. return fromCanvas(canvas, type);
  17470. };
  17471. return function (ir, value) {
  17472. return ir.toCanvas().then(function (canvas) {
  17473. return filterImpl(canvas, ir.getType(), value);
  17474. });
  17475. };
  17476. };
  17477. var complexAdjustableColorFilter = function (matrixAdjustFn) {
  17478. return function (ir, adjust) {
  17479. return colorFilter(ir, matrixAdjustFn(identity(), adjust));
  17480. };
  17481. };
  17482. var basicColorFilter = function (matrix) {
  17483. return function (ir) {
  17484. return colorFilter(ir, matrix);
  17485. };
  17486. };
  17487. var basicConvolutionFilter = function (kernel) {
  17488. return function (ir) {
  17489. return convoluteFilter(ir, kernel);
  17490. };
  17491. };
  17492. var invert$1 = basicColorFilter([
  17493. -1,
  17494. 0,
  17495. 0,
  17496. 0,
  17497. 255,
  17498. 0,
  17499. -1,
  17500. 0,
  17501. 0,
  17502. 255,
  17503. 0,
  17504. 0,
  17505. -1,
  17506. 0,
  17507. 255,
  17508. 0,
  17509. 0,
  17510. 0,
  17511. 1,
  17512. 0,
  17513. 0,
  17514. 0,
  17515. 0,
  17516. 0,
  17517. 1
  17518. ]);
  17519. var brightness$1 = complexAdjustableColorFilter(adjustBrightness);
  17520. var contrast$1 = complexAdjustableColorFilter(adjustContrast);
  17521. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  17522. return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB));
  17523. };
  17524. var sharpen$1 = basicConvolutionFilter([
  17525. 0,
  17526. -1,
  17527. 0,
  17528. -1,
  17529. 5,
  17530. -1,
  17531. 0,
  17532. -1,
  17533. 0
  17534. ]);
  17535. var gamma$1 = functionColorFilter(function (color, value) {
  17536. return Math.pow(color / 255, 1 - value) * 255;
  17537. });
  17538. var scale = function (image, dW, dH) {
  17539. var sW = getWidth$1(image);
  17540. var sH = getHeight$1(image);
  17541. var wRatio = dW / sW;
  17542. var hRatio = dH / sH;
  17543. var scaleCapped = false;
  17544. if (wRatio < 0.5 || wRatio > 2) {
  17545. wRatio = wRatio < 0.5 ? 0.5 : 2;
  17546. scaleCapped = true;
  17547. }
  17548. if (hRatio < 0.5 || hRatio > 2) {
  17549. hRatio = hRatio < 0.5 ? 0.5 : 2;
  17550. scaleCapped = true;
  17551. }
  17552. var scaled = _scale(image, wRatio, hRatio);
  17553. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  17554. return scale(tCanvas, dW, dH);
  17555. });
  17556. };
  17557. var _scale = function (image, wRatio, hRatio) {
  17558. return new Promise$1(function (resolve) {
  17559. var sW = getWidth$1(image);
  17560. var sH = getHeight$1(image);
  17561. var dW = Math.floor(sW * wRatio);
  17562. var dH = Math.floor(sH * hRatio);
  17563. var canvas = create$3(dW, dH);
  17564. var context = get2dContext(canvas);
  17565. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  17566. resolve(canvas);
  17567. });
  17568. };
  17569. var ceilWithPrecision = function (num, precision) {
  17570. if (precision === void 0) {
  17571. precision = 2;
  17572. }
  17573. var mul = Math.pow(10, precision);
  17574. var upper = Math.round(num * mul);
  17575. return Math.ceil(upper / mul);
  17576. };
  17577. var rotate$1 = function (ir, angle) {
  17578. return ir.toCanvas().then(function (canvas) {
  17579. return applyRotate(canvas, ir.getType(), angle);
  17580. });
  17581. };
  17582. var applyRotate = function (image, type, angle) {
  17583. var degrees = angle < 0 ? 360 + angle : angle;
  17584. var rad = degrees * Math.PI / 180;
  17585. var width = image.width;
  17586. var height = image.height;
  17587. var sin = Math.sin(rad);
  17588. var cos = Math.cos(rad);
  17589. var newWidth = ceilWithPrecision(Math.abs(width * cos) + Math.abs(height * sin));
  17590. var newHeight = ceilWithPrecision(Math.abs(width * sin) + Math.abs(height * cos));
  17591. var canvas = create$3(newWidth, newHeight);
  17592. var context = get2dContext(canvas);
  17593. context.translate(newWidth / 2, newHeight / 2);
  17594. context.rotate(rad);
  17595. context.drawImage(image, -width / 2, -height / 2);
  17596. return fromCanvas(canvas, type);
  17597. };
  17598. var flip$1 = function (ir, axis) {
  17599. return ir.toCanvas().then(function (canvas) {
  17600. return applyFlip(canvas, ir.getType(), axis);
  17601. });
  17602. };
  17603. var applyFlip = function (image, type, axis) {
  17604. var canvas = create$3(image.width, image.height);
  17605. var context = get2dContext(canvas);
  17606. if (axis === 'v') {
  17607. context.scale(1, -1);
  17608. context.drawImage(image, 0, -canvas.height);
  17609. } else {
  17610. context.scale(-1, 1);
  17611. context.drawImage(image, -canvas.width, 0);
  17612. }
  17613. return fromCanvas(canvas, type);
  17614. };
  17615. var crop$1 = function (ir, x, y, w, h) {
  17616. return ir.toCanvas().then(function (canvas) {
  17617. return applyCrop(canvas, ir.getType(), x, y, w, h);
  17618. });
  17619. };
  17620. var applyCrop = function (image, type, x, y, w, h) {
  17621. var canvas = create$3(w, h);
  17622. var context = get2dContext(canvas);
  17623. context.drawImage(image, -x, -y);
  17624. return fromCanvas(canvas, type);
  17625. };
  17626. var resize$2 = function (ir, w, h) {
  17627. return ir.toCanvas().then(function (canvas) {
  17628. return scale(canvas, w, h).then(function (newCanvas) {
  17629. return fromCanvas(newCanvas, ir.getType());
  17630. });
  17631. });
  17632. };
  17633. var invert = function (ir) {
  17634. return invert$1(ir);
  17635. };
  17636. var sharpen = function (ir) {
  17637. return sharpen$1(ir);
  17638. };
  17639. var gamma = function (ir, value) {
  17640. return gamma$1(ir, value);
  17641. };
  17642. var colorize = function (ir, adjustR, adjustG, adjustB) {
  17643. return colorize$1(ir, adjustR, adjustG, adjustB);
  17644. };
  17645. var brightness = function (ir, adjust) {
  17646. return brightness$1(ir, adjust);
  17647. };
  17648. var contrast = function (ir, adjust) {
  17649. return contrast$1(ir, adjust);
  17650. };
  17651. var flip = function (ir, axis) {
  17652. return flip$1(ir, axis);
  17653. };
  17654. var crop = function (ir, x, y, w, h) {
  17655. return crop$1(ir, x, y, w, h);
  17656. };
  17657. var resize$1 = function (ir, w, h) {
  17658. return resize$2(ir, w, h);
  17659. };
  17660. var rotate = function (ir, angle) {
  17661. return rotate$1(ir, angle);
  17662. };
  17663. var renderIcon = function (iconName, iconsProvider, behaviours) {
  17664. return render$3(iconName, {
  17665. tag: 'span',
  17666. classes: [
  17667. 'tox-icon',
  17668. 'tox-tbtn__icon-wrap'
  17669. ],
  17670. behaviours: behaviours
  17671. }, iconsProvider);
  17672. };
  17673. var renderIconFromPack = function (iconName, iconsProvider) {
  17674. return renderIcon(iconName, iconsProvider, []);
  17675. };
  17676. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  17677. return renderIcon(iconName, iconsProvider, [Replacing.config({})]);
  17678. };
  17679. var renderLabel$1 = function (text, prefix, providersBackstage) {
  17680. return {
  17681. dom: {
  17682. tag: 'span',
  17683. innerHtml: providersBackstage.translate(text),
  17684. classes: [prefix + '__select-label']
  17685. },
  17686. behaviours: derive$1([Replacing.config({})])
  17687. };
  17688. };
  17689. var _a;
  17690. var internalToolbarButtonExecute = generate$6('toolbar.button.execute');
  17691. var onToolbarButtonExecute = function (info) {
  17692. return runOnExecute$1(function (comp, _simulatedEvent) {
  17693. runWithApi(info, comp)(function (itemApi) {
  17694. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  17695. info.onAction(itemApi);
  17696. });
  17697. });
  17698. };
  17699. var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [
  17700. 'disabling',
  17701. 'alloy.base.behaviour',
  17702. 'toggling',
  17703. 'toolbar-button-events'
  17704. ], _a);
  17705. var updateMenuText = generate$6('update-menu-text');
  17706. var updateMenuIcon = generate$6('update-menu-icon');
  17707. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  17708. var editorOffCell = Cell(noop);
  17709. var optMemDisplayText = spec.text.map(function (text) {
  17710. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  17711. });
  17712. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  17713. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  17714. });
  17715. var onLeftOrRightInMenu = function (comp, se) {
  17716. var dropdown = Representing.getValue(comp);
  17717. Focusing.focus(dropdown);
  17718. emitWith(dropdown, 'keydown', { raw: se.event.raw });
  17719. Dropdown.close(dropdown);
  17720. return Optional.some(true);
  17721. };
  17722. var role = spec.role.fold(function () {
  17723. return {};
  17724. }, function (role) {
  17725. return { role: role };
  17726. });
  17727. var tooltipAttributes = spec.tooltip.fold(function () {
  17728. return {};
  17729. }, function (tooltip) {
  17730. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  17731. return {
  17732. 'title': translatedTooltip,
  17733. 'aria-label': translatedTooltip
  17734. };
  17735. });
  17736. var iconSpec = render$3('chevron-down', {
  17737. tag: 'div',
  17738. classes: [prefix + '__select-chevron']
  17739. }, sharedBackstage.providers.icons);
  17740. var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
  17741. dom: {
  17742. tag: 'button',
  17743. classes: [
  17744. prefix,
  17745. prefix + '--select'
  17746. ].concat(map$2(spec.classes, function (c) {
  17747. return prefix + '--' + c;
  17748. })),
  17749. attributes: __assign({}, tooltipAttributes)
  17750. },
  17751. components: componentRenderPipeline([
  17752. optMemDisplayIcon.map(function (mem) {
  17753. return mem.asSpec();
  17754. }),
  17755. optMemDisplayText.map(function (mem) {
  17756. return mem.asSpec();
  17757. }),
  17758. Optional.some(iconSpec)
  17759. ]),
  17760. matchWidth: true,
  17761. useMinWidth: true,
  17762. dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours), [
  17763. DisablingConfigs.button(function () {
  17764. return spec.disabled || sharedBackstage.providers.isDisabled();
  17765. }),
  17766. receivingConfig(),
  17767. Unselecting.config({}),
  17768. Replacing.config({}),
  17769. config('dropdown-events', [
  17770. onControlAttached(spec, editorOffCell),
  17771. onControlDetached(spec, editorOffCell)
  17772. ]),
  17773. config('menubutton-update-display-text', [
  17774. run$1(updateMenuText, function (comp, se) {
  17775. optMemDisplayText.bind(function (mem) {
  17776. return mem.getOpt(comp);
  17777. }).each(function (displayText) {
  17778. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event.text))]);
  17779. });
  17780. }),
  17781. run$1(updateMenuIcon, function (comp, se) {
  17782. optMemDisplayIcon.bind(function (mem) {
  17783. return mem.getOpt(comp);
  17784. }).each(function (displayIcon) {
  17785. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
  17786. });
  17787. })
  17788. ])
  17789. ])),
  17790. eventOrder: deepMerge(toolbarButtonEventOrder, {
  17791. mousedown: [
  17792. 'focusing',
  17793. 'alloy.base.behaviour',
  17794. 'item-type-events',
  17795. 'normal-dropdown-events'
  17796. ]
  17797. }),
  17798. sandboxBehaviours: derive$1([Keying.config({
  17799. mode: 'special',
  17800. onLeft: onLeftOrRightInMenu,
  17801. onRight: onLeftOrRightInMenu
  17802. })]),
  17803. lazySink: sharedBackstage.getSink,
  17804. toggleClass: prefix + '--active',
  17805. parts: { menu: part(false, spec.columns, spec.presets) },
  17806. fetch: function (comp) {
  17807. return Future.nu(curry(spec.fetch, comp));
  17808. }
  17809. })));
  17810. return memDropdown.asSpec();
  17811. };
  17812. var isMenuItemReference = function (item) {
  17813. return isString(item);
  17814. };
  17815. var isSeparator$1 = function (item) {
  17816. return item.type === 'separator';
  17817. };
  17818. var isExpandingMenuItem = function (item) {
  17819. return has$2(item, 'getSubmenuItems');
  17820. };
  17821. var separator$2 = { type: 'separator' };
  17822. var unwrapReferences = function (items, menuItems) {
  17823. var realItems = foldl(items, function (acc, item) {
  17824. if (isMenuItemReference(item)) {
  17825. if (item === '') {
  17826. return acc;
  17827. } else if (item === '|') {
  17828. return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
  17829. } else if (has$2(menuItems, item.toLowerCase())) {
  17830. return acc.concat([menuItems[item.toLowerCase()]]);
  17831. } else {
  17832. return acc;
  17833. }
  17834. } else {
  17835. return acc.concat([item]);
  17836. }
  17837. }, []);
  17838. if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
  17839. realItems.pop();
  17840. }
  17841. return realItems;
  17842. };
  17843. var getFromExpandingItem = function (item, menuItems) {
  17844. var submenuItems = item.getSubmenuItems();
  17845. var rest = expand(submenuItems, menuItems);
  17846. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  17847. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  17848. return {
  17849. item: item,
  17850. menus: newMenus,
  17851. expansions: newExpansions
  17852. };
  17853. };
  17854. var getFromItem = function (item, menuItems) {
  17855. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  17856. item: item,
  17857. menus: {},
  17858. expansions: {}
  17859. };
  17860. };
  17861. var generateValueIfRequired = function (item) {
  17862. if (isSeparator$1(item)) {
  17863. return item;
  17864. } else {
  17865. var itemValue = get$e(item, 'value').getOrThunk(function () {
  17866. return generate$6('generated-menu-item');
  17867. });
  17868. return deepMerge({ value: itemValue }, item);
  17869. }
  17870. };
  17871. var expand = function (items, menuItems) {
  17872. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  17873. return foldr(realItems, function (acc, item) {
  17874. var itemWithValue = generateValueIfRequired(item);
  17875. var newData = getFromItem(itemWithValue, menuItems);
  17876. return {
  17877. menus: deepMerge(acc.menus, newData.menus),
  17878. items: [newData.item].concat(acc.items),
  17879. expansions: deepMerge(acc.expansions, newData.expansions)
  17880. };
  17881. }, {
  17882. menus: {},
  17883. expansions: {},
  17884. items: []
  17885. });
  17886. };
  17887. var build = function (items, itemResponse, backstage, isHorizontalMenu) {
  17888. var primary = generate$6('primary-menu');
  17889. var data = expand(items, backstage.shared.providers.menuItems());
  17890. if (data.items.length === 0) {
  17891. return Optional.none();
  17892. }
  17893. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  17894. var submenus = map(data.menus, function (menuItems, menuName) {
  17895. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  17896. });
  17897. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  17898. return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
  17899. };
  17900. var getMenuButtonApi = function (component) {
  17901. return {
  17902. isDisabled: function () {
  17903. return Disabling.isDisabled(component);
  17904. },
  17905. setDisabled: function (state) {
  17906. return Disabling.set(component, state);
  17907. },
  17908. setActive: function (state) {
  17909. var elm = component.element;
  17910. if (state) {
  17911. add$2(elm, 'tox-tbtn--enabled');
  17912. set$7(elm, 'aria-pressed', true);
  17913. } else {
  17914. remove$3(elm, 'tox-tbtn--enabled');
  17915. remove$6(elm, 'aria-pressed');
  17916. }
  17917. },
  17918. isActive: function () {
  17919. return has(component.element, 'tox-tbtn--enabled');
  17920. }
  17921. };
  17922. };
  17923. var renderMenuButton = function (spec, prefix, backstage, role) {
  17924. return renderCommonDropdown({
  17925. text: spec.text,
  17926. icon: spec.icon,
  17927. tooltip: spec.tooltip,
  17928. role: role,
  17929. fetch: function (_comp, callback) {
  17930. spec.fetch(function (items) {
  17931. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  17932. });
  17933. },
  17934. onSetup: spec.onSetup,
  17935. getApi: getMenuButtonApi,
  17936. columns: 1,
  17937. presets: 'normal',
  17938. classes: [],
  17939. dropdownBehaviours: [Tabstopping.config({})]
  17940. }, prefix, backstage.shared);
  17941. };
  17942. var getFetch = function (items, getButton, backstage) {
  17943. var getMenuItemAction = function (item) {
  17944. return function (api) {
  17945. var newValue = !api.isActive();
  17946. api.setActive(newValue);
  17947. item.storage.set(newValue);
  17948. backstage.shared.getSink().each(function (sink) {
  17949. getButton().getOpt(sink).each(function (orig) {
  17950. focus$3(orig.element);
  17951. emitWith(orig, formActionEvent, {
  17952. name: item.name,
  17953. value: item.storage.get()
  17954. });
  17955. });
  17956. });
  17957. };
  17958. };
  17959. var getMenuItemSetup = function (item) {
  17960. return function (api) {
  17961. api.setActive(item.storage.get());
  17962. };
  17963. };
  17964. return function (success) {
  17965. success(map$2(items, function (item) {
  17966. var text = item.text.fold(function () {
  17967. return {};
  17968. }, function (text) {
  17969. return { text: text };
  17970. });
  17971. return __assign(__assign({
  17972. type: item.type,
  17973. active: false
  17974. }, text), {
  17975. onAction: getMenuItemAction(item),
  17976. onSetup: getMenuItemSetup(item)
  17977. });
  17978. }));
  17979. };
  17980. };
  17981. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) {
  17982. if (extraBehaviours === void 0) {
  17983. extraBehaviours = [];
  17984. }
  17985. var action = actionOpt.fold(function () {
  17986. return {};
  17987. }, function (action) {
  17988. return { action: action };
  17989. });
  17990. var common = __assign({
  17991. buttonBehaviours: derive$1([
  17992. DisablingConfigs.button(function () {
  17993. return spec.disabled || providersBackstage.isDisabled();
  17994. }),
  17995. receivingConfig(),
  17996. Tabstopping.config({}),
  17997. config('button press', [
  17998. preventDefault('click'),
  17999. preventDefault('mousedown')
  18000. ])
  18001. ].concat(extraBehaviours)),
  18002. eventOrder: {
  18003. click: [
  18004. 'button press',
  18005. 'alloy.base.behaviour'
  18006. ],
  18007. mousedown: [
  18008. 'button press',
  18009. 'alloy.base.behaviour'
  18010. ]
  18011. }
  18012. }, action);
  18013. var domFinal = deepMerge(common, { dom: dom });
  18014. return deepMerge(domFinal, { components: components });
  18015. };
  18016. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  18017. if (extraBehaviours === void 0) {
  18018. extraBehaviours = [];
  18019. }
  18020. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  18021. return {
  18022. 'aria-label': providersBackstage.translate(tooltip),
  18023. 'title': providersBackstage.translate(tooltip)
  18024. };
  18025. }).getOr({});
  18026. var dom = {
  18027. tag: 'button',
  18028. classes: ['tox-tbtn'],
  18029. attributes: tooltipAttributes
  18030. };
  18031. var icon = spec.icon.map(function (iconName) {
  18032. return renderIconFromPack(iconName, providersBackstage.icons);
  18033. });
  18034. var components = componentRenderPipeline([icon]);
  18035. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  18036. };
  18037. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  18038. if (extraBehaviours === void 0) {
  18039. extraBehaviours = [];
  18040. }
  18041. var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
  18042. return Button.sketch(iconButtonSpec);
  18043. };
  18044. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  18045. if (extraBehaviours === void 0) {
  18046. extraBehaviours = [];
  18047. }
  18048. if (extraClasses === void 0) {
  18049. extraClasses = [];
  18050. }
  18051. var translatedText = providersBackstage.translate(spec.text);
  18052. var icon = spec.icon ? spec.icon.map(function (iconName) {
  18053. return renderIconFromPack(iconName, providersBackstage.icons);
  18054. }) : Optional.none();
  18055. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  18056. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  18057. var classes = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [
  18058. 'tox-button',
  18059. 'tox-button--secondary'
  18060. ] : ['tox-button']), icon.isSome() ? ['tox-button--icon'] : []), spec.borderless ? ['tox-button--naked'] : []), extraClasses);
  18061. var dom = __assign(__assign({
  18062. tag: 'button',
  18063. classes: classes
  18064. }, innerHtml), { attributes: { title: translatedText } });
  18065. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  18066. };
  18067. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  18068. if (extraBehaviours === void 0) {
  18069. extraBehaviours = [];
  18070. }
  18071. if (extraClasses === void 0) {
  18072. extraClasses = [];
  18073. }
  18074. var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
  18075. return Button.sketch(buttonSpec);
  18076. };
  18077. var getAction = function (name, buttonType) {
  18078. return function (comp) {
  18079. if (buttonType === 'custom') {
  18080. emitWith(comp, formActionEvent, {
  18081. name: name,
  18082. value: {}
  18083. });
  18084. } else if (buttonType === 'submit') {
  18085. emit(comp, formSubmitEvent);
  18086. } else if (buttonType === 'cancel') {
  18087. emit(comp, formCancelEvent);
  18088. } else {
  18089. console.error('Unknown button type: ', buttonType);
  18090. }
  18091. };
  18092. };
  18093. var isMenuFooterButtonSpec = function (spec, buttonType) {
  18094. return buttonType === 'menu';
  18095. };
  18096. var isNormalFooterButtonSpec = function (spec, buttonType) {
  18097. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  18098. };
  18099. var renderFooterButton = function (spec, buttonType, backstage) {
  18100. if (isMenuFooterButtonSpec(spec, buttonType)) {
  18101. var getButton = function () {
  18102. return memButton_1;
  18103. };
  18104. var menuButtonSpec = spec;
  18105. var fixedSpec = __assign(__assign({}, spec), {
  18106. onSetup: function (api) {
  18107. api.setDisabled(spec.disabled);
  18108. return noop;
  18109. },
  18110. fetch: getFetch(menuButtonSpec.items, getButton, backstage)
  18111. });
  18112. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none()));
  18113. return memButton_1.asSpec();
  18114. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  18115. var action = getAction(spec.name, buttonType);
  18116. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  18117. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  18118. } else {
  18119. console.error('Unknown footer button type: ', buttonType);
  18120. }
  18121. };
  18122. var renderDialogButton = function (spec, providersBackstage) {
  18123. var action = getAction(spec.name, 'custom');
  18124. return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
  18125. RepresentingConfigs.memory(''),
  18126. ComposingConfigs.self()
  18127. ]))));
  18128. };
  18129. var schema$h = constant$1([
  18130. defaulted('field1Name', 'field1'),
  18131. defaulted('field2Name', 'field2'),
  18132. onStrictHandler('onLockedChange'),
  18133. markers$1(['lockClass']),
  18134. defaulted('locked', false),
  18135. SketchBehaviours.field('coupledFieldBehaviours', [
  18136. Composing,
  18137. Representing
  18138. ])
  18139. ]);
  18140. var getField = function (comp, detail, partName) {
  18141. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  18142. };
  18143. var coupledPart = function (selfName, otherName) {
  18144. return required({
  18145. factory: FormField,
  18146. name: selfName,
  18147. overrides: function (detail) {
  18148. return {
  18149. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run$1(input(), function (me) {
  18150. getField(me, detail, otherName).each(function (other) {
  18151. getPart(me, detail, 'lock').each(function (lock) {
  18152. if (Toggling.isOn(lock)) {
  18153. detail.onLockedChange(me, other, lock);
  18154. }
  18155. });
  18156. });
  18157. })])])
  18158. };
  18159. }
  18160. });
  18161. };
  18162. var parts$c = constant$1([
  18163. coupledPart('field1', 'field2'),
  18164. coupledPart('field2', 'field1'),
  18165. required({
  18166. factory: Button,
  18167. schema: [required$1('dom')],
  18168. name: 'lock',
  18169. overrides: function (detail) {
  18170. return {
  18171. buttonBehaviours: derive$1([Toggling.config({
  18172. selected: detail.locked,
  18173. toggleClass: detail.markers.lockClass,
  18174. aria: { mode: 'pressed' }
  18175. })])
  18176. };
  18177. }
  18178. })
  18179. ]);
  18180. var factory$f = function (detail, components, _spec, _externals) {
  18181. return {
  18182. uid: detail.uid,
  18183. dom: detail.dom,
  18184. components: components,
  18185. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  18186. Composing.config({ find: Optional.some }),
  18187. Representing.config({
  18188. store: {
  18189. mode: 'manual',
  18190. getValue: function (comp) {
  18191. var _a;
  18192. var parts = getPartsOrDie(comp, detail, [
  18193. 'field1',
  18194. 'field2'
  18195. ]);
  18196. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  18197. },
  18198. setValue: function (comp, value) {
  18199. var parts = getPartsOrDie(comp, detail, [
  18200. 'field1',
  18201. 'field2'
  18202. ]);
  18203. if (hasNonNullableKey(value, detail.field1Name)) {
  18204. Representing.setValue(parts.field1(), value[detail.field1Name]);
  18205. }
  18206. if (hasNonNullableKey(value, detail.field2Name)) {
  18207. Representing.setValue(parts.field2(), value[detail.field2Name]);
  18208. }
  18209. }
  18210. }
  18211. })
  18212. ]),
  18213. apis: {
  18214. getField1: function (component) {
  18215. return getPart(component, detail, 'field1');
  18216. },
  18217. getField2: function (component) {
  18218. return getPart(component, detail, 'field2');
  18219. },
  18220. getLock: function (component) {
  18221. return getPart(component, detail, 'lock');
  18222. }
  18223. }
  18224. };
  18225. };
  18226. var FormCoupledInputs = composite({
  18227. name: 'FormCoupledInputs',
  18228. configFields: schema$h(),
  18229. partFields: parts$c(),
  18230. factory: factory$f,
  18231. apis: {
  18232. getField1: function (apis, component) {
  18233. return apis.getField1(component);
  18234. },
  18235. getField2: function (apis, component) {
  18236. return apis.getField2(component);
  18237. },
  18238. getLock: function (apis, component) {
  18239. return apis.getLock(component);
  18240. }
  18241. }
  18242. });
  18243. var formatSize = function (size) {
  18244. var unitDec = {
  18245. '': 0,
  18246. 'px': 0,
  18247. 'pt': 1,
  18248. 'mm': 1,
  18249. 'pc': 2,
  18250. 'ex': 2,
  18251. 'em': 2,
  18252. 'ch': 2,
  18253. 'rem': 2,
  18254. 'cm': 3,
  18255. 'in': 4,
  18256. '%': 4
  18257. };
  18258. var maxDecimal = function (unit) {
  18259. return unit in unitDec ? unitDec[unit] : 1;
  18260. };
  18261. var numText = size.value.toFixed(maxDecimal(size.unit));
  18262. if (numText.indexOf('.') !== -1) {
  18263. numText = numText.replace(/\.?0*$/, '');
  18264. }
  18265. return numText + size.unit;
  18266. };
  18267. var parseSize = function (sizeText) {
  18268. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  18269. var match = numPattern.exec(sizeText);
  18270. if (match !== null) {
  18271. var value = parseFloat(match[1]);
  18272. var unit = match[2];
  18273. return Result.value({
  18274. value: value,
  18275. unit: unit
  18276. });
  18277. } else {
  18278. return Result.error(sizeText);
  18279. }
  18280. };
  18281. var convertUnit = function (size, unit) {
  18282. var inInch = {
  18283. '': 96,
  18284. 'px': 96,
  18285. 'pt': 72,
  18286. 'cm': 2.54,
  18287. 'pc': 12,
  18288. 'mm': 25.4,
  18289. 'in': 1
  18290. };
  18291. var supported = function (u) {
  18292. return has$2(inInch, u);
  18293. };
  18294. if (size.unit === unit) {
  18295. return Optional.some(size.value);
  18296. } else if (supported(size.unit) && supported(unit)) {
  18297. if (inInch[size.unit] === inInch[unit]) {
  18298. return Optional.some(size.value);
  18299. } else {
  18300. return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
  18301. }
  18302. } else {
  18303. return Optional.none();
  18304. }
  18305. };
  18306. var noSizeConversion = function (_input) {
  18307. return Optional.none();
  18308. };
  18309. var ratioSizeConversion = function (scale, unit) {
  18310. return function (size) {
  18311. return convertUnit(size, unit).map(function (value) {
  18312. return {
  18313. value: value * scale,
  18314. unit: unit
  18315. };
  18316. });
  18317. };
  18318. };
  18319. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  18320. var cValue = parseSize(currentFieldText).toOptional();
  18321. var oValue = parseSize(otherFieldText).toOptional();
  18322. return lift2(cValue, oValue, function (cSize, oSize) {
  18323. return convertUnit(cSize, oSize.unit).map(function (val) {
  18324. return oSize.value / val;
  18325. }).map(function (r) {
  18326. return ratioSizeConversion(r, oSize.unit);
  18327. }).getOr(noSizeConversion);
  18328. }).getOr(noSizeConversion);
  18329. };
  18330. var renderSizeInput = function (spec, providersBackstage) {
  18331. var converter = noSizeConversion;
  18332. var ratioEvent = generate$6('ratio-event');
  18333. var makeIcon = function (iconName) {
  18334. return render$3(iconName, {
  18335. tag: 'span',
  18336. classes: [
  18337. 'tox-icon',
  18338. 'tox-lock-icon__' + iconName
  18339. ]
  18340. }, providersBackstage.icons);
  18341. };
  18342. var pLock = FormCoupledInputs.parts.lock({
  18343. dom: {
  18344. tag: 'button',
  18345. classes: [
  18346. 'tox-lock',
  18347. 'tox-button',
  18348. 'tox-button--naked',
  18349. 'tox-button--icon'
  18350. ],
  18351. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  18352. },
  18353. components: [
  18354. makeIcon('lock'),
  18355. makeIcon('unlock')
  18356. ],
  18357. buttonBehaviours: derive$1([
  18358. Disabling.config({
  18359. disabled: function () {
  18360. return spec.disabled || providersBackstage.isDisabled();
  18361. }
  18362. }),
  18363. receivingConfig(),
  18364. Tabstopping.config({})
  18365. ])
  18366. });
  18367. var formGroup = function (components) {
  18368. return {
  18369. dom: {
  18370. tag: 'div',
  18371. classes: ['tox-form__group']
  18372. },
  18373. components: components
  18374. };
  18375. };
  18376. var getFieldPart = function (isField1) {
  18377. return FormField.parts.field({
  18378. factory: Input,
  18379. inputClasses: ['tox-textfield'],
  18380. inputBehaviours: derive$1([
  18381. Disabling.config({
  18382. disabled: function () {
  18383. return spec.disabled || providersBackstage.isDisabled();
  18384. }
  18385. }),
  18386. receivingConfig(),
  18387. Tabstopping.config({}),
  18388. config('size-input-events', [
  18389. run$1(focusin(), function (component, _simulatedEvent) {
  18390. emitWith(component, ratioEvent, { isField1: isField1 });
  18391. }),
  18392. run$1(change(), function (component, _simulatedEvent) {
  18393. emitWith(component, formChangeEvent, { name: spec.name });
  18394. })
  18395. ])
  18396. ]),
  18397. selectOnFocus: false
  18398. });
  18399. };
  18400. var getLabel = function (label) {
  18401. return {
  18402. dom: {
  18403. tag: 'label',
  18404. classes: ['tox-label'],
  18405. innerHtml: providersBackstage.translate(label)
  18406. }
  18407. };
  18408. };
  18409. var widthField = FormCoupledInputs.parts.field1(formGroup([
  18410. FormField.parts.label(getLabel('Width')),
  18411. getFieldPart(true)
  18412. ]));
  18413. var heightField = FormCoupledInputs.parts.field2(formGroup([
  18414. FormField.parts.label(getLabel('Height')),
  18415. getFieldPart(false)
  18416. ]));
  18417. return FormCoupledInputs.sketch({
  18418. dom: {
  18419. tag: 'div',
  18420. classes: ['tox-form__group']
  18421. },
  18422. components: [{
  18423. dom: {
  18424. tag: 'div',
  18425. classes: ['tox-form__controls-h-stack']
  18426. },
  18427. components: [
  18428. widthField,
  18429. heightField,
  18430. formGroup([
  18431. getLabel('&nbsp;'),
  18432. pLock
  18433. ])
  18434. ]
  18435. }],
  18436. field1Name: 'width',
  18437. field2Name: 'height',
  18438. locked: true,
  18439. markers: { lockClass: 'tox-locked' },
  18440. onLockedChange: function (current, other, _lock) {
  18441. parseSize(Representing.getValue(current)).each(function (size) {
  18442. converter(size).each(function (newSize) {
  18443. Representing.setValue(other, formatSize(newSize));
  18444. });
  18445. });
  18446. },
  18447. coupledFieldBehaviours: derive$1([
  18448. Disabling.config({
  18449. disabled: function () {
  18450. return spec.disabled || providersBackstage.isDisabled();
  18451. },
  18452. onDisabled: function (comp) {
  18453. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  18454. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  18455. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  18456. },
  18457. onEnabled: function (comp) {
  18458. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  18459. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  18460. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  18461. }
  18462. }),
  18463. receivingConfig(),
  18464. config('size-input-events2', [run$1(ratioEvent, function (component, simulatedEvent) {
  18465. var isField1 = simulatedEvent.event.isField1;
  18466. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  18467. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  18468. var value1 = optCurrent.map(Representing.getValue).getOr('');
  18469. var value2 = optOther.map(Representing.getValue).getOr('');
  18470. converter = makeRatioConverter(value1, value2);
  18471. })])
  18472. ])
  18473. });
  18474. };
  18475. var undo = constant$1(generate$6('undo'));
  18476. var redo = constant$1(generate$6('redo'));
  18477. var zoom = constant$1(generate$6('zoom'));
  18478. var back = constant$1(generate$6('back'));
  18479. var apply = constant$1(generate$6('apply'));
  18480. var swap = constant$1(generate$6('swap'));
  18481. var transform$1 = constant$1(generate$6('transform'));
  18482. var tempTransform = constant$1(generate$6('temp-transform'));
  18483. var transformApply = constant$1(generate$6('transform-apply'));
  18484. var internal = {
  18485. undo: undo,
  18486. redo: redo,
  18487. zoom: zoom,
  18488. back: back,
  18489. apply: apply,
  18490. swap: swap,
  18491. transform: transform$1,
  18492. tempTransform: tempTransform,
  18493. transformApply: transformApply
  18494. };
  18495. var saveState = constant$1('save-state');
  18496. var disable = constant$1('disable');
  18497. var enable = constant$1('enable');
  18498. var external = {
  18499. formActionEvent: formActionEvent,
  18500. saveState: saveState,
  18501. disable: disable,
  18502. enable: enable
  18503. };
  18504. var renderEditPanel = function (imagePanel, providersBackstage) {
  18505. var createButton = function (text, action, disabled, primary) {
  18506. return record(renderButton({
  18507. name: text,
  18508. text: text,
  18509. disabled: disabled,
  18510. primary: primary,
  18511. icon: Optional.none(),
  18512. borderless: false
  18513. }, action, providersBackstage));
  18514. };
  18515. var createIconButton = function (icon, tooltip, action, disabled) {
  18516. return record(renderIconButton({
  18517. name: icon,
  18518. icon: Optional.some(icon),
  18519. tooltip: Optional.some(tooltip),
  18520. disabled: disabled,
  18521. primary: false,
  18522. borderless: false
  18523. }, action, providersBackstage));
  18524. };
  18525. var disableAllComponents = function (comps, eventcomp) {
  18526. comps.map(function (mem) {
  18527. var component = mem.get(eventcomp);
  18528. if (component.hasConfigured(Disabling)) {
  18529. Disabling.disable(component);
  18530. }
  18531. });
  18532. };
  18533. var enableAllComponents = function (comps, eventcomp) {
  18534. comps.map(function (mem) {
  18535. var component = mem.get(eventcomp);
  18536. if (component.hasConfigured(Disabling)) {
  18537. Disabling.enable(component);
  18538. }
  18539. });
  18540. };
  18541. var panelDom = {
  18542. tag: 'div',
  18543. classes: [
  18544. 'tox-image-tools__toolbar',
  18545. 'tox-image-tools-edit-panel'
  18546. ]
  18547. };
  18548. var noop$1 = noop;
  18549. var emit$1 = function (comp, event, data) {
  18550. emitWith(comp, event, data);
  18551. };
  18552. var emitDisable = function (component) {
  18553. return emit(component, external.disable());
  18554. };
  18555. var emitEnable = function (component) {
  18556. return emit(component, external.enable());
  18557. };
  18558. var emitTransform = function (comp, transform) {
  18559. emitDisable(comp);
  18560. emit$1(comp, internal.transform(), { transform: transform });
  18561. emitEnable(comp);
  18562. };
  18563. var emitTempTransform = function (comp, transform) {
  18564. emitDisable(comp);
  18565. emit$1(comp, internal.tempTransform(), { transform: transform });
  18566. emitEnable(comp);
  18567. };
  18568. var getBackSwap = function (anyInSystem) {
  18569. return function () {
  18570. memContainer.getOpt(anyInSystem).each(function (container) {
  18571. Replacing.set(container, [ButtonPanel]);
  18572. });
  18573. };
  18574. };
  18575. var emitTransformApply = function (comp, transform) {
  18576. emitDisable(comp);
  18577. emit$1(comp, internal.transformApply(), {
  18578. transform: transform,
  18579. swap: getBackSwap(comp)
  18580. });
  18581. emitEnable(comp);
  18582. };
  18583. var createBackButton = function () {
  18584. return createButton('Back', function (button) {
  18585. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  18586. }, false, false);
  18587. };
  18588. var createSpacer = function () {
  18589. return record({
  18590. dom: {
  18591. tag: 'div',
  18592. classes: ['tox-spacer']
  18593. },
  18594. behaviours: derive$1([Disabling.config({})])
  18595. });
  18596. };
  18597. var createApplyButton = function () {
  18598. return createButton('Apply', function (button) {
  18599. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  18600. }, true, true);
  18601. };
  18602. var makeCropTransform = function () {
  18603. return function (ir) {
  18604. var rect = imagePanel.getRect();
  18605. return crop(ir, rect.x, rect.y, rect.w, rect.h);
  18606. };
  18607. };
  18608. var cropPanelComponents = [
  18609. createBackButton(),
  18610. createSpacer(),
  18611. createButton('Apply', function (button) {
  18612. var transform = makeCropTransform();
  18613. emitTransformApply(button, transform);
  18614. imagePanel.hideCrop();
  18615. }, false, true)
  18616. ];
  18617. var CropPanel = Container.sketch({
  18618. dom: panelDom,
  18619. components: cropPanelComponents.map(function (mem) {
  18620. return mem.asSpec();
  18621. }),
  18622. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  18623. run$1(external.disable(), function (comp, _se) {
  18624. disableAllComponents(cropPanelComponents, comp);
  18625. }),
  18626. run$1(external.enable(), function (comp, _se) {
  18627. enableAllComponents(cropPanelComponents, comp);
  18628. })
  18629. ])])
  18630. });
  18631. var memSize = record(renderSizeInput({
  18632. name: 'size',
  18633. label: Optional.none(),
  18634. constrain: true,
  18635. disabled: false
  18636. }, providersBackstage));
  18637. var makeResizeTransform = function (width, height) {
  18638. return function (ir) {
  18639. return resize$1(ir, width, height);
  18640. };
  18641. };
  18642. var resizePanelComponents = [
  18643. createBackButton(),
  18644. createSpacer(),
  18645. memSize,
  18646. createSpacer(),
  18647. createButton('Apply', function (button) {
  18648. memSize.getOpt(button).each(function (sizeInput) {
  18649. var value = Representing.getValue(sizeInput);
  18650. var width = parseInt(value.width, 10);
  18651. var height = parseInt(value.height, 10);
  18652. var transform = makeResizeTransform(width, height);
  18653. emitTransformApply(button, transform);
  18654. });
  18655. }, false, true)
  18656. ];
  18657. var ResizePanel = Container.sketch({
  18658. dom: panelDom,
  18659. components: resizePanelComponents.map(function (mem) {
  18660. return mem.asSpec();
  18661. }),
  18662. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  18663. run$1(external.disable(), function (comp, _se) {
  18664. disableAllComponents(resizePanelComponents, comp);
  18665. }),
  18666. run$1(external.enable(), function (comp, _se) {
  18667. enableAllComponents(resizePanelComponents, comp);
  18668. })
  18669. ])])
  18670. });
  18671. var makeValueTransform = function (transform, value) {
  18672. return function (ir) {
  18673. return transform(ir, value);
  18674. };
  18675. };
  18676. var horizontalFlip = makeValueTransform(flip, 'h');
  18677. var verticalFlip = makeValueTransform(flip, 'v');
  18678. var counterclockwiseRotate = makeValueTransform(rotate, -90);
  18679. var clockwiseRotate = makeValueTransform(rotate, 90);
  18680. var flipRotateOnAction = function (comp, operation) {
  18681. emitTempTransform(comp, operation);
  18682. };
  18683. var flipRotateComponents = [
  18684. createBackButton(),
  18685. createSpacer(),
  18686. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  18687. flipRotateOnAction(button, horizontalFlip);
  18688. }, false),
  18689. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  18690. flipRotateOnAction(button, verticalFlip);
  18691. }, false),
  18692. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  18693. flipRotateOnAction(button, counterclockwiseRotate);
  18694. }, false),
  18695. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  18696. flipRotateOnAction(button, clockwiseRotate);
  18697. }, false),
  18698. createSpacer(),
  18699. createApplyButton()
  18700. ];
  18701. var FlipRotatePanel = Container.sketch({
  18702. dom: panelDom,
  18703. components: flipRotateComponents.map(function (mem) {
  18704. return mem.asSpec();
  18705. }),
  18706. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  18707. run$1(external.disable(), function (comp, _se) {
  18708. disableAllComponents(flipRotateComponents, comp);
  18709. }),
  18710. run$1(external.enable(), function (comp, _se) {
  18711. enableAllComponents(flipRotateComponents, comp);
  18712. })
  18713. ])])
  18714. });
  18715. var makeSlider = function (label, onChoose, min, value, max) {
  18716. var labelPart = Slider.parts.label({
  18717. dom: {
  18718. tag: 'label',
  18719. classes: ['tox-label'],
  18720. innerHtml: providersBackstage.translate(label)
  18721. }
  18722. });
  18723. var spectrum = Slider.parts.spectrum({
  18724. dom: {
  18725. tag: 'div',
  18726. classes: ['tox-slider__rail'],
  18727. attributes: { role: 'presentation' }
  18728. }
  18729. });
  18730. var thumb = Slider.parts.thumb({
  18731. dom: {
  18732. tag: 'div',
  18733. classes: ['tox-slider__handle'],
  18734. attributes: { role: 'presentation' }
  18735. }
  18736. });
  18737. return record(Slider.sketch({
  18738. dom: {
  18739. tag: 'div',
  18740. classes: ['tox-slider'],
  18741. attributes: { role: 'presentation' }
  18742. },
  18743. model: {
  18744. mode: 'x',
  18745. minX: min,
  18746. maxX: max,
  18747. getInitialValue: constant$1({ x: value })
  18748. },
  18749. components: [
  18750. labelPart,
  18751. spectrum,
  18752. thumb
  18753. ],
  18754. sliderBehaviours: derive$1([Focusing.config({})]),
  18755. onChoose: onChoose
  18756. }));
  18757. };
  18758. var makeVariableSlider = function (label, transform, min, value, max) {
  18759. var onChoose = function (slider, _thumb, value) {
  18760. var valTransform = makeValueTransform(transform, value.x / 100);
  18761. emitTransform(slider, valTransform);
  18762. };
  18763. return makeSlider(label, onChoose, min, value, max);
  18764. };
  18765. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  18766. return [
  18767. createBackButton(),
  18768. makeVariableSlider(label, transform, min, value, max),
  18769. createApplyButton()
  18770. ];
  18771. };
  18772. var createVariableFilterPanel = function (label, transform, min, value, max) {
  18773. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  18774. return Container.sketch({
  18775. dom: panelDom,
  18776. components: filterPanelComponents.map(function (mem) {
  18777. return mem.asSpec();
  18778. }),
  18779. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  18780. run$1(external.disable(), function (comp, _se) {
  18781. disableAllComponents(filterPanelComponents, comp);
  18782. }),
  18783. run$1(external.enable(), function (comp, _se) {
  18784. enableAllComponents(filterPanelComponents, comp);
  18785. })
  18786. ])])
  18787. });
  18788. };
  18789. var filterPanelComponents = [
  18790. createBackButton(),
  18791. createSpacer(),
  18792. createApplyButton()
  18793. ];
  18794. var FilterPanel = Container.sketch({
  18795. dom: panelDom,
  18796. components: filterPanelComponents.map(function (mem) {
  18797. return mem.asSpec();
  18798. })
  18799. });
  18800. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness, -100, 0, 100);
  18801. var ContrastPanel = createVariableFilterPanel('Contrast', contrast, -100, 0, 100);
  18802. var GammaPanel = createVariableFilterPanel('Gamma', gamma, -100, 0, 100);
  18803. var makeColorTransform = function (red, green, blue) {
  18804. return function (ir) {
  18805. return colorize(ir, red, green, blue);
  18806. };
  18807. };
  18808. var makeColorSlider = function (label) {
  18809. var onChoose = function (slider, _thumb, _value) {
  18810. var redOpt = memRed.getOpt(slider);
  18811. var blueOpt = memBlue.getOpt(slider);
  18812. var greenOpt = memGreen.getOpt(slider);
  18813. redOpt.each(function (red) {
  18814. blueOpt.each(function (blue) {
  18815. greenOpt.each(function (green) {
  18816. var r = Representing.getValue(red).x / 100;
  18817. var g = Representing.getValue(green).x / 100;
  18818. var b = Representing.getValue(blue).x / 100;
  18819. var transform = makeColorTransform(r, g, b);
  18820. emitTransform(slider, transform);
  18821. });
  18822. });
  18823. });
  18824. };
  18825. return makeSlider(label, onChoose, 0, 100, 200);
  18826. };
  18827. var memRed = makeColorSlider('R');
  18828. var memGreen = makeColorSlider('G');
  18829. var memBlue = makeColorSlider('B');
  18830. var colorizePanelComponents = [
  18831. createBackButton(),
  18832. memRed,
  18833. memGreen,
  18834. memBlue,
  18835. createApplyButton()
  18836. ];
  18837. var ColorizePanel = Container.sketch({
  18838. dom: panelDom,
  18839. components: colorizePanelComponents.map(function (mem) {
  18840. return mem.asSpec();
  18841. })
  18842. });
  18843. var getTransformPanelEvent = function (panel, transform, update) {
  18844. return function (button) {
  18845. var swap = function () {
  18846. memContainer.getOpt(button).each(function (container) {
  18847. Replacing.set(container, [panel]);
  18848. update(container);
  18849. });
  18850. };
  18851. emit$1(button, internal.swap(), {
  18852. transform: transform,
  18853. swap: swap
  18854. });
  18855. };
  18856. };
  18857. var cropPanelUpdate = function (_anyInSystem) {
  18858. imagePanel.showCrop();
  18859. };
  18860. var resizePanelUpdate = function (anyInSystem) {
  18861. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  18862. var measurements = imagePanel.getMeasurements();
  18863. var width = measurements.width;
  18864. var height = measurements.height;
  18865. Representing.setValue(sizeInput, {
  18866. width: width,
  18867. height: height
  18868. });
  18869. });
  18870. };
  18871. var sharpenTransform = Optional.some(sharpen);
  18872. var invertTransform = Optional.some(invert);
  18873. var buttonPanelComponents = [
  18874. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
  18875. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
  18876. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
  18877. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
  18878. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  18879. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
  18880. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
  18881. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
  18882. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  18883. ];
  18884. var ButtonPanel = Container.sketch({
  18885. dom: panelDom,
  18886. components: buttonPanelComponents.map(function (mem) {
  18887. return mem.asSpec();
  18888. })
  18889. });
  18890. var container = Container.sketch({
  18891. dom: { tag: 'div' },
  18892. components: [ButtonPanel],
  18893. containerBehaviours: derive$1([Replacing.config({})])
  18894. });
  18895. var memContainer = record(container);
  18896. var getApplyButton = function (anyInSystem) {
  18897. return memContainer.getOpt(anyInSystem).map(function (container) {
  18898. var panel = container.components()[0];
  18899. return panel.components()[panel.components().length - 1];
  18900. });
  18901. };
  18902. return {
  18903. memContainer: memContainer,
  18904. getApplyButton: getApplyButton
  18905. };
  18906. };
  18907. var global$5 = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  18908. var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
  18909. var global$3 = tinymce.util.Tools.resolve('tinymce.util.Observable');
  18910. var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK');
  18911. var getDocumentSize = function (doc) {
  18912. var max = Math.max;
  18913. var documentElement = doc.documentElement;
  18914. var body = doc.body;
  18915. var scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  18916. var clientWidth = max(documentElement.clientWidth, body.clientWidth);
  18917. var offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  18918. var scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  18919. var clientHeight = max(documentElement.clientHeight, body.clientHeight);
  18920. var offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  18921. return {
  18922. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  18923. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  18924. };
  18925. };
  18926. var updateWithTouchData = function (e) {
  18927. var keys, i;
  18928. if (e.changedTouches) {
  18929. keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  18930. for (i = 0; i < keys.length; i++) {
  18931. e[keys[i]] = e.changedTouches[0][keys[i]];
  18932. }
  18933. }
  18934. };
  18935. function DragHelper (id, settings) {
  18936. var $eventOverlay;
  18937. var doc = settings.document || document;
  18938. var downButton;
  18939. var startX, startY;
  18940. var handleElement = doc.getElementById(settings.handle || id);
  18941. var start = function (e) {
  18942. var docSize = getDocumentSize(doc);
  18943. var cursor;
  18944. updateWithTouchData(e);
  18945. e.preventDefault();
  18946. downButton = e.button;
  18947. var handleElm = handleElement;
  18948. startX = e.screenX;
  18949. startY = e.screenY;
  18950. if (window.getComputedStyle) {
  18951. cursor = window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
  18952. } else {
  18953. cursor = handleElm.runtimeStyle.cursor;
  18954. }
  18955. $eventOverlay = global$4('<div></div>').css({
  18956. position: 'absolute',
  18957. top: 0,
  18958. left: 0,
  18959. width: docSize.width,
  18960. height: docSize.height,
  18961. zIndex: 2147483647,
  18962. opacity: 0.0001,
  18963. cursor: cursor
  18964. }).appendTo(doc.body);
  18965. global$4(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
  18966. settings.start(e);
  18967. };
  18968. var drag = function (e) {
  18969. updateWithTouchData(e);
  18970. if (e.button !== downButton) {
  18971. return stop(e);
  18972. }
  18973. e.deltaX = e.screenX - startX;
  18974. e.deltaY = e.screenY - startY;
  18975. e.preventDefault();
  18976. settings.drag(e);
  18977. };
  18978. var stop = function (e) {
  18979. updateWithTouchData(e);
  18980. global$4(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
  18981. $eventOverlay.remove();
  18982. if (settings.stop) {
  18983. settings.stop(e);
  18984. }
  18985. };
  18986. var destroy = function () {
  18987. global$4(handleElement).off();
  18988. };
  18989. global$4(handleElement).on('mousedown touchstart', start);
  18990. return { destroy: destroy };
  18991. }
  18992. var count = 0;
  18993. var create$1 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18994. var dragHelpers;
  18995. var prefix = 'tox-';
  18996. var id = prefix + 'crid-' + count++;
  18997. var handles = [
  18998. {
  18999. name: 'move',
  19000. xMul: 0,
  19001. yMul: 0,
  19002. deltaX: 1,
  19003. deltaY: 1,
  19004. deltaW: 0,
  19005. deltaH: 0,
  19006. label: 'Crop Mask'
  19007. },
  19008. {
  19009. name: 'nw',
  19010. xMul: 0,
  19011. yMul: 0,
  19012. deltaX: 1,
  19013. deltaY: 1,
  19014. deltaW: -1,
  19015. deltaH: -1,
  19016. label: 'Top Left Crop Handle'
  19017. },
  19018. {
  19019. name: 'ne',
  19020. xMul: 1,
  19021. yMul: 0,
  19022. deltaX: 0,
  19023. deltaY: 1,
  19024. deltaW: 1,
  19025. deltaH: -1,
  19026. label: 'Top Right Crop Handle'
  19027. },
  19028. {
  19029. name: 'sw',
  19030. xMul: 0,
  19031. yMul: 1,
  19032. deltaX: 1,
  19033. deltaY: 0,
  19034. deltaW: -1,
  19035. deltaH: 1,
  19036. label: 'Bottom Left Crop Handle'
  19037. },
  19038. {
  19039. name: 'se',
  19040. xMul: 1,
  19041. yMul: 1,
  19042. deltaX: 0,
  19043. deltaY: 0,
  19044. deltaW: 1,
  19045. deltaH: 1,
  19046. label: 'Bottom Right Crop Handle'
  19047. }
  19048. ];
  19049. var blockers = [
  19050. 'top',
  19051. 'right',
  19052. 'bottom',
  19053. 'left'
  19054. ];
  19055. var getAbsoluteRect = function (outerRect, relativeRect) {
  19056. return {
  19057. x: relativeRect.x + outerRect.x,
  19058. y: relativeRect.y + outerRect.y,
  19059. w: relativeRect.w,
  19060. h: relativeRect.h
  19061. };
  19062. };
  19063. var getRelativeRect = function (outerRect, innerRect) {
  19064. return {
  19065. x: innerRect.x - outerRect.x,
  19066. y: innerRect.y - outerRect.y,
  19067. w: innerRect.w,
  19068. h: innerRect.h
  19069. };
  19070. };
  19071. var getInnerRect = function () {
  19072. return getRelativeRect(clampRect, currentRect);
  19073. };
  19074. var moveRect = function (handle, startRect, deltaX, deltaY) {
  19075. var x, y, w, h, rect;
  19076. x = startRect.x;
  19077. y = startRect.y;
  19078. w = startRect.w;
  19079. h = startRect.h;
  19080. x += deltaX * handle.deltaX;
  19081. y += deltaY * handle.deltaY;
  19082. w += deltaX * handle.deltaW;
  19083. h += deltaY * handle.deltaH;
  19084. if (w < 20) {
  19085. w = 20;
  19086. }
  19087. if (h < 20) {
  19088. h = 20;
  19089. }
  19090. rect = currentRect = global$5.clamp({
  19091. x: x,
  19092. y: y,
  19093. w: w,
  19094. h: h
  19095. }, clampRect, handle.name === 'move');
  19096. rect = getRelativeRect(clampRect, rect);
  19097. instance.fire('updateRect', { rect: rect });
  19098. setInnerRect(rect);
  19099. };
  19100. var render = function () {
  19101. var createDragHelper = function (handle) {
  19102. var startRect;
  19103. return DragHelper(id, {
  19104. document: containerElm.ownerDocument,
  19105. handle: id + '-' + handle.name,
  19106. start: function () {
  19107. startRect = currentRect;
  19108. },
  19109. drag: function (e) {
  19110. moveRect(handle, startRect, e.deltaX, e.deltaY);
  19111. }
  19112. });
  19113. };
  19114. global$4('<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">').appendTo(containerElm);
  19115. global$6.each(blockers, function (blocker) {
  19116. global$4('#' + id, containerElm).append('<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">');
  19117. });
  19118. global$6.each(handles, function (handle) {
  19119. global$4('#' + id, containerElm).append('<div id="' + id + '-' + handle.name + '" class="' + prefix + 'croprect-handle ' + prefix + 'croprect-handle-' + handle.name + '"' + 'style="display: none" data-mce-bogus="all" role="gridcell" tabindex="-1"' + ' aria-label="' + handle.label + '" aria-grabbed="false" title="' + handle.label + '">');
  19120. });
  19121. dragHelpers = global$6.map(handles, createDragHelper);
  19122. repaint(currentRect);
  19123. global$4(containerElm).on('focusin focusout', function (e) {
  19124. global$4(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
  19125. });
  19126. global$4(containerElm).on('keydown', function (e) {
  19127. var activeHandle;
  19128. global$6.each(handles, function (handle) {
  19129. if (e.target.id === id + '-' + handle.name) {
  19130. activeHandle = handle;
  19131. return false;
  19132. }
  19133. });
  19134. var moveAndBlock = function (evt, handle, startRect, deltaX, deltaY) {
  19135. evt.stopPropagation();
  19136. evt.preventDefault();
  19137. moveRect(activeHandle, startRect, deltaX, deltaY);
  19138. };
  19139. switch (e.keyCode) {
  19140. case global$2.LEFT:
  19141. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  19142. break;
  19143. case global$2.RIGHT:
  19144. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  19145. break;
  19146. case global$2.UP:
  19147. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  19148. break;
  19149. case global$2.DOWN:
  19150. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  19151. break;
  19152. case global$2.ENTER:
  19153. case global$2.SPACEBAR:
  19154. e.preventDefault();
  19155. action();
  19156. break;
  19157. }
  19158. });
  19159. };
  19160. var toggleVisibility = function (state) {
  19161. var selectors = global$6.map(handles, function (handle) {
  19162. return '#' + id + '-' + handle.name;
  19163. }).concat(global$6.map(blockers, function (blocker) {
  19164. return '#' + id + '-' + blocker;
  19165. })).join(',');
  19166. if (state) {
  19167. global$4(selectors, containerElm).show();
  19168. } else {
  19169. global$4(selectors, containerElm).hide();
  19170. }
  19171. };
  19172. var repaint = function (rect) {
  19173. var updateElementRect = function (name, rect) {
  19174. if (rect.h < 0) {
  19175. rect.h = 0;
  19176. }
  19177. if (rect.w < 0) {
  19178. rect.w = 0;
  19179. }
  19180. global$4('#' + id + '-' + name, containerElm).css({
  19181. left: rect.x,
  19182. top: rect.y,
  19183. width: rect.w,
  19184. height: rect.h
  19185. });
  19186. };
  19187. global$6.each(handles, function (handle) {
  19188. global$4('#' + id + '-' + handle.name, containerElm).css({
  19189. left: rect.w * handle.xMul + rect.x,
  19190. top: rect.h * handle.yMul + rect.y
  19191. });
  19192. });
  19193. updateElementRect('top', {
  19194. x: viewPortRect.x,
  19195. y: viewPortRect.y,
  19196. w: viewPortRect.w,
  19197. h: rect.y - viewPortRect.y
  19198. });
  19199. updateElementRect('right', {
  19200. x: rect.x + rect.w,
  19201. y: rect.y,
  19202. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  19203. h: rect.h
  19204. });
  19205. updateElementRect('bottom', {
  19206. x: viewPortRect.x,
  19207. y: rect.y + rect.h,
  19208. w: viewPortRect.w,
  19209. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  19210. });
  19211. updateElementRect('left', {
  19212. x: viewPortRect.x,
  19213. y: rect.y,
  19214. w: rect.x - viewPortRect.x,
  19215. h: rect.h
  19216. });
  19217. updateElementRect('move', rect);
  19218. };
  19219. var setRect = function (rect) {
  19220. currentRect = rect;
  19221. repaint(currentRect);
  19222. };
  19223. var setViewPortRect = function (rect) {
  19224. viewPortRect = rect;
  19225. repaint(currentRect);
  19226. };
  19227. var setInnerRect = function (rect) {
  19228. setRect(getAbsoluteRect(clampRect, rect));
  19229. };
  19230. var setClampRect = function (rect) {
  19231. clampRect = rect;
  19232. repaint(currentRect);
  19233. };
  19234. var destroy = function () {
  19235. global$6.each(dragHelpers, function (helper) {
  19236. helper.destroy();
  19237. });
  19238. dragHelpers = [];
  19239. };
  19240. render();
  19241. var instance = global$6.extend({
  19242. toggleVisibility: toggleVisibility,
  19243. setClampRect: setClampRect,
  19244. setRect: setRect,
  19245. getInnerRect: getInnerRect,
  19246. setInnerRect: setInnerRect,
  19247. setViewPortRect: setViewPortRect,
  19248. destroy: destroy
  19249. }, global$3);
  19250. return instance;
  19251. };
  19252. var CropRect = { create: create$1 };
  19253. var loadImage = function (image) {
  19254. return new global$d(function (resolve) {
  19255. var loaded = function () {
  19256. image.removeEventListener('load', loaded);
  19257. resolve(image);
  19258. };
  19259. if (image.complete) {
  19260. resolve(image);
  19261. } else {
  19262. image.addEventListener('load', loaded);
  19263. }
  19264. });
  19265. };
  19266. var renderImagePanel = function (initialUrl) {
  19267. var memBg = record({
  19268. dom: {
  19269. tag: 'div',
  19270. classes: ['tox-image-tools__image-bg'],
  19271. attributes: { role: 'presentation' }
  19272. }
  19273. });
  19274. var zoomState = Cell(1);
  19275. var cropRect = value$1();
  19276. var rectState = Cell({
  19277. x: 0,
  19278. y: 0,
  19279. w: 1,
  19280. h: 1
  19281. });
  19282. var viewRectState = Cell({
  19283. x: 0,
  19284. y: 0,
  19285. w: 1,
  19286. h: 1
  19287. });
  19288. var repaintImg = function (anyInSystem, img) {
  19289. memContainer.getOpt(anyInSystem).each(function (panel) {
  19290. var zoom = zoomState.get();
  19291. var panelW = get$7(panel.element);
  19292. var panelH = get$8(panel.element);
  19293. var width = img.dom.naturalWidth * zoom;
  19294. var height = img.dom.naturalHeight * zoom;
  19295. var left = Math.max(0, panelW / 2 - width / 2);
  19296. var top = Math.max(0, panelH / 2 - height / 2);
  19297. var css = {
  19298. left: left.toString() + 'px',
  19299. top: top.toString() + 'px',
  19300. width: width.toString() + 'px',
  19301. height: height.toString() + 'px',
  19302. position: 'absolute'
  19303. };
  19304. setAll(img, css);
  19305. memBg.getOpt(panel).each(function (bg) {
  19306. setAll(bg.element, css);
  19307. });
  19308. cropRect.on(function (cRect) {
  19309. var rect = rectState.get();
  19310. cRect.setRect({
  19311. x: rect.x * zoom + left,
  19312. y: rect.y * zoom + top,
  19313. w: rect.w * zoom,
  19314. h: rect.h * zoom
  19315. });
  19316. cRect.setClampRect({
  19317. x: left,
  19318. y: top,
  19319. w: width,
  19320. h: height
  19321. });
  19322. cRect.setViewPortRect({
  19323. x: 0,
  19324. y: 0,
  19325. w: panelW,
  19326. h: panelH
  19327. });
  19328. });
  19329. });
  19330. };
  19331. var zoomFit = function (anyInSystem, img) {
  19332. memContainer.getOpt(anyInSystem).each(function (panel) {
  19333. var panelW = get$7(panel.element);
  19334. var panelH = get$8(panel.element);
  19335. var width = img.dom.naturalWidth;
  19336. var height = img.dom.naturalHeight;
  19337. var zoom = Math.min(panelW / width, panelH / height);
  19338. if (zoom >= 1) {
  19339. zoomState.set(1);
  19340. } else {
  19341. zoomState.set(zoom);
  19342. }
  19343. });
  19344. };
  19345. var updateSrc = function (anyInSystem, url) {
  19346. var img = SugarElement.fromTag('img');
  19347. set$7(img, 'src', url);
  19348. return loadImage(img.dom).then(function () {
  19349. if (anyInSystem.getSystem().isConnected()) {
  19350. memContainer.getOpt(anyInSystem).map(function (panel) {
  19351. var aImg = external$2({ element: img });
  19352. Replacing.replaceAt(panel, 1, Optional.some(aImg));
  19353. var lastViewRect = viewRectState.get();
  19354. var viewRect = {
  19355. x: 0,
  19356. y: 0,
  19357. w: img.dom.naturalWidth,
  19358. h: img.dom.naturalHeight
  19359. };
  19360. viewRectState.set(viewRect);
  19361. var rect = global$5.inflate(viewRect, -20, -20);
  19362. rectState.set(rect);
  19363. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  19364. zoomFit(panel, img);
  19365. }
  19366. repaintImg(panel, img);
  19367. });
  19368. }
  19369. });
  19370. };
  19371. var zoom = function (anyInSystem, direction) {
  19372. var currentZoom = zoomState.get();
  19373. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  19374. zoomState.set(newZoom);
  19375. memContainer.getOpt(anyInSystem).each(function (panel) {
  19376. var img = panel.components()[1].element;
  19377. repaintImg(panel, img);
  19378. });
  19379. };
  19380. var showCrop = function () {
  19381. cropRect.on(function (cRect) {
  19382. cRect.toggleVisibility(true);
  19383. });
  19384. };
  19385. var hideCrop = function () {
  19386. cropRect.on(function (cRect) {
  19387. cRect.toggleVisibility(false);
  19388. });
  19389. };
  19390. var getRect = function () {
  19391. return rectState.get();
  19392. };
  19393. var container = Container.sketch({
  19394. dom: {
  19395. tag: 'div',
  19396. classes: ['tox-image-tools__image']
  19397. },
  19398. components: [
  19399. memBg.asSpec(),
  19400. {
  19401. dom: {
  19402. tag: 'img',
  19403. attributes: { src: initialUrl }
  19404. }
  19405. },
  19406. {
  19407. dom: { tag: 'div' },
  19408. behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
  19409. memContainer.getOpt(comp).each(function (container) {
  19410. var el = container.element.dom;
  19411. var cRect = CropRect.create({
  19412. x: 10,
  19413. y: 10,
  19414. w: 100,
  19415. h: 100
  19416. }, {
  19417. x: 0,
  19418. y: 0,
  19419. w: 200,
  19420. h: 200
  19421. }, {
  19422. x: 0,
  19423. y: 0,
  19424. w: 200,
  19425. h: 200
  19426. }, el, noop);
  19427. cRect.toggleVisibility(false);
  19428. cRect.on('updateRect', function (e) {
  19429. var rect = e.rect;
  19430. var zoom = zoomState.get();
  19431. var newRect = {
  19432. x: Math.round(rect.x / zoom),
  19433. y: Math.round(rect.y / zoom),
  19434. w: Math.round(rect.w / zoom),
  19435. h: Math.round(rect.h / zoom)
  19436. };
  19437. rectState.set(newRect);
  19438. });
  19439. cropRect.set(cRect);
  19440. });
  19441. })])])
  19442. }
  19443. ],
  19444. containerBehaviours: derive$1([
  19445. Replacing.config({}),
  19446. config('image-panel-events', [runOnAttached(function (comp) {
  19447. updateSrc(comp, initialUrl);
  19448. })])
  19449. ])
  19450. });
  19451. var memContainer = record(container);
  19452. var getMeasurements = function () {
  19453. var viewRect = viewRectState.get();
  19454. return {
  19455. width: viewRect.w,
  19456. height: viewRect.h
  19457. };
  19458. };
  19459. return {
  19460. memContainer: memContainer,
  19461. updateSrc: updateSrc,
  19462. zoom: zoom,
  19463. showCrop: showCrop,
  19464. hideCrop: hideCrop,
  19465. getRect: getRect,
  19466. getMeasurements: getMeasurements
  19467. };
  19468. };
  19469. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  19470. return renderIconButton({
  19471. name: innerHtml,
  19472. icon: Optional.some(icon),
  19473. disabled: disabled,
  19474. tooltip: Optional.some(innerHtml),
  19475. primary: false,
  19476. borderless: false
  19477. }, action, providersBackstage);
  19478. };
  19479. var setButtonEnabled = function (button, enabled) {
  19480. if (enabled) {
  19481. Disabling.enable(button);
  19482. } else {
  19483. Disabling.disable(button);
  19484. }
  19485. };
  19486. var renderSideBar = function (providersBackstage) {
  19487. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  19488. memUndo.getOpt(anyInSystem).each(function (undo) {
  19489. setButtonEnabled(undo, undoEnabled);
  19490. });
  19491. memRedo.getOpt(anyInSystem).each(function (redo) {
  19492. setButtonEnabled(redo, redoEnabled);
  19493. });
  19494. };
  19495. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  19496. emitWith(button, internal.undo(), { direction: 1 });
  19497. }, providersBackstage));
  19498. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  19499. emitWith(button, internal.redo(), { direction: 1 });
  19500. }, providersBackstage));
  19501. var container = Container.sketch({
  19502. dom: {
  19503. tag: 'div',
  19504. classes: [
  19505. 'tox-image-tools__toolbar',
  19506. 'tox-image-tools__sidebar'
  19507. ]
  19508. },
  19509. components: [
  19510. memUndo.asSpec(),
  19511. memRedo.asSpec(),
  19512. createButton('Zoom in', 'zoom-in', false, function (button) {
  19513. emitWith(button, internal.zoom(), { direction: 1 });
  19514. }, providersBackstage),
  19515. createButton('Zoom out', 'zoom-out', false, function (button) {
  19516. emitWith(button, internal.zoom(), { direction: -1 });
  19517. }, providersBackstage)
  19518. ]
  19519. });
  19520. return {
  19521. container: container,
  19522. updateButtonUndoStates: updateButtonUndoStates
  19523. };
  19524. };
  19525. function UndoStack () {
  19526. var data = [];
  19527. var index = -1;
  19528. var add = function (state) {
  19529. var removed = data.splice(++index);
  19530. data.push(state);
  19531. return {
  19532. state: state,
  19533. removed: removed
  19534. };
  19535. };
  19536. var undo = function () {
  19537. if (canUndo()) {
  19538. return data[--index];
  19539. }
  19540. };
  19541. var redo = function () {
  19542. if (canRedo()) {
  19543. return data[++index];
  19544. }
  19545. };
  19546. var canUndo = function () {
  19547. return index > 0;
  19548. };
  19549. var canRedo = function () {
  19550. return index !== -1 && index < data.length - 1;
  19551. };
  19552. return {
  19553. data: data,
  19554. add: add,
  19555. undo: undo,
  19556. redo: redo,
  19557. canUndo: canUndo,
  19558. canRedo: canRedo
  19559. };
  19560. }
  19561. var makeState = function (initialState) {
  19562. var blobState = Cell(initialState);
  19563. var tempState = value$1();
  19564. var undoStack = UndoStack();
  19565. undoStack.add(initialState);
  19566. var getBlobState = function () {
  19567. return blobState.get();
  19568. };
  19569. var setBlobState = function (state) {
  19570. blobState.set(state);
  19571. };
  19572. var getTempState = function () {
  19573. return tempState.get().getOrThunk(blobState.get);
  19574. };
  19575. var updateTempState = function (blob) {
  19576. var newTempState = createState(blob);
  19577. destroyTempState();
  19578. tempState.set(newTempState);
  19579. return newTempState.url;
  19580. };
  19581. var createState = function (blob) {
  19582. return {
  19583. blob: blob,
  19584. url: URL.createObjectURL(blob)
  19585. };
  19586. };
  19587. var destroyState = function (state) {
  19588. URL.revokeObjectURL(state.url);
  19589. };
  19590. var destroyStates = function (states) {
  19591. global$6.each(states, destroyState);
  19592. };
  19593. var destroyTempState = function () {
  19594. tempState.on(destroyState);
  19595. tempState.clear();
  19596. };
  19597. var addBlobState = function (blob) {
  19598. var newState = createState(blob);
  19599. setBlobState(newState);
  19600. var removed = undoStack.add(newState).removed;
  19601. destroyStates(removed);
  19602. return newState.url;
  19603. };
  19604. var addTempState = function (blob) {
  19605. var newState = createState(blob);
  19606. tempState.set(newState);
  19607. return newState.url;
  19608. };
  19609. var applyTempState = function (postApply) {
  19610. return tempState.get().fold(noop, function (temp) {
  19611. addBlobState(temp.blob);
  19612. postApply();
  19613. });
  19614. };
  19615. var undo = function () {
  19616. var currentState = undoStack.undo();
  19617. setBlobState(currentState);
  19618. return currentState.url;
  19619. };
  19620. var redo = function () {
  19621. var currentState = undoStack.redo();
  19622. setBlobState(currentState);
  19623. return currentState.url;
  19624. };
  19625. var getHistoryStates = function () {
  19626. var undoEnabled = undoStack.canUndo();
  19627. var redoEnabled = undoStack.canRedo();
  19628. return {
  19629. undoEnabled: undoEnabled,
  19630. redoEnabled: redoEnabled
  19631. };
  19632. };
  19633. return {
  19634. getBlobState: getBlobState,
  19635. setBlobState: setBlobState,
  19636. addBlobState: addBlobState,
  19637. getTempState: getTempState,
  19638. updateTempState: updateTempState,
  19639. addTempState: addTempState,
  19640. applyTempState: applyTempState,
  19641. destroyTempState: destroyTempState,
  19642. undo: undo,
  19643. redo: redo,
  19644. getHistoryStates: getHistoryStates
  19645. };
  19646. };
  19647. var renderImageTools = function (detail, providersBackstage) {
  19648. var state = makeState(detail.currentState);
  19649. var zoom = function (anyInSystem, simulatedEvent) {
  19650. var direction = simulatedEvent.event.direction;
  19651. imagePanel.zoom(anyInSystem, direction);
  19652. };
  19653. var updateButtonUndoStates = function (anyInSystem) {
  19654. var historyStates = state.getHistoryStates();
  19655. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  19656. emitWith(anyInSystem, external.formActionEvent, {
  19657. name: external.saveState(),
  19658. value: historyStates.undoEnabled
  19659. });
  19660. };
  19661. var disableUndoRedo = function (anyInSystem) {
  19662. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  19663. };
  19664. var undo = function (anyInSystem, _simulatedEvent) {
  19665. var url = state.undo();
  19666. updateSrc(anyInSystem, url).then(function (_oImg) {
  19667. unblock(anyInSystem);
  19668. updateButtonUndoStates(anyInSystem);
  19669. });
  19670. };
  19671. var redo = function (anyInSystem, _simulatedEvent) {
  19672. var url = state.redo();
  19673. updateSrc(anyInSystem, url).then(function (_oImg) {
  19674. unblock(anyInSystem);
  19675. updateButtonUndoStates(anyInSystem);
  19676. });
  19677. };
  19678. var imageResultToBlob = function (ir) {
  19679. return ir.toBlob();
  19680. };
  19681. var block = function (anyInSystem) {
  19682. emitWith(anyInSystem, external.formActionEvent, {
  19683. name: external.disable(),
  19684. value: {}
  19685. });
  19686. };
  19687. var unblock = function (anyInSystem) {
  19688. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  19689. Disabling.enable(applyButton);
  19690. });
  19691. emitWith(anyInSystem, external.formActionEvent, {
  19692. name: external.enable(),
  19693. value: {}
  19694. });
  19695. };
  19696. var updateSrc = function (anyInSystem, src) {
  19697. block(anyInSystem);
  19698. return imagePanel.updateSrc(anyInSystem, src);
  19699. };
  19700. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  19701. block(anyInSystem);
  19702. blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  19703. return updateSrc(anyInSystem, url);
  19704. }).then(function () {
  19705. updateButtonUndoStates(anyInSystem);
  19706. swap();
  19707. unblock(anyInSystem);
  19708. }).catch(function (err) {
  19709. console.log(err);
  19710. if (anyInSystem.getSystem().isConnected()) {
  19711. unblock(anyInSystem);
  19712. }
  19713. });
  19714. };
  19715. var manipulate = function (anyInSystem, filter, swap) {
  19716. var blob = state.getBlobState().blob;
  19717. var action = function (blob) {
  19718. return state.updateTempState(blob);
  19719. };
  19720. blobManipulate(anyInSystem, blob, filter, action, swap);
  19721. };
  19722. var tempManipulate = function (anyInSystem, filter) {
  19723. var blob = state.getTempState().blob;
  19724. var action = function (blob) {
  19725. return state.addTempState(blob);
  19726. };
  19727. blobManipulate(anyInSystem, blob, filter, action, noop);
  19728. };
  19729. var manipulateApply = function (anyInSystem, filter, swap) {
  19730. var blob = state.getBlobState().blob;
  19731. var action = function (blob) {
  19732. var url = state.addBlobState(blob);
  19733. destroyTempState(anyInSystem);
  19734. return url;
  19735. };
  19736. blobManipulate(anyInSystem, blob, filter, action, swap);
  19737. };
  19738. var apply = function (anyInSystem, simulatedEvent) {
  19739. var postApply = function () {
  19740. destroyTempState(anyInSystem);
  19741. var swap = simulatedEvent.event.swap;
  19742. swap();
  19743. };
  19744. state.applyTempState(postApply);
  19745. };
  19746. var destroyTempState = function (anyInSystem) {
  19747. var currentUrl = state.getBlobState().url;
  19748. state.destroyTempState();
  19749. updateButtonUndoStates(anyInSystem);
  19750. return currentUrl;
  19751. };
  19752. var cancel = function (anyInSystem) {
  19753. var currentUrl = destroyTempState(anyInSystem);
  19754. updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
  19755. unblock(anyInSystem);
  19756. });
  19757. };
  19758. var back = function (anyInSystem, simulatedEvent) {
  19759. cancel(anyInSystem);
  19760. var swap = simulatedEvent.event.swap;
  19761. swap();
  19762. imagePanel.hideCrop();
  19763. };
  19764. var transform = function (anyInSystem, simulatedEvent) {
  19765. return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
  19766. };
  19767. var tempTransform = function (anyInSystem, simulatedEvent) {
  19768. return tempManipulate(anyInSystem, simulatedEvent.event.transform);
  19769. };
  19770. var transformApply = function (anyInSystem, simulatedEvent) {
  19771. return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
  19772. };
  19773. var imagePanel = renderImagePanel(detail.currentState.url);
  19774. var sideBar = renderSideBar(providersBackstage);
  19775. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  19776. var swap = function (anyInSystem, simulatedEvent) {
  19777. disableUndoRedo(anyInSystem);
  19778. var transform = simulatedEvent.event.transform;
  19779. var swap = simulatedEvent.event.swap;
  19780. transform.fold(function () {
  19781. swap();
  19782. }, function (transform) {
  19783. manipulate(anyInSystem, transform, swap);
  19784. });
  19785. };
  19786. return {
  19787. dom: {
  19788. tag: 'div',
  19789. attributes: { role: 'presentation' }
  19790. },
  19791. components: [
  19792. editPanel.memContainer.asSpec(),
  19793. imagePanel.memContainer.asSpec(),
  19794. sideBar.container
  19795. ],
  19796. behaviours: derive$1([
  19797. Representing.config({
  19798. store: {
  19799. mode: 'manual',
  19800. getValue: function () {
  19801. return state.getBlobState();
  19802. }
  19803. }
  19804. }),
  19805. config('image-tools-events', [
  19806. run$1(internal.undo(), undo),
  19807. run$1(internal.redo(), redo),
  19808. run$1(internal.zoom(), zoom),
  19809. run$1(internal.back(), back),
  19810. run$1(internal.apply(), apply),
  19811. run$1(internal.transform(), transform),
  19812. run$1(internal.tempTransform(), tempTransform),
  19813. run$1(internal.transformApply(), transformApply),
  19814. run$1(internal.swap(), swap)
  19815. ]),
  19816. ComposingConfigs.self()
  19817. ])
  19818. };
  19819. };
  19820. var renderLabel = function (spec, backstageShared) {
  19821. var label = {
  19822. dom: {
  19823. tag: 'label',
  19824. innerHtml: backstageShared.providers.translate(spec.label),
  19825. classes: ['tox-label']
  19826. }
  19827. };
  19828. var comps = map$2(spec.items, backstageShared.interpreter);
  19829. return {
  19830. dom: {
  19831. tag: 'div',
  19832. classes: ['tox-form__group']
  19833. },
  19834. components: [label].concat(comps),
  19835. behaviours: derive$1([
  19836. ComposingConfigs.self(),
  19837. Replacing.config({}),
  19838. RepresentingConfigs.domHtml(Optional.none()),
  19839. Keying.config({ mode: 'acyclic' })
  19840. ])
  19841. };
  19842. };
  19843. var isSingleListItem = function (item) {
  19844. return !has$2(item, 'items');
  19845. };
  19846. var dataAttribute = 'data-value';
  19847. var fetchItems = function (dropdownComp, name, items, selectedValue) {
  19848. return map$2(items, function (item) {
  19849. if (!isSingleListItem(item)) {
  19850. return {
  19851. type: 'nestedmenuitem',
  19852. text: item.text,
  19853. getSubmenuItems: function () {
  19854. return fetchItems(dropdownComp, name, item.items, selectedValue);
  19855. }
  19856. };
  19857. } else {
  19858. return {
  19859. type: 'togglemenuitem',
  19860. text: item.text,
  19861. value: item.value,
  19862. active: item.value === selectedValue,
  19863. onAction: function () {
  19864. Representing.setValue(dropdownComp, item.value);
  19865. emitWith(dropdownComp, formChangeEvent, { name: name });
  19866. Focusing.focus(dropdownComp);
  19867. }
  19868. };
  19869. }
  19870. });
  19871. };
  19872. var findItemByValue = function (items, value) {
  19873. return findMap(items, function (item) {
  19874. if (!isSingleListItem(item)) {
  19875. return findItemByValue(item.items, value);
  19876. } else {
  19877. return someIf(item.value === value, item);
  19878. }
  19879. });
  19880. };
  19881. var renderListBox = function (spec, backstage) {
  19882. var providersBackstage = backstage.shared.providers;
  19883. var initialItem = head(spec.items).filter(isSingleListItem);
  19884. var pLabel = spec.label.map(function (label) {
  19885. return renderLabel$2(label, providersBackstage);
  19886. });
  19887. var pField = FormField.parts.field({
  19888. dom: {},
  19889. factory: {
  19890. sketch: function (sketchSpec) {
  19891. return renderCommonDropdown({
  19892. uid: sketchSpec.uid,
  19893. text: initialItem.map(function (item) {
  19894. return item.text;
  19895. }),
  19896. icon: Optional.none(),
  19897. tooltip: spec.label,
  19898. role: Optional.none(),
  19899. fetch: function (comp, callback) {
  19900. var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
  19901. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  19902. },
  19903. onSetup: constant$1(noop),
  19904. getApi: constant$1({}),
  19905. columns: 1,
  19906. presets: 'normal',
  19907. classes: [],
  19908. dropdownBehaviours: [
  19909. Tabstopping.config({}),
  19910. Representing.config({
  19911. store: {
  19912. mode: 'manual',
  19913. initialValue: initialItem.map(function (item) {
  19914. return item.value;
  19915. }).getOr(''),
  19916. getValue: function (comp) {
  19917. return get$c(comp.element, dataAttribute);
  19918. },
  19919. setValue: function (comp, data) {
  19920. findItemByValue(spec.items, data).each(function (item) {
  19921. set$7(comp.element, dataAttribute, item.value);
  19922. emitWith(comp, updateMenuText, { text: item.text });
  19923. });
  19924. }
  19925. }
  19926. })
  19927. ]
  19928. }, 'tox-listbox', backstage.shared);
  19929. }
  19930. }
  19931. });
  19932. var listBoxWrap = {
  19933. dom: {
  19934. tag: 'div',
  19935. classes: ['tox-listboxfield']
  19936. },
  19937. components: [pField]
  19938. };
  19939. return FormField.sketch({
  19940. dom: {
  19941. tag: 'div',
  19942. classes: ['tox-form__group']
  19943. },
  19944. components: flatten([
  19945. pLabel.toArray(),
  19946. [listBoxWrap]
  19947. ]),
  19948. fieldBehaviours: derive$1([Disabling.config({
  19949. disabled: constant$1(spec.disabled),
  19950. onDisabled: function (comp) {
  19951. FormField.getField(comp).each(Disabling.disable);
  19952. },
  19953. onEnabled: function (comp) {
  19954. FormField.getField(comp).each(Disabling.enable);
  19955. }
  19956. })])
  19957. });
  19958. };
  19959. var renderPanel = function (spec, backstage) {
  19960. return {
  19961. dom: {
  19962. tag: 'div',
  19963. classes: spec.classes
  19964. },
  19965. components: map$2(spec.items, backstage.shared.interpreter)
  19966. };
  19967. };
  19968. var factory$e = function (detail, _spec) {
  19969. var options = map$2(detail.options, function (option) {
  19970. return {
  19971. dom: {
  19972. tag: 'option',
  19973. value: option.value,
  19974. innerHtml: option.text
  19975. }
  19976. };
  19977. });
  19978. var initialValues = detail.data.map(function (v) {
  19979. return wrap$1('initialValue', v);
  19980. }).getOr({});
  19981. return {
  19982. uid: detail.uid,
  19983. dom: {
  19984. tag: 'select',
  19985. classes: detail.selectClasses,
  19986. attributes: detail.selectAttributes
  19987. },
  19988. components: options,
  19989. behaviours: augment(detail.selectBehaviours, [
  19990. Focusing.config({}),
  19991. Representing.config({
  19992. store: __assign({
  19993. mode: 'manual',
  19994. getValue: function (select) {
  19995. return get$9(select.element);
  19996. },
  19997. setValue: function (select, newValue) {
  19998. var found = find$5(detail.options, function (opt) {
  19999. return opt.value === newValue;
  20000. });
  20001. if (found.isSome()) {
  20002. set$5(select.element, newValue);
  20003. }
  20004. }
  20005. }, initialValues)
  20006. })
  20007. ])
  20008. };
  20009. };
  20010. var HtmlSelect = single({
  20011. name: 'HtmlSelect',
  20012. configFields: [
  20013. required$1('options'),
  20014. field('selectBehaviours', [
  20015. Focusing,
  20016. Representing
  20017. ]),
  20018. defaulted('selectClasses', []),
  20019. defaulted('selectAttributes', {}),
  20020. option('data')
  20021. ],
  20022. factory: factory$e
  20023. });
  20024. var renderSelectBox = function (spec, providersBackstage) {
  20025. var translatedOptions = map$2(spec.items, function (item) {
  20026. return {
  20027. text: providersBackstage.translate(item.text),
  20028. value: item.value
  20029. };
  20030. });
  20031. var pLabel = spec.label.map(function (label) {
  20032. return renderLabel$2(label, providersBackstage);
  20033. });
  20034. var pField = FormField.parts.field({
  20035. dom: {},
  20036. selectAttributes: { size: spec.size },
  20037. options: translatedOptions,
  20038. factory: HtmlSelect,
  20039. selectBehaviours: derive$1([
  20040. Disabling.config({
  20041. disabled: function () {
  20042. return spec.disabled || providersBackstage.isDisabled();
  20043. }
  20044. }),
  20045. Tabstopping.config({}),
  20046. config('selectbox-change', [run$1(change(), function (component, _) {
  20047. emitWith(component, formChangeEvent, { name: spec.name });
  20048. })])
  20049. ])
  20050. });
  20051. var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3('chevron-down', {
  20052. tag: 'div',
  20053. classes: ['tox-selectfield__icon-js']
  20054. }, providersBackstage.icons));
  20055. var selectWrap = {
  20056. dom: {
  20057. tag: 'div',
  20058. classes: ['tox-selectfield']
  20059. },
  20060. components: flatten([
  20061. [pField],
  20062. chevron.toArray()
  20063. ])
  20064. };
  20065. return FormField.sketch({
  20066. dom: {
  20067. tag: 'div',
  20068. classes: ['tox-form__group']
  20069. },
  20070. components: flatten([
  20071. pLabel.toArray(),
  20072. [selectWrap]
  20073. ]),
  20074. fieldBehaviours: derive$1([
  20075. Disabling.config({
  20076. disabled: function () {
  20077. return spec.disabled || providersBackstage.isDisabled();
  20078. },
  20079. onDisabled: function (comp) {
  20080. FormField.getField(comp).each(Disabling.disable);
  20081. },
  20082. onEnabled: function (comp) {
  20083. FormField.getField(comp).each(Disabling.enable);
  20084. }
  20085. }),
  20086. receivingConfig()
  20087. ])
  20088. });
  20089. };
  20090. var renderTable = function (spec, providersBackstage) {
  20091. var renderTh = function (text) {
  20092. return {
  20093. dom: {
  20094. tag: 'th',
  20095. innerHtml: providersBackstage.translate(text)
  20096. }
  20097. };
  20098. };
  20099. var renderHeader = function (header) {
  20100. return {
  20101. dom: { tag: 'thead' },
  20102. components: [{
  20103. dom: { tag: 'tr' },
  20104. components: map$2(header, renderTh)
  20105. }]
  20106. };
  20107. };
  20108. var renderTd = function (text) {
  20109. return {
  20110. dom: {
  20111. tag: 'td',
  20112. innerHtml: providersBackstage.translate(text)
  20113. }
  20114. };
  20115. };
  20116. var renderTr = function (row) {
  20117. return {
  20118. dom: { tag: 'tr' },
  20119. components: map$2(row, renderTd)
  20120. };
  20121. };
  20122. var renderRows = function (rows) {
  20123. return {
  20124. dom: { tag: 'tbody' },
  20125. components: map$2(rows, renderTr)
  20126. };
  20127. };
  20128. return {
  20129. dom: {
  20130. tag: 'table',
  20131. classes: ['tox-dialog__table']
  20132. },
  20133. components: [
  20134. renderHeader(spec.header),
  20135. renderRows(spec.cells)
  20136. ],
  20137. behaviours: derive$1([
  20138. Tabstopping.config({}),
  20139. Focusing.config({})
  20140. ])
  20141. };
  20142. };
  20143. var renderTextField = function (spec, providersBackstage) {
  20144. var pLabel = spec.label.map(function (label) {
  20145. return renderLabel$2(label, providersBackstage);
  20146. });
  20147. var baseInputBehaviours = [
  20148. Disabling.config({
  20149. disabled: function () {
  20150. return spec.disabled || providersBackstage.isDisabled();
  20151. }
  20152. }),
  20153. receivingConfig(),
  20154. Keying.config({
  20155. mode: 'execution',
  20156. useEnter: spec.multiline !== true,
  20157. useControlEnter: spec.multiline === true,
  20158. execute: function (comp) {
  20159. emit(comp, formSubmitEvent);
  20160. return Optional.some(true);
  20161. }
  20162. }),
  20163. config('textfield-change', [
  20164. run$1(input(), function (component, _) {
  20165. emitWith(component, formChangeEvent, { name: spec.name });
  20166. }),
  20167. run$1(postPaste(), function (component, _) {
  20168. emitWith(component, formChangeEvent, { name: spec.name });
  20169. })
  20170. ]),
  20171. Tabstopping.config({})
  20172. ];
  20173. var validatingBehaviours = spec.validation.map(function (vl) {
  20174. return Invalidating.config({
  20175. getRoot: function (input) {
  20176. return parent(input.element);
  20177. },
  20178. invalidClass: 'tox-invalid',
  20179. validator: {
  20180. validate: function (input) {
  20181. var v = Representing.getValue(input);
  20182. var result = vl.validator(v);
  20183. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  20184. },
  20185. validateOnLoad: vl.validateOnLoad
  20186. }
  20187. });
  20188. }).toArray();
  20189. var placeholder = spec.placeholder.fold(constant$1({}), function (p) {
  20190. return { placeholder: providersBackstage.translate(p) };
  20191. });
  20192. var inputMode = spec.inputMode.fold(constant$1({}), function (mode) {
  20193. return { inputmode: mode };
  20194. });
  20195. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  20196. var pField = FormField.parts.field({
  20197. tag: spec.multiline === true ? 'textarea' : 'input',
  20198. inputAttributes: inputAttributes,
  20199. inputClasses: [spec.classname],
  20200. inputBehaviours: derive$1(flatten([
  20201. baseInputBehaviours,
  20202. validatingBehaviours
  20203. ])),
  20204. selectOnFocus: false,
  20205. factory: Input
  20206. });
  20207. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  20208. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  20209. var extraBehaviours = [
  20210. Disabling.config({
  20211. disabled: function () {
  20212. return spec.disabled || providersBackstage.isDisabled();
  20213. },
  20214. onDisabled: function (comp) {
  20215. FormField.getField(comp).each(Disabling.disable);
  20216. },
  20217. onEnabled: function (comp) {
  20218. FormField.getField(comp).each(Disabling.enable);
  20219. }
  20220. }),
  20221. receivingConfig()
  20222. ];
  20223. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  20224. };
  20225. var renderInput = function (spec, providersBackstage) {
  20226. return renderTextField({
  20227. name: spec.name,
  20228. multiline: false,
  20229. label: spec.label,
  20230. inputMode: spec.inputMode,
  20231. placeholder: spec.placeholder,
  20232. flex: false,
  20233. disabled: spec.disabled,
  20234. classname: 'tox-textfield',
  20235. validation: Optional.none(),
  20236. maximized: spec.maximized
  20237. }, providersBackstage);
  20238. };
  20239. var renderTextarea = function (spec, providersBackstage) {
  20240. return renderTextField({
  20241. name: spec.name,
  20242. multiline: true,
  20243. label: spec.label,
  20244. inputMode: Optional.none(),
  20245. placeholder: spec.placeholder,
  20246. flex: true,
  20247. disabled: spec.disabled,
  20248. classname: 'tox-textarea',
  20249. validation: Optional.none(),
  20250. maximized: spec.maximized
  20251. }, providersBackstage);
  20252. };
  20253. var events$6 = function (streamConfig, streamState) {
  20254. var streams = streamConfig.stream.streams;
  20255. var processor = streams.setup(streamConfig, streamState);
  20256. return derive$2([
  20257. run$1(streamConfig.event, processor),
  20258. runOnDetached(function () {
  20259. return streamState.cancel();
  20260. })
  20261. ].concat(streamConfig.cancelEvent.map(function (e) {
  20262. return [run$1(e, function () {
  20263. return streamState.cancel();
  20264. })];
  20265. }).getOr([])));
  20266. };
  20267. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  20268. __proto__: null,
  20269. events: events$6
  20270. });
  20271. var throttle = function (_config) {
  20272. var state = Cell(null);
  20273. var readState = function () {
  20274. return { timer: state.get() !== null ? 'set' : 'unset' };
  20275. };
  20276. var setTimer = function (t) {
  20277. state.set(t);
  20278. };
  20279. var cancel = function () {
  20280. var t = state.get();
  20281. if (t !== null) {
  20282. t.cancel();
  20283. }
  20284. };
  20285. return nu$8({
  20286. readState: readState,
  20287. setTimer: setTimer,
  20288. cancel: cancel
  20289. });
  20290. };
  20291. var init$9 = function (spec) {
  20292. return spec.stream.streams.state(spec);
  20293. };
  20294. var StreamingState = /*#__PURE__*/Object.freeze({
  20295. __proto__: null,
  20296. throttle: throttle,
  20297. init: init$9
  20298. });
  20299. var setup$c = function (streamInfo, streamState) {
  20300. var sInfo = streamInfo.stream;
  20301. var throttler = last(streamInfo.onStream, sInfo.delay);
  20302. streamState.setTimer(throttler);
  20303. return function (component, simulatedEvent) {
  20304. throttler.throttle(component, simulatedEvent);
  20305. if (sInfo.stopEvent) {
  20306. simulatedEvent.stop();
  20307. }
  20308. };
  20309. };
  20310. var StreamingSchema = [
  20311. requiredOf('stream', choose$1('mode', {
  20312. throttle: [
  20313. required$1('delay'),
  20314. defaulted('stopEvent', true),
  20315. output$1('streams', {
  20316. setup: setup$c,
  20317. state: throttle
  20318. })
  20319. ]
  20320. })),
  20321. defaulted('event', 'input'),
  20322. option('cancelEvent'),
  20323. onStrictHandler('onStream')
  20324. ];
  20325. var Streaming = create$7({
  20326. fields: StreamingSchema,
  20327. name: 'streaming',
  20328. active: ActiveStreaming,
  20329. state: StreamingState
  20330. });
  20331. var setValueFromItem = function (model, input, item) {
  20332. var itemData = Representing.getValue(item);
  20333. Representing.setValue(input, itemData);
  20334. setCursorAtEnd(input);
  20335. };
  20336. var setSelectionOn = function (input, f) {
  20337. var el = input.element;
  20338. var value = get$9(el);
  20339. var node = el.dom;
  20340. if (get$c(el, 'type') !== 'number') {
  20341. f(node, value);
  20342. }
  20343. };
  20344. var setCursorAtEnd = function (input) {
  20345. setSelectionOn(input, function (node, value) {
  20346. return node.setSelectionRange(value.length, value.length);
  20347. });
  20348. };
  20349. var setSelectionToEnd = function (input, startOffset) {
  20350. setSelectionOn(input, function (node, value) {
  20351. return node.setSelectionRange(startOffset, value.length);
  20352. });
  20353. };
  20354. var attemptSelectOver = function (model, input, item) {
  20355. if (!model.selectsOver) {
  20356. return Optional.none();
  20357. } else {
  20358. var currentValue = Representing.getValue(input);
  20359. var inputDisplay_1 = model.getDisplayText(currentValue);
  20360. var itemValue = Representing.getValue(item);
  20361. var itemDisplay = model.getDisplayText(itemValue);
  20362. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () {
  20363. setValueFromItem(model, input, item);
  20364. setSelectionToEnd(input, inputDisplay_1.length);
  20365. }) : Optional.none();
  20366. }
  20367. };
  20368. var itemExecute = constant$1('alloy.typeahead.itemexecute');
  20369. var make$3 = function (detail, components, spec, externals) {
  20370. var navigateList = function (comp, simulatedEvent, highlighter) {
  20371. detail.previewing.set(false);
  20372. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20373. if (Sandboxing.isOpen(sandbox)) {
  20374. Composing.getCurrent(sandbox).each(function (menu) {
  20375. Highlighting.getHighlighted(menu).fold(function () {
  20376. highlighter(menu);
  20377. }, function () {
  20378. dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
  20379. });
  20380. });
  20381. } else {
  20382. var onOpenSync = function (sandbox) {
  20383. Composing.getCurrent(sandbox).each(highlighter);
  20384. };
  20385. open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  20386. }
  20387. };
  20388. var focusBehaviours$1 = focusBehaviours(detail);
  20389. var mapFetch = function (comp) {
  20390. return function (tdata) {
  20391. return tdata.map(function (data) {
  20392. var menus = values(data.menus);
  20393. var items = bind$3(menus, function (menu) {
  20394. return filter$2(menu.items, function (item) {
  20395. return item.type === 'item';
  20396. });
  20397. });
  20398. var repState = Representing.getState(comp);
  20399. repState.update(map$2(items, function (item) {
  20400. return item.data;
  20401. }));
  20402. return data;
  20403. });
  20404. };
  20405. };
  20406. var behaviours = [
  20407. Focusing.config({}),
  20408. Representing.config({
  20409. onSetValue: detail.onSetValue,
  20410. store: __assign({
  20411. mode: 'dataset',
  20412. getDataKey: function (comp) {
  20413. return get$9(comp.element);
  20414. },
  20415. getFallbackEntry: function (itemString) {
  20416. return {
  20417. value: itemString,
  20418. meta: {}
  20419. };
  20420. },
  20421. setValue: function (comp, data) {
  20422. set$5(comp.element, detail.model.getDisplayText(data));
  20423. }
  20424. }, detail.initialData.map(function (d) {
  20425. return wrap$1('initialValue', d);
  20426. }).getOr({}))
  20427. }),
  20428. Streaming.config({
  20429. stream: {
  20430. mode: 'throttle',
  20431. delay: detail.responseTime,
  20432. stopEvent: false
  20433. },
  20434. onStream: function (component, _simulatedEvent) {
  20435. var sandbox = Coupling.getCoupled(component, 'sandbox');
  20436. var focusInInput = Focusing.isFocused(component);
  20437. if (focusInInput) {
  20438. if (get$9(component.element).length >= detail.minChars) {
  20439. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  20440. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  20441. });
  20442. detail.previewing.set(true);
  20443. var onOpenSync = function (_sandbox) {
  20444. Composing.getCurrent(sandbox).each(function (menu) {
  20445. previousValue_1.fold(function () {
  20446. if (detail.model.selectsOver) {
  20447. Highlighting.highlightFirst(menu);
  20448. }
  20449. }, function (pv) {
  20450. Highlighting.highlightBy(menu, function (item) {
  20451. var itemData = Representing.getValue(item);
  20452. return itemData.value === pv.value;
  20453. });
  20454. Highlighting.getHighlighted(menu).orThunk(function () {
  20455. Highlighting.highlightFirst(menu);
  20456. return Optional.none();
  20457. });
  20458. });
  20459. });
  20460. };
  20461. open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  20462. }
  20463. }
  20464. },
  20465. cancelEvent: typeaheadCancel()
  20466. }),
  20467. Keying.config({
  20468. mode: 'special',
  20469. onDown: function (comp, simulatedEvent) {
  20470. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  20471. return Optional.some(true);
  20472. },
  20473. onEscape: function (comp) {
  20474. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20475. if (Sandboxing.isOpen(sandbox)) {
  20476. Sandboxing.close(sandbox);
  20477. return Optional.some(true);
  20478. }
  20479. return Optional.none();
  20480. },
  20481. onUp: function (comp, simulatedEvent) {
  20482. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  20483. return Optional.some(true);
  20484. },
  20485. onEnter: function (comp) {
  20486. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20487. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  20488. if (sandboxIsOpen && !detail.previewing.get()) {
  20489. return Composing.getCurrent(sandbox).bind(function (menu) {
  20490. return Highlighting.getHighlighted(menu);
  20491. }).map(function (item) {
  20492. emitWith(comp, itemExecute(), { item: item });
  20493. return true;
  20494. });
  20495. } else {
  20496. var currentValue = Representing.getValue(comp);
  20497. emit(comp, typeaheadCancel());
  20498. detail.onExecute(sandbox, comp, currentValue);
  20499. if (sandboxIsOpen) {
  20500. Sandboxing.close(sandbox);
  20501. }
  20502. return Optional.some(true);
  20503. }
  20504. }
  20505. }),
  20506. Toggling.config({
  20507. toggleClass: detail.markers.openClass,
  20508. aria: { mode: 'expanded' }
  20509. }),
  20510. Coupling.config({
  20511. others: {
  20512. sandbox: function (hotspot) {
  20513. return makeSandbox$1(detail, hotspot, {
  20514. onOpen: function () {
  20515. return Toggling.on(hotspot);
  20516. },
  20517. onClose: function () {
  20518. return Toggling.off(hotspot);
  20519. }
  20520. });
  20521. }
  20522. }
  20523. }),
  20524. config('typeaheadevents', [
  20525. runOnExecute$1(function (comp) {
  20526. var onOpenSync = noop;
  20527. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  20528. }),
  20529. run$1(itemExecute(), function (comp, se) {
  20530. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20531. setValueFromItem(detail.model, comp, se.event.item);
  20532. emit(comp, typeaheadCancel());
  20533. detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
  20534. Sandboxing.close(sandbox);
  20535. setCursorAtEnd(comp);
  20536. })
  20537. ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function (typeahead) {
  20538. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  20539. if (search(sandbox.element).isNone()) {
  20540. Sandboxing.close(sandbox);
  20541. }
  20542. })] : []))
  20543. ];
  20544. return {
  20545. uid: detail.uid,
  20546. dom: dom(deepMerge(detail, {
  20547. inputAttributes: {
  20548. 'role': 'combobox',
  20549. 'aria-autocomplete': 'list',
  20550. 'aria-haspopup': 'true'
  20551. }
  20552. })),
  20553. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  20554. eventOrder: detail.eventOrder
  20555. };
  20556. };
  20557. var schema$g = constant$1([
  20558. option('lazySink'),
  20559. required$1('fetch'),
  20560. defaulted('minChars', 5),
  20561. defaulted('responseTime', 1000),
  20562. onHandler('onOpen'),
  20563. defaulted('getHotspot', Optional.some),
  20564. defaulted('getAnchorOverrides', constant$1({})),
  20565. defaulted('layouts', Optional.none()),
  20566. defaulted('eventOrder', {}),
  20567. defaultedObjOf('model', {}, [
  20568. defaulted('getDisplayText', function (itemData) {
  20569. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  20570. }),
  20571. defaulted('selectsOver', true),
  20572. defaulted('populateFromBrowse', true)
  20573. ]),
  20574. onHandler('onSetValue'),
  20575. onKeyboardHandler('onExecute'),
  20576. onHandler('onItemExecute'),
  20577. defaulted('inputClasses', []),
  20578. defaulted('inputAttributes', {}),
  20579. defaulted('inputStyles', {}),
  20580. defaulted('matchWidth', true),
  20581. defaulted('useMinWidth', false),
  20582. defaulted('dismissOnBlur', true),
  20583. markers$1(['openClass']),
  20584. option('initialData'),
  20585. field('typeaheadBehaviours', [
  20586. Focusing,
  20587. Representing,
  20588. Streaming,
  20589. Keying,
  20590. Toggling,
  20591. Coupling
  20592. ]),
  20593. customField('previewing', function () {
  20594. return Cell(true);
  20595. })
  20596. ].concat(schema$k()).concat(sandboxFields()));
  20597. var parts$b = constant$1([external$1({
  20598. schema: [tieredMenuMarkers()],
  20599. name: 'menu',
  20600. overrides: function (detail) {
  20601. return {
  20602. fakeFocus: true,
  20603. onHighlight: function (menu, item) {
  20604. if (!detail.previewing.get()) {
  20605. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20606. if (detail.model.populateFromBrowse) {
  20607. setValueFromItem(detail.model, input, item);
  20608. }
  20609. });
  20610. } else {
  20611. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20612. attemptSelectOver(detail.model, input, item).fold(function () {
  20613. return Highlighting.dehighlight(menu, item);
  20614. }, function (fn) {
  20615. return fn();
  20616. });
  20617. });
  20618. }
  20619. detail.previewing.set(false);
  20620. },
  20621. onExecute: function (menu, item) {
  20622. return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) {
  20623. emitWith(typeahead, itemExecute(), { item: item });
  20624. return true;
  20625. });
  20626. },
  20627. onHover: function (menu, item) {
  20628. detail.previewing.set(false);
  20629. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20630. if (detail.model.populateFromBrowse) {
  20631. setValueFromItem(detail.model, input, item);
  20632. }
  20633. });
  20634. }
  20635. };
  20636. }
  20637. })]);
  20638. var Typeahead = composite({
  20639. name: 'Typeahead',
  20640. configFields: schema$g(),
  20641. partFields: parts$b(),
  20642. factory: make$3
  20643. });
  20644. var wrap = function (delegate) {
  20645. var toCached = function () {
  20646. return wrap(delegate.toCached());
  20647. };
  20648. var bindFuture = function (f) {
  20649. return wrap(delegate.bind(function (resA) {
  20650. return resA.fold(function (err) {
  20651. return Future.pure(Result.error(err));
  20652. }, function (a) {
  20653. return f(a);
  20654. });
  20655. }));
  20656. };
  20657. var bindResult = function (f) {
  20658. return wrap(delegate.map(function (resA) {
  20659. return resA.bind(f);
  20660. }));
  20661. };
  20662. var mapResult = function (f) {
  20663. return wrap(delegate.map(function (resA) {
  20664. return resA.map(f);
  20665. }));
  20666. };
  20667. var mapError = function (f) {
  20668. return wrap(delegate.map(function (resA) {
  20669. return resA.mapError(f);
  20670. }));
  20671. };
  20672. var foldResult = function (whenError, whenValue) {
  20673. return delegate.map(function (res) {
  20674. return res.fold(whenError, whenValue);
  20675. });
  20676. };
  20677. var withTimeout = function (timeout, errorThunk) {
  20678. return wrap(Future.nu(function (callback) {
  20679. var timedOut = false;
  20680. var timer = setTimeout(function () {
  20681. timedOut = true;
  20682. callback(Result.error(errorThunk()));
  20683. }, timeout);
  20684. delegate.get(function (result) {
  20685. if (!timedOut) {
  20686. clearTimeout(timer);
  20687. callback(result);
  20688. }
  20689. });
  20690. }));
  20691. };
  20692. return __assign(__assign({}, delegate), {
  20693. toCached: toCached,
  20694. bindFuture: bindFuture,
  20695. bindResult: bindResult,
  20696. mapResult: mapResult,
  20697. mapError: mapError,
  20698. foldResult: foldResult,
  20699. withTimeout: withTimeout
  20700. });
  20701. };
  20702. var nu$1 = function (worker) {
  20703. return wrap(Future.nu(worker));
  20704. };
  20705. var value = function (value) {
  20706. return wrap(Future.pure(Result.value(value)));
  20707. };
  20708. var error = function (error) {
  20709. return wrap(Future.pure(Result.error(error)));
  20710. };
  20711. var fromResult = function (result) {
  20712. return wrap(Future.pure(result));
  20713. };
  20714. var fromFuture = function (future) {
  20715. return wrap(future.map(Result.value));
  20716. };
  20717. var fromPromise = function (promise) {
  20718. return nu$1(function (completer) {
  20719. promise.then(function (value) {
  20720. completer(Result.value(value));
  20721. }, function (error) {
  20722. completer(Result.error(error));
  20723. });
  20724. });
  20725. };
  20726. var FutureResult = {
  20727. nu: nu$1,
  20728. wrap: wrap,
  20729. pure: value,
  20730. value: value,
  20731. error: error,
  20732. fromResult: fromResult,
  20733. fromFuture: fromFuture,
  20734. fromPromise: fromPromise
  20735. };
  20736. var separator$1 = { type: 'separator' };
  20737. var toMenuItem = function (target) {
  20738. return {
  20739. type: 'menuitem',
  20740. value: target.url,
  20741. text: target.title,
  20742. meta: { attach: target.attach },
  20743. onAction: noop
  20744. };
  20745. };
  20746. var staticMenuItem = function (title, url) {
  20747. return {
  20748. type: 'menuitem',
  20749. value: url,
  20750. text: title,
  20751. meta: { attach: undefined },
  20752. onAction: noop
  20753. };
  20754. };
  20755. var toMenuItems = function (targets) {
  20756. return map$2(targets, toMenuItem);
  20757. };
  20758. var filterLinkTargets = function (type, targets) {
  20759. return filter$2(targets, function (target) {
  20760. return target.type === type;
  20761. });
  20762. };
  20763. var filteredTargets = function (type, targets) {
  20764. return toMenuItems(filterLinkTargets(type, targets));
  20765. };
  20766. var headerTargets = function (linkInfo) {
  20767. return filteredTargets('header', linkInfo.targets);
  20768. };
  20769. var anchorTargets = function (linkInfo) {
  20770. return filteredTargets('anchor', linkInfo.targets);
  20771. };
  20772. var anchorTargetTop = function (linkInfo) {
  20773. return Optional.from(linkInfo.anchorTop).map(function (url) {
  20774. return staticMenuItem('<top>', url);
  20775. }).toArray();
  20776. };
  20777. var anchorTargetBottom = function (linkInfo) {
  20778. return Optional.from(linkInfo.anchorBottom).map(function (url) {
  20779. return staticMenuItem('<bottom>', url);
  20780. }).toArray();
  20781. };
  20782. var historyTargets = function (history) {
  20783. return map$2(history, function (url) {
  20784. return staticMenuItem(url, url);
  20785. });
  20786. };
  20787. var joinMenuLists = function (items) {
  20788. return foldl(items, function (a, b) {
  20789. var bothEmpty = a.length === 0 || b.length === 0;
  20790. return bothEmpty ? a.concat(b) : a.concat(separator$1, b);
  20791. }, []);
  20792. };
  20793. var filterByQuery = function (term, menuItems) {
  20794. var lowerCaseTerm = term.toLowerCase();
  20795. return filter$2(menuItems, function (item) {
  20796. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  20797. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  20798. });
  20799. };
  20800. var getItems = function (fileType, input, urlBackstage) {
  20801. var urlInputValue = Representing.getValue(input);
  20802. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  20803. var info = urlBackstage.getLinkInformation();
  20804. return info.fold(function () {
  20805. return [];
  20806. }, function (linkInfo) {
  20807. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  20808. return fileType === 'file' ? joinMenuLists([
  20809. history,
  20810. filterByQuery(term, headerTargets(linkInfo)),
  20811. filterByQuery(term, flatten([
  20812. anchorTargetTop(linkInfo),
  20813. anchorTargets(linkInfo),
  20814. anchorTargetBottom(linkInfo)
  20815. ]))
  20816. ]) : history;
  20817. });
  20818. };
  20819. var errorId = generate$6('aria-invalid');
  20820. var renderUrlInput = function (spec, backstage, urlBackstage) {
  20821. var _a;
  20822. var providersBackstage = backstage.shared.providers;
  20823. var updateHistory = function (component) {
  20824. var urlEntry = Representing.getValue(component);
  20825. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  20826. };
  20827. var pField = FormField.parts.field({
  20828. factory: Typeahead,
  20829. dismissOnBlur: true,
  20830. inputClasses: ['tox-textfield'],
  20831. sandboxClasses: ['tox-dialog__popups'],
  20832. inputAttributes: {
  20833. 'aria-errormessage': errorId,
  20834. 'type': 'url'
  20835. },
  20836. minChars: 0,
  20837. responseTime: 0,
  20838. fetch: function (input) {
  20839. var items = getItems(spec.filetype, input, urlBackstage);
  20840. var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  20841. return Future.pure(tdata);
  20842. },
  20843. getHotspot: function (comp) {
  20844. return memUrlBox.getOpt(comp);
  20845. },
  20846. onSetValue: function (comp, _newValue) {
  20847. if (comp.hasConfigured(Invalidating)) {
  20848. Invalidating.run(comp).get(noop);
  20849. }
  20850. },
  20851. typeaheadBehaviours: derive$1(flatten([
  20852. urlBackstage.getValidationHandler().map(function (handler) {
  20853. return Invalidating.config({
  20854. getRoot: function (comp) {
  20855. return parent(comp.element);
  20856. },
  20857. invalidClass: 'tox-control-wrap--status-invalid',
  20858. notify: {
  20859. onInvalid: function (comp, err) {
  20860. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  20861. set$7(invalidComp.element, 'title', providersBackstage.translate(err));
  20862. });
  20863. }
  20864. },
  20865. validator: {
  20866. validate: function (input) {
  20867. var urlEntry = Representing.getValue(input);
  20868. return FutureResult.nu(function (completer) {
  20869. handler({
  20870. type: spec.filetype,
  20871. url: urlEntry.value
  20872. }, function (validation) {
  20873. if (validation.status === 'invalid') {
  20874. var err = Result.error(validation.message);
  20875. completer(err);
  20876. } else {
  20877. var val = Result.value(validation.message);
  20878. completer(val);
  20879. }
  20880. });
  20881. });
  20882. },
  20883. validateOnLoad: false
  20884. }
  20885. });
  20886. }).toArray(),
  20887. [
  20888. Disabling.config({
  20889. disabled: function () {
  20890. return spec.disabled || providersBackstage.isDisabled();
  20891. }
  20892. }),
  20893. Tabstopping.config({}),
  20894. config('urlinput-events', flatten([
  20895. spec.filetype === 'file' ? [run$1(input(), function (comp) {
  20896. emitWith(comp, formChangeEvent, { name: spec.name });
  20897. })] : [],
  20898. [
  20899. run$1(change(), function (comp) {
  20900. emitWith(comp, formChangeEvent, { name: spec.name });
  20901. updateHistory(comp);
  20902. }),
  20903. run$1(postPaste(), function (comp) {
  20904. emitWith(comp, formChangeEvent, { name: spec.name });
  20905. updateHistory(comp);
  20906. })
  20907. ]
  20908. ]))
  20909. ]
  20910. ])),
  20911. eventOrder: (_a = {}, _a[input()] = [
  20912. 'streaming',
  20913. 'urlinput-events',
  20914. 'invalidating'
  20915. ], _a),
  20916. model: {
  20917. getDisplayText: function (itemData) {
  20918. return itemData.value;
  20919. },
  20920. selectsOver: false,
  20921. populateFromBrowse: false
  20922. },
  20923. markers: { openClass: 'tox-textfield--popup-open' },
  20924. lazySink: backstage.shared.getSink,
  20925. parts: { menu: part(false, 1, 'normal') },
  20926. onExecute: function (_menu, component, _entry) {
  20927. emitWith(component, formSubmitEvent, {});
  20928. },
  20929. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  20930. updateHistory(typeahead);
  20931. emitWith(typeahead, formChangeEvent, { name: spec.name });
  20932. }
  20933. });
  20934. var pLabel = spec.label.map(function (label) {
  20935. return renderLabel$2(label, providersBackstage);
  20936. });
  20937. var makeIcon = function (name, errId, icon, label) {
  20938. if (icon === void 0) {
  20939. icon = name;
  20940. }
  20941. if (label === void 0) {
  20942. label = name;
  20943. }
  20944. return render$3(icon, {
  20945. tag: 'div',
  20946. classes: [
  20947. 'tox-icon',
  20948. 'tox-control-wrap__status-icon-' + name
  20949. ],
  20950. attributes: __assign({
  20951. 'title': providersBackstage.translate(label),
  20952. 'aria-live': 'polite'
  20953. }, errId.fold(function () {
  20954. return {};
  20955. }, function (id) {
  20956. return { id: id };
  20957. }))
  20958. }, providersBackstage.icons);
  20959. };
  20960. var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
  20961. var memStatus = record({
  20962. dom: {
  20963. tag: 'div',
  20964. classes: ['tox-control-wrap__status-icon-wrap']
  20965. },
  20966. components: [memInvalidIcon.asSpec()]
  20967. });
  20968. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  20969. var browseUrlEvent = generate$6('browser.url.event');
  20970. var memUrlBox = record({
  20971. dom: {
  20972. tag: 'div',
  20973. classes: ['tox-control-wrap']
  20974. },
  20975. components: [
  20976. pField,
  20977. memStatus.asSpec()
  20978. ],
  20979. behaviours: derive$1([Disabling.config({
  20980. disabled: function () {
  20981. return spec.disabled || providersBackstage.isDisabled();
  20982. }
  20983. })])
  20984. });
  20985. var memUrlPickerButton = record(renderButton({
  20986. name: spec.name,
  20987. icon: Optional.some('browse'),
  20988. text: spec.label.getOr(''),
  20989. disabled: spec.disabled,
  20990. primary: false,
  20991. borderless: true
  20992. }, function (component) {
  20993. return emit(component, browseUrlEvent);
  20994. }, providersBackstage, [], ['tox-browse-url']));
  20995. var controlHWrapper = function () {
  20996. return {
  20997. dom: {
  20998. tag: 'div',
  20999. classes: ['tox-form__controls-h-stack']
  21000. },
  21001. components: flatten([
  21002. [memUrlBox.asSpec()],
  21003. optUrlPicker.map(function () {
  21004. return memUrlPickerButton.asSpec();
  21005. }).toArray()
  21006. ])
  21007. };
  21008. };
  21009. var openUrlPicker = function (comp) {
  21010. Composing.getCurrent(comp).each(function (field) {
  21011. var componentData = Representing.getValue(field);
  21012. var urlData = __assign({ fieldname: spec.name }, componentData);
  21013. optUrlPicker.each(function (picker) {
  21014. picker(urlData).get(function (chosenData) {
  21015. Representing.setValue(field, chosenData);
  21016. emitWith(comp, formChangeEvent, { name: spec.name });
  21017. });
  21018. });
  21019. });
  21020. };
  21021. return FormField.sketch({
  21022. dom: renderFormFieldDom(),
  21023. components: pLabel.toArray().concat([controlHWrapper()]),
  21024. fieldBehaviours: derive$1([
  21025. Disabling.config({
  21026. disabled: function () {
  21027. return spec.disabled || providersBackstage.isDisabled();
  21028. },
  21029. onDisabled: function (comp) {
  21030. FormField.getField(comp).each(Disabling.disable);
  21031. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  21032. },
  21033. onEnabled: function (comp) {
  21034. FormField.getField(comp).each(Disabling.enable);
  21035. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  21036. }
  21037. }),
  21038. receivingConfig(),
  21039. config('url-input-events', [run$1(browseUrlEvent, openUrlPicker)])
  21040. ])
  21041. });
  21042. };
  21043. var renderAlertBanner = function (spec, providersBackstage) {
  21044. return Container.sketch({
  21045. dom: {
  21046. tag: 'div',
  21047. attributes: { role: 'alert' },
  21048. classes: [
  21049. 'tox-notification',
  21050. 'tox-notification--in',
  21051. 'tox-notification--' + spec.level
  21052. ]
  21053. },
  21054. components: [
  21055. {
  21056. dom: {
  21057. tag: 'div',
  21058. classes: ['tox-notification__icon']
  21059. },
  21060. components: [Button.sketch({
  21061. dom: {
  21062. tag: 'button',
  21063. classes: [
  21064. 'tox-button',
  21065. 'tox-button--naked',
  21066. 'tox-button--icon'
  21067. ],
  21068. innerHtml: get$1(spec.icon, providersBackstage.icons),
  21069. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  21070. },
  21071. action: function (comp) {
  21072. emitWith(comp, formActionEvent, {
  21073. name: 'alert-banner',
  21074. value: spec.url
  21075. });
  21076. },
  21077. buttonBehaviours: derive$1([addFocusableBehaviour()])
  21078. })]
  21079. },
  21080. {
  21081. dom: {
  21082. tag: 'div',
  21083. classes: ['tox-notification__body'],
  21084. innerHtml: providersBackstage.translate(spec.text)
  21085. }
  21086. }
  21087. ]
  21088. });
  21089. };
  21090. var renderCheckbox = function (spec, providerBackstage) {
  21091. var repBehaviour = Representing.config({
  21092. store: {
  21093. mode: 'manual',
  21094. getValue: function (comp) {
  21095. var el = comp.element.dom;
  21096. return el.checked;
  21097. },
  21098. setValue: function (comp, value) {
  21099. var el = comp.element.dom;
  21100. el.checked = value;
  21101. }
  21102. }
  21103. });
  21104. var toggleCheckboxHandler = function (comp) {
  21105. comp.element.dom.click();
  21106. return Optional.some(true);
  21107. };
  21108. var pField = FormField.parts.field({
  21109. factory: { sketch: identity$1 },
  21110. dom: {
  21111. tag: 'input',
  21112. classes: ['tox-checkbox__input'],
  21113. attributes: { type: 'checkbox' }
  21114. },
  21115. behaviours: derive$1([
  21116. ComposingConfigs.self(),
  21117. Disabling.config({
  21118. disabled: function () {
  21119. return spec.disabled || providerBackstage.isDisabled();
  21120. }
  21121. }),
  21122. Tabstopping.config({}),
  21123. Focusing.config({}),
  21124. repBehaviour,
  21125. Keying.config({
  21126. mode: 'special',
  21127. onEnter: toggleCheckboxHandler,
  21128. onSpace: toggleCheckboxHandler,
  21129. stopSpaceKeyup: true
  21130. }),
  21131. config('checkbox-events', [run$1(change(), function (component, _) {
  21132. emitWith(component, formChangeEvent, { name: spec.name });
  21133. })])
  21134. ])
  21135. });
  21136. var pLabel = FormField.parts.label({
  21137. dom: {
  21138. tag: 'span',
  21139. classes: ['tox-checkbox__label'],
  21140. innerHtml: providerBackstage.translate(spec.label)
  21141. },
  21142. behaviours: derive$1([Unselecting.config({})])
  21143. });
  21144. var makeIcon = function (className) {
  21145. var iconName = className === 'checked' ? 'selected' : 'unselected';
  21146. return render$3(iconName, {
  21147. tag: 'span',
  21148. classes: [
  21149. 'tox-icon',
  21150. 'tox-checkbox-icon__' + className
  21151. ]
  21152. }, providerBackstage.icons);
  21153. };
  21154. var memIcons = record({
  21155. dom: {
  21156. tag: 'div',
  21157. classes: ['tox-checkbox__icons']
  21158. },
  21159. components: [
  21160. makeIcon('checked'),
  21161. makeIcon('unchecked')
  21162. ]
  21163. });
  21164. return FormField.sketch({
  21165. dom: {
  21166. tag: 'label',
  21167. classes: ['tox-checkbox']
  21168. },
  21169. components: [
  21170. pField,
  21171. memIcons.asSpec(),
  21172. pLabel
  21173. ],
  21174. fieldBehaviours: derive$1([
  21175. Disabling.config({
  21176. disabled: function () {
  21177. return spec.disabled || providerBackstage.isDisabled();
  21178. },
  21179. disableClass: 'tox-checkbox--disabled',
  21180. onDisabled: function (comp) {
  21181. FormField.getField(comp).each(Disabling.disable);
  21182. },
  21183. onEnabled: function (comp) {
  21184. FormField.getField(comp).each(Disabling.enable);
  21185. }
  21186. }),
  21187. receivingConfig()
  21188. ])
  21189. });
  21190. };
  21191. var renderHtmlPanel = function (spec) {
  21192. if (spec.presets === 'presentation') {
  21193. return Container.sketch({
  21194. dom: {
  21195. tag: 'div',
  21196. classes: ['tox-form__group'],
  21197. innerHtml: spec.html
  21198. }
  21199. });
  21200. } else {
  21201. return Container.sketch({
  21202. dom: {
  21203. tag: 'div',
  21204. classes: ['tox-form__group'],
  21205. innerHtml: spec.html,
  21206. attributes: { role: 'document' }
  21207. },
  21208. containerBehaviours: derive$1([
  21209. Tabstopping.config({}),
  21210. Focusing.config({})
  21211. ])
  21212. });
  21213. }
  21214. };
  21215. var make$2 = function (render) {
  21216. return function (parts, spec, backstage) {
  21217. return get$e(spec, 'name').fold(function () {
  21218. return render(spec, backstage);
  21219. }, function (fieldName) {
  21220. return parts.field(fieldName, render(spec, backstage));
  21221. });
  21222. };
  21223. };
  21224. var makeIframe = function (render) {
  21225. return function (parts, spec, backstage) {
  21226. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  21227. return make$2(render)(parts, iframeSpec, backstage);
  21228. };
  21229. };
  21230. var factories = {
  21231. bar: make$2(function (spec, backstage) {
  21232. return renderBar(spec, backstage.shared);
  21233. }),
  21234. collection: make$2(function (spec, backstage) {
  21235. return renderCollection(spec, backstage.shared.providers);
  21236. }),
  21237. alertbanner: make$2(function (spec, backstage) {
  21238. return renderAlertBanner(spec, backstage.shared.providers);
  21239. }),
  21240. input: make$2(function (spec, backstage) {
  21241. return renderInput(spec, backstage.shared.providers);
  21242. }),
  21243. textarea: make$2(function (spec, backstage) {
  21244. return renderTextarea(spec, backstage.shared.providers);
  21245. }),
  21246. label: make$2(function (spec, backstage) {
  21247. return renderLabel(spec, backstage.shared);
  21248. }),
  21249. iframe: makeIframe(function (spec, backstage) {
  21250. return renderIFrame(spec, backstage.shared.providers);
  21251. }),
  21252. button: make$2(function (spec, backstage) {
  21253. return renderDialogButton(spec, backstage.shared.providers);
  21254. }),
  21255. checkbox: make$2(function (spec, backstage) {
  21256. return renderCheckbox(spec, backstage.shared.providers);
  21257. }),
  21258. colorinput: make$2(function (spec, backstage) {
  21259. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  21260. }),
  21261. colorpicker: make$2(renderColorPicker),
  21262. dropzone: make$2(function (spec, backstage) {
  21263. return renderDropZone(spec, backstage.shared.providers);
  21264. }),
  21265. grid: make$2(function (spec, backstage) {
  21266. return renderGrid(spec, backstage.shared);
  21267. }),
  21268. listbox: make$2(function (spec, backstage) {
  21269. return renderListBox(spec, backstage);
  21270. }),
  21271. selectbox: make$2(function (spec, backstage) {
  21272. return renderSelectBox(spec, backstage.shared.providers);
  21273. }),
  21274. sizeinput: make$2(function (spec, backstage) {
  21275. return renderSizeInput(spec, backstage.shared.providers);
  21276. }),
  21277. urlinput: make$2(function (spec, backstage) {
  21278. return renderUrlInput(spec, backstage, backstage.urlinput);
  21279. }),
  21280. customeditor: make$2(renderCustomEditor),
  21281. htmlpanel: make$2(renderHtmlPanel),
  21282. imagetools: make$2(function (spec, backstage) {
  21283. return renderImageTools(spec, backstage.shared.providers);
  21284. }),
  21285. table: make$2(function (spec, backstage) {
  21286. return renderTable(spec, backstage.shared.providers);
  21287. }),
  21288. panel: make$2(function (spec, backstage) {
  21289. return renderPanel(spec, backstage);
  21290. })
  21291. };
  21292. var noFormParts = {
  21293. field: function (_name, spec) {
  21294. return spec;
  21295. }
  21296. };
  21297. var interpretInForm = function (parts, spec, oldBackstage) {
  21298. var newBackstage = deepMerge(oldBackstage, {
  21299. shared: {
  21300. interpreter: function (childSpec) {
  21301. return interpretParts(parts, childSpec, newBackstage);
  21302. }
  21303. }
  21304. });
  21305. return interpretParts(parts, spec, newBackstage);
  21306. };
  21307. var interpretParts = function (parts, spec, backstage) {
  21308. return get$e(factories, spec.type).fold(function () {
  21309. console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  21310. return spec;
  21311. }, function (factory) {
  21312. return factory(parts, spec, backstage);
  21313. });
  21314. };
  21315. var interpretWithoutForm = function (spec, backstage) {
  21316. var parts = noFormParts;
  21317. return interpretParts(parts, spec, backstage);
  21318. };
  21319. var bubbleAlignments$2 = {
  21320. valignCentre: [],
  21321. alignCentre: [],
  21322. alignLeft: [],
  21323. alignRight: [],
  21324. right: [],
  21325. left: [],
  21326. bottom: [],
  21327. top: []
  21328. };
  21329. var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  21330. var bubbleSize = 12;
  21331. var overrides = { maxHeightFunction: expandable$1() };
  21332. var editableAreaAnchor = function () {
  21333. return {
  21334. type: 'node',
  21335. root: getContentContainer(contentAreaElement()),
  21336. node: Optional.from(contentAreaElement()),
  21337. bubble: nu$5(bubbleSize, bubbleSize, bubbleAlignments$2),
  21338. layouts: {
  21339. onRtl: function () {
  21340. return [northeast];
  21341. },
  21342. onLtr: function () {
  21343. return [northwest];
  21344. }
  21345. },
  21346. overrides: overrides
  21347. };
  21348. };
  21349. var standardAnchor = function () {
  21350. return {
  21351. type: 'hotspot',
  21352. hotspot: lazyAnchorbar(),
  21353. bubble: nu$5(-bubbleSize, bubbleSize, bubbleAlignments$2),
  21354. layouts: {
  21355. onRtl: function () {
  21356. return [southeast$2];
  21357. },
  21358. onLtr: function () {
  21359. return [southwest$2];
  21360. }
  21361. },
  21362. overrides: overrides
  21363. };
  21364. };
  21365. return function () {
  21366. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  21367. };
  21368. };
  21369. var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  21370. var editableAreaAnchor = function () {
  21371. return {
  21372. type: 'node',
  21373. root: getContentContainer(contentAreaElement()),
  21374. node: Optional.from(contentAreaElement()),
  21375. layouts: {
  21376. onRtl: function () {
  21377. return [north];
  21378. },
  21379. onLtr: function () {
  21380. return [north];
  21381. }
  21382. }
  21383. };
  21384. };
  21385. var standardAnchor = function () {
  21386. return {
  21387. type: 'hotspot',
  21388. hotspot: lazyAnchorbar(),
  21389. layouts: {
  21390. onRtl: function () {
  21391. return [south$2];
  21392. },
  21393. onLtr: function () {
  21394. return [south$2];
  21395. }
  21396. }
  21397. };
  21398. };
  21399. return function () {
  21400. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  21401. };
  21402. };
  21403. var getCursorAnchor = function (editor, bodyElement) {
  21404. return function () {
  21405. return {
  21406. type: 'selection',
  21407. root: bodyElement(),
  21408. getSelection: function () {
  21409. var rng = editor.selection.getRng();
  21410. return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  21411. }
  21412. };
  21413. };
  21414. };
  21415. var getNodeAnchor$1 = function (bodyElement) {
  21416. return function (element) {
  21417. return {
  21418. type: 'node',
  21419. root: bodyElement(),
  21420. node: element
  21421. };
  21422. };
  21423. };
  21424. var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
  21425. var useFixedToolbarContainer = useFixedContainer(editor);
  21426. var bodyElement = function () {
  21427. return SugarElement.fromDom(editor.getBody());
  21428. };
  21429. var contentAreaElement = function () {
  21430. return SugarElement.fromDom(editor.getContentAreaContainer());
  21431. };
  21432. var lazyUseEditableAreaAnchor = function () {
  21433. return useFixedToolbarContainer || !isToolbarTop();
  21434. };
  21435. return {
  21436. inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  21437. banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  21438. cursor: getCursorAnchor(editor, bodyElement),
  21439. node: getNodeAnchor$1(bodyElement)
  21440. };
  21441. };
  21442. var colorPicker = function (editor) {
  21443. return function (callback, value) {
  21444. var dialog = colorPickerDialog(editor);
  21445. dialog(callback, value);
  21446. };
  21447. };
  21448. var hasCustomColors = function (editor) {
  21449. return function () {
  21450. return hasCustomColors$1(editor);
  21451. };
  21452. };
  21453. var getColors = function (editor) {
  21454. return function () {
  21455. return getColors$2(editor);
  21456. };
  21457. };
  21458. var getColorCols = function (editor) {
  21459. return function () {
  21460. return getColorCols$1(editor);
  21461. };
  21462. };
  21463. var ColorInputBackstage = function (editor) {
  21464. return {
  21465. colorPicker: colorPicker(editor),
  21466. hasCustomColors: hasCustomColors(editor),
  21467. getColors: getColors(editor),
  21468. getColorCols: getColorCols(editor)
  21469. };
  21470. };
  21471. var isDraggableModal = function (editor) {
  21472. return function () {
  21473. return isDraggableModal$1(editor);
  21474. };
  21475. };
  21476. var DialogBackstage = function (editor) {
  21477. return { isDraggableModal: isDraggableModal(editor) };
  21478. };
  21479. var HeaderBackstage = function (editor) {
  21480. var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  21481. return {
  21482. isPositionedAtTop: function () {
  21483. return mode.get() === 'top';
  21484. },
  21485. getDockingMode: mode.get,
  21486. setDockingMode: mode.set
  21487. };
  21488. };
  21489. var defaultStyleFormats = [
  21490. {
  21491. title: 'Headings',
  21492. items: [
  21493. {
  21494. title: 'Heading 1',
  21495. format: 'h1'
  21496. },
  21497. {
  21498. title: 'Heading 2',
  21499. format: 'h2'
  21500. },
  21501. {
  21502. title: 'Heading 3',
  21503. format: 'h3'
  21504. },
  21505. {
  21506. title: 'Heading 4',
  21507. format: 'h4'
  21508. },
  21509. {
  21510. title: 'Heading 5',
  21511. format: 'h5'
  21512. },
  21513. {
  21514. title: 'Heading 6',
  21515. format: 'h6'
  21516. }
  21517. ]
  21518. },
  21519. {
  21520. title: 'Inline',
  21521. items: [
  21522. {
  21523. title: 'Bold',
  21524. format: 'bold'
  21525. },
  21526. {
  21527. title: 'Italic',
  21528. format: 'italic'
  21529. },
  21530. {
  21531. title: 'Underline',
  21532. format: 'underline'
  21533. },
  21534. {
  21535. title: 'Strikethrough',
  21536. format: 'strikethrough'
  21537. },
  21538. {
  21539. title: 'Superscript',
  21540. format: 'superscript'
  21541. },
  21542. {
  21543. title: 'Subscript',
  21544. format: 'subscript'
  21545. },
  21546. {
  21547. title: 'Code',
  21548. format: 'code'
  21549. }
  21550. ]
  21551. },
  21552. {
  21553. title: 'Blocks',
  21554. items: [
  21555. {
  21556. title: 'Paragraph',
  21557. format: 'p'
  21558. },
  21559. {
  21560. title: 'Blockquote',
  21561. format: 'blockquote'
  21562. },
  21563. {
  21564. title: 'Div',
  21565. format: 'div'
  21566. },
  21567. {
  21568. title: 'Pre',
  21569. format: 'pre'
  21570. }
  21571. ]
  21572. },
  21573. {
  21574. title: 'Align',
  21575. items: [
  21576. {
  21577. title: 'Left',
  21578. format: 'alignleft'
  21579. },
  21580. {
  21581. title: 'Center',
  21582. format: 'aligncenter'
  21583. },
  21584. {
  21585. title: 'Right',
  21586. format: 'alignright'
  21587. },
  21588. {
  21589. title: 'Justify',
  21590. format: 'alignjustify'
  21591. }
  21592. ]
  21593. }
  21594. ];
  21595. var isNestedFormat = function (format) {
  21596. return has$2(format, 'items');
  21597. };
  21598. var isBlockFormat = function (format) {
  21599. return has$2(format, 'block');
  21600. };
  21601. var isInlineFormat = function (format) {
  21602. return has$2(format, 'inline');
  21603. };
  21604. var isSelectorFormat = function (format) {
  21605. return has$2(format, 'selector');
  21606. };
  21607. var mapFormats = function (userFormats) {
  21608. return foldl(userFormats, function (acc, fmt) {
  21609. if (isNestedFormat(fmt)) {
  21610. var result = mapFormats(fmt.items);
  21611. return {
  21612. customFormats: acc.customFormats.concat(result.customFormats),
  21613. formats: acc.formats.concat([{
  21614. title: fmt.title,
  21615. items: result.formats
  21616. }])
  21617. };
  21618. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  21619. var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
  21620. var formatNameWithPrefix = 'custom-' + formatName;
  21621. return {
  21622. customFormats: acc.customFormats.concat([{
  21623. name: formatNameWithPrefix,
  21624. format: fmt
  21625. }]),
  21626. formats: acc.formats.concat([{
  21627. title: fmt.title,
  21628. format: formatNameWithPrefix,
  21629. icon: fmt.icon
  21630. }])
  21631. };
  21632. } else {
  21633. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  21634. }
  21635. }, {
  21636. customFormats: [],
  21637. formats: []
  21638. });
  21639. };
  21640. var registerCustomFormats = function (editor, userFormats) {
  21641. var result = mapFormats(userFormats);
  21642. var registerFormats = function (customFormats) {
  21643. each$1(customFormats, function (fmt) {
  21644. if (!editor.formatter.has(fmt.name)) {
  21645. editor.formatter.register(fmt.name, fmt.format);
  21646. }
  21647. });
  21648. };
  21649. if (editor.formatter) {
  21650. registerFormats(result.customFormats);
  21651. } else {
  21652. editor.on('init', function () {
  21653. registerFormats(result.customFormats);
  21654. });
  21655. }
  21656. return result.formats;
  21657. };
  21658. var getStyleFormats = function (editor) {
  21659. return getUserStyleFormats(editor).map(function (userFormats) {
  21660. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  21661. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  21662. }).getOr(defaultStyleFormats);
  21663. };
  21664. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  21665. var formatterSpec = {
  21666. type: 'formatter',
  21667. isSelected: isSelectedFor(item.format),
  21668. getStylePreview: getPreviewFor(item.format)
  21669. };
  21670. return deepMerge(item, formatterSpec);
  21671. };
  21672. var register$8 = function (editor, formats, isSelectedFor, getPreviewFor) {
  21673. var enrichSupported = function (item) {
  21674. return processBasic(item, isSelectedFor, getPreviewFor);
  21675. };
  21676. var enrichMenu = function (item) {
  21677. var submenuSpec = { type: 'submenu' };
  21678. return deepMerge(item, submenuSpec);
  21679. };
  21680. var enrichCustom = function (item) {
  21681. var formatName = isString(item.name) ? item.name : generate$6(item.title);
  21682. var formatNameWithPrefix = 'custom-' + formatName;
  21683. var customSpec = {
  21684. type: 'formatter',
  21685. format: formatNameWithPrefix,
  21686. isSelected: isSelectedFor(formatNameWithPrefix),
  21687. getStylePreview: getPreviewFor(formatNameWithPrefix)
  21688. };
  21689. var newItem = deepMerge(item, customSpec);
  21690. editor.formatter.register(formatName, newItem);
  21691. return newItem;
  21692. };
  21693. var doEnrich = function (items) {
  21694. return map$2(items, function (item) {
  21695. var keys$1 = keys(item);
  21696. if (hasNonNullableKey(item, 'items')) {
  21697. var newItems = doEnrich(item.items);
  21698. return deepMerge(enrichMenu(item), { getStyleItems: constant$1(newItems) });
  21699. } else if (hasNonNullableKey(item, 'format')) {
  21700. return enrichSupported(item);
  21701. } else if (keys$1.length === 1 && contains$2(keys$1, 'title')) {
  21702. return deepMerge(item, { type: 'separator' });
  21703. } else {
  21704. return enrichCustom(item);
  21705. }
  21706. });
  21707. };
  21708. return doEnrich(formats);
  21709. };
  21710. var init$8 = function (editor) {
  21711. var isSelectedFor = function (format) {
  21712. return function () {
  21713. return editor.formatter.match(format);
  21714. };
  21715. };
  21716. var getPreviewFor = function (format) {
  21717. return function () {
  21718. var fmt = editor.formatter.get(format);
  21719. return fmt !== undefined ? Optional.some({
  21720. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  21721. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  21722. }) : Optional.none();
  21723. };
  21724. };
  21725. var flatten = function (fmt) {
  21726. var subs = fmt.items;
  21727. return subs !== undefined && subs.length > 0 ? bind$3(subs, flatten) : [fmt.format];
  21728. };
  21729. var settingsFormats = Cell([]);
  21730. var settingsFlattenedFormats = Cell([]);
  21731. var eventsFormats = Cell([]);
  21732. var eventsFlattenedFormats = Cell([]);
  21733. var replaceSettings = Cell(false);
  21734. editor.on('PreInit', function (_e) {
  21735. var formats = getStyleFormats(editor);
  21736. var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor);
  21737. settingsFormats.set(enriched);
  21738. settingsFlattenedFormats.set(bind$3(enriched, flatten));
  21739. });
  21740. editor.on('addStyleModifications', function (e) {
  21741. var modifications = register$8(editor, e.items, isSelectedFor, getPreviewFor);
  21742. eventsFormats.set(modifications);
  21743. replaceSettings.set(e.replace);
  21744. eventsFlattenedFormats.set(bind$3(modifications, flatten));
  21745. });
  21746. var getData = function () {
  21747. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  21748. var fromEvents = eventsFormats.get();
  21749. return fromSettings.concat(fromEvents);
  21750. };
  21751. var getFlattenedKeys = function () {
  21752. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  21753. var fromEvents = eventsFlattenedFormats.get();
  21754. return fromSettings.concat(fromEvents);
  21755. };
  21756. return {
  21757. getData: getData,
  21758. getFlattenedKeys: getFlattenedKeys
  21759. };
  21760. };
  21761. var isElement = function (node) {
  21762. return isNonNullable(node) && node.nodeType === 1;
  21763. };
  21764. var trim = global$6.trim;
  21765. var hasContentEditableState = function (value) {
  21766. return function (node) {
  21767. if (isElement(node)) {
  21768. if (node.contentEditable === value) {
  21769. return true;
  21770. }
  21771. if (node.getAttribute('data-mce-contenteditable') === value) {
  21772. return true;
  21773. }
  21774. }
  21775. return false;
  21776. };
  21777. };
  21778. var isContentEditableTrue = hasContentEditableState('true');
  21779. var isContentEditableFalse = hasContentEditableState('false');
  21780. var create = function (type, title, url, level, attach) {
  21781. return {
  21782. type: type,
  21783. title: title,
  21784. url: url,
  21785. level: level,
  21786. attach: attach
  21787. };
  21788. };
  21789. var isChildOfContentEditableTrue = function (node) {
  21790. while (node = node.parentNode) {
  21791. var value = node.contentEditable;
  21792. if (value && value !== 'inherit') {
  21793. return isContentEditableTrue(node);
  21794. }
  21795. }
  21796. return false;
  21797. };
  21798. var select = function (selector, root) {
  21799. return map$2(descendants(SugarElement.fromDom(root), selector), function (element) {
  21800. return element.dom;
  21801. });
  21802. };
  21803. var getElementText = function (elm) {
  21804. return elm.innerText || elm.textContent;
  21805. };
  21806. var getOrGenerateId = function (elm) {
  21807. return elm.id ? elm.id : generate$6('h');
  21808. };
  21809. var isAnchor = function (elm) {
  21810. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  21811. };
  21812. var isValidAnchor = function (elm) {
  21813. return isAnchor(elm) && isEditable(elm);
  21814. };
  21815. var isHeader = function (elm) {
  21816. return elm && /^(H[1-6])$/.test(elm.nodeName);
  21817. };
  21818. var isEditable = function (elm) {
  21819. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  21820. };
  21821. var isValidHeader = function (elm) {
  21822. return isHeader(elm) && isEditable(elm);
  21823. };
  21824. var getLevel = function (elm) {
  21825. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  21826. };
  21827. var headerTarget = function (elm) {
  21828. var headerId = getOrGenerateId(elm);
  21829. var attach = function () {
  21830. elm.id = headerId;
  21831. };
  21832. return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  21833. };
  21834. var anchorTarget = function (elm) {
  21835. var anchorId = elm.id || elm.name;
  21836. var anchorText = getElementText(elm);
  21837. return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  21838. };
  21839. var getHeaderTargets = function (elms) {
  21840. return map$2(filter$2(elms, isValidHeader), headerTarget);
  21841. };
  21842. var getAnchorTargets = function (elms) {
  21843. return map$2(filter$2(elms, isValidAnchor), anchorTarget);
  21844. };
  21845. var getTargetElements = function (elm) {
  21846. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  21847. return elms;
  21848. };
  21849. var hasTitle = function (target) {
  21850. return trim(target.title).length > 0;
  21851. };
  21852. var find = function (elm) {
  21853. var elms = getTargetElements(elm);
  21854. return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  21855. };
  21856. var LinkTargets = { find: find };
  21857. var STORAGE_KEY = 'tinymce-url-history';
  21858. var HISTORY_LENGTH = 5;
  21859. var isHttpUrl = function (url) {
  21860. return isString(url) && /^https?/.test(url);
  21861. };
  21862. var isArrayOfUrl = function (a) {
  21863. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  21864. };
  21865. var isRecordOfUrlArray = function (r) {
  21866. return isObject(r) && find$4(r, function (value) {
  21867. return !isArrayOfUrl(value);
  21868. }).isNone();
  21869. };
  21870. var getAllHistory = function () {
  21871. var unparsedHistory = global$9.getItem(STORAGE_KEY);
  21872. if (unparsedHistory === null) {
  21873. return {};
  21874. }
  21875. var history;
  21876. try {
  21877. history = JSON.parse(unparsedHistory);
  21878. } catch (e) {
  21879. if (e instanceof SyntaxError) {
  21880. console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  21881. return {};
  21882. }
  21883. throw e;
  21884. }
  21885. if (!isRecordOfUrlArray(history)) {
  21886. console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  21887. return {};
  21888. }
  21889. return history;
  21890. };
  21891. var setAllHistory = function (history) {
  21892. if (!isRecordOfUrlArray(history)) {
  21893. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  21894. }
  21895. global$9.setItem(STORAGE_KEY, JSON.stringify(history));
  21896. };
  21897. var getHistory = function (fileType) {
  21898. var history = getAllHistory();
  21899. return get$e(history, fileType).getOr([]);
  21900. };
  21901. var addToHistory = function (url, fileType) {
  21902. if (!isHttpUrl(url)) {
  21903. return;
  21904. }
  21905. var history = getAllHistory();
  21906. var items = get$e(history, fileType).getOr([]);
  21907. var itemsWithoutUrl = filter$2(items, function (item) {
  21908. return item !== url;
  21909. });
  21910. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  21911. setAllHistory(history);
  21912. };
  21913. var isTruthy = function (value) {
  21914. return !!value;
  21915. };
  21916. var makeMap = function (value) {
  21917. return map(global$6.makeMap(value, /[, ]/), isTruthy);
  21918. };
  21919. var getPicker = function (editor) {
  21920. return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
  21921. };
  21922. var getPickerTypes = function (editor) {
  21923. var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
  21924. var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
  21925. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  21926. return getPicker(editor).fold(never, function (_picker) {
  21927. return optTypes.fold(always, function (types) {
  21928. return keys(types).length > 0 ? types : false;
  21929. });
  21930. });
  21931. };
  21932. var getPickerSetting = function (editor, filetype) {
  21933. var pickerTypes = getPickerTypes(editor);
  21934. if (isBoolean(pickerTypes)) {
  21935. return pickerTypes ? getPicker(editor) : Optional.none();
  21936. } else {
  21937. return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
  21938. }
  21939. };
  21940. var getUrlPicker = function (editor, filetype) {
  21941. return getPickerSetting(editor, filetype).map(function (picker) {
  21942. return function (entry) {
  21943. return Future.nu(function (completer) {
  21944. var handler = function (value, meta) {
  21945. if (!isString(value)) {
  21946. throw new Error('Expected value to be string');
  21947. }
  21948. if (meta !== undefined && !isObject(meta)) {
  21949. throw new Error('Expected meta to be a object');
  21950. }
  21951. var r = {
  21952. value: value,
  21953. meta: meta
  21954. };
  21955. completer(r);
  21956. };
  21957. var meta = __assign({
  21958. filetype: filetype,
  21959. fieldname: entry.fieldname
  21960. }, Optional.from(entry.meta).getOr({}));
  21961. picker.call(editor, handler, entry.value, meta);
  21962. });
  21963. };
  21964. });
  21965. };
  21966. var getTextSetting = function (value) {
  21967. return Optional.from(value).filter(isString).getOrUndefined();
  21968. };
  21969. var getLinkInformation = function (editor) {
  21970. if (noTypeaheadUrls(editor)) {
  21971. return Optional.none();
  21972. }
  21973. return Optional.some({
  21974. targets: LinkTargets.find(editor.getBody()),
  21975. anchorTop: getTextSetting(getAnchorTop(editor)),
  21976. anchorBottom: getTextSetting(getAnchorBottom(editor))
  21977. });
  21978. };
  21979. var getValidationHandler = function (editor) {
  21980. return Optional.from(getFilePickerValidatorHandler(editor));
  21981. };
  21982. var UrlInputBackstage = function (editor) {
  21983. return {
  21984. getHistory: getHistory,
  21985. addToHistory: addToHistory,
  21986. getLinkInformation: function () {
  21987. return getLinkInformation(editor);
  21988. },
  21989. getValidationHandler: function () {
  21990. return getValidationHandler(editor);
  21991. },
  21992. getUrlPicker: function (filetype) {
  21993. return getUrlPicker(editor, filetype);
  21994. }
  21995. };
  21996. };
  21997. var init$7 = function (sink, editor, lazyAnchorbar) {
  21998. var contextMenuState = Cell(false);
  21999. var toolbar = HeaderBackstage(editor);
  22000. var backstage = {
  22001. shared: {
  22002. providers: {
  22003. icons: function () {
  22004. return editor.ui.registry.getAll().icons;
  22005. },
  22006. menuItems: function () {
  22007. return editor.ui.registry.getAll().menuItems;
  22008. },
  22009. translate: global$f.translate,
  22010. isDisabled: function () {
  22011. return editor.mode.isReadOnly() || editor.ui.isDisabled();
  22012. },
  22013. getSetting: editor.getParam.bind(editor)
  22014. },
  22015. interpreter: function (s) {
  22016. return interpretWithoutForm(s, backstage);
  22017. },
  22018. anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  22019. header: toolbar,
  22020. getSink: function () {
  22021. return Result.value(sink);
  22022. }
  22023. },
  22024. urlinput: UrlInputBackstage(editor),
  22025. styleselect: init$8(editor),
  22026. colorinput: ColorInputBackstage(editor),
  22027. dialog: DialogBackstage(editor),
  22028. isContextMenuOpen: function () {
  22029. return contextMenuState.get();
  22030. },
  22031. setContextMenuState: function (state) {
  22032. return contextMenuState.set(state);
  22033. }
  22034. };
  22035. return backstage;
  22036. };
  22037. var setup$b = function (editor, mothership, uiMothership) {
  22038. var broadcastEvent = function (name, evt) {
  22039. each$1([
  22040. mothership,
  22041. uiMothership
  22042. ], function (ship) {
  22043. ship.broadcastEvent(name, evt);
  22044. });
  22045. };
  22046. var broadcastOn = function (channel, message) {
  22047. each$1([
  22048. mothership,
  22049. uiMothership
  22050. ], function (ship) {
  22051. ship.broadcastOn([channel], message);
  22052. });
  22053. };
  22054. var fireDismissPopups = function (evt) {
  22055. return broadcastOn(dismissPopups(), { target: evt.target });
  22056. };
  22057. var onTouchstart = bind(SugarElement.fromDom(document), 'touchstart', fireDismissPopups);
  22058. var onTouchmove = bind(SugarElement.fromDom(document), 'touchmove', function (evt) {
  22059. return broadcastEvent(documentTouchmove(), evt);
  22060. });
  22061. var onTouchend = bind(SugarElement.fromDom(document), 'touchend', function (evt) {
  22062. return broadcastEvent(documentTouchend(), evt);
  22063. });
  22064. var onMousedown = bind(SugarElement.fromDom(document), 'mousedown', fireDismissPopups);
  22065. var onMouseup = bind(SugarElement.fromDom(document), 'mouseup', function (evt) {
  22066. if (evt.raw.button === 0) {
  22067. broadcastOn(mouseReleased(), { target: evt.target });
  22068. }
  22069. });
  22070. var onContentClick = function (raw) {
  22071. return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
  22072. };
  22073. var onContentMouseup = function (raw) {
  22074. if (raw.button === 0) {
  22075. broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
  22076. }
  22077. };
  22078. var onContentMousedown = function () {
  22079. each$1(editor.editorManager.get(), function (loopEditor) {
  22080. if (editor !== loopEditor) {
  22081. loopEditor.fire('DismissPopups', { relatedTarget: editor });
  22082. }
  22083. });
  22084. };
  22085. var onWindowScroll = function (evt) {
  22086. return broadcastEvent(windowScroll(), fromRawEvent(evt));
  22087. };
  22088. var onWindowResize = function (evt) {
  22089. broadcastOn(repositionPopups(), {});
  22090. broadcastEvent(windowResize(), fromRawEvent(evt));
  22091. };
  22092. var onEditorResize = function () {
  22093. return broadcastOn(repositionPopups(), {});
  22094. };
  22095. var onEditorProgress = function (evt) {
  22096. if (evt.state) {
  22097. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
  22098. }
  22099. };
  22100. var onDismissPopups = function (event) {
  22101. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
  22102. };
  22103. editor.on('PostRender', function () {
  22104. editor.on('click', onContentClick);
  22105. editor.on('tap', onContentClick);
  22106. editor.on('mouseup', onContentMouseup);
  22107. editor.on('mousedown', onContentMousedown);
  22108. editor.on('ScrollWindow', onWindowScroll);
  22109. editor.on('ResizeWindow', onWindowResize);
  22110. editor.on('ResizeEditor', onEditorResize);
  22111. editor.on('AfterProgressState', onEditorProgress);
  22112. editor.on('DismissPopups', onDismissPopups);
  22113. });
  22114. editor.on('remove', function () {
  22115. editor.off('click', onContentClick);
  22116. editor.off('tap', onContentClick);
  22117. editor.off('mouseup', onContentMouseup);
  22118. editor.off('mousedown', onContentMousedown);
  22119. editor.off('ScrollWindow', onWindowScroll);
  22120. editor.off('ResizeWindow', onWindowResize);
  22121. editor.off('ResizeEditor', onEditorResize);
  22122. editor.off('AfterProgressState', onEditorProgress);
  22123. editor.off('DismissPopups', onDismissPopups);
  22124. onMousedown.unbind();
  22125. onTouchstart.unbind();
  22126. onTouchmove.unbind();
  22127. onTouchend.unbind();
  22128. onMouseup.unbind();
  22129. });
  22130. editor.on('detach', function () {
  22131. detachSystem(mothership);
  22132. detachSystem(uiMothership);
  22133. mothership.destroy();
  22134. uiMothership.destroy();
  22135. });
  22136. };
  22137. var parts$a = AlloyParts;
  22138. var partType = PartType;
  22139. var schema$f = constant$1([
  22140. defaulted('shell', false),
  22141. required$1('makeItem'),
  22142. defaulted('setupItem', noop),
  22143. SketchBehaviours.field('listBehaviours', [Replacing])
  22144. ]);
  22145. var customListDetail = function () {
  22146. return { behaviours: derive$1([Replacing.config({})]) };
  22147. };
  22148. var itemsPart = optional({
  22149. name: 'items',
  22150. overrides: customListDetail
  22151. });
  22152. var parts$9 = constant$1([itemsPart]);
  22153. var name = constant$1('CustomList');
  22154. var factory$d = function (detail, components, _spec, _external) {
  22155. var setItems = function (list, items) {
  22156. getListContainer(list).fold(function () {
  22157. console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  22158. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  22159. }, function (container) {
  22160. var itemComps = Replacing.contents(container);
  22161. var numListsRequired = items.length;
  22162. var numListsToAdd = numListsRequired - itemComps.length;
  22163. var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function () {
  22164. return detail.makeItem();
  22165. }) : [];
  22166. var itemsToRemove = itemComps.slice(numListsRequired);
  22167. each$1(itemsToRemove, function (item) {
  22168. return Replacing.remove(container, item);
  22169. });
  22170. each$1(itemsToAdd, function (item) {
  22171. return Replacing.append(container, item);
  22172. });
  22173. var builtLists = Replacing.contents(container);
  22174. each$1(builtLists, function (item, i) {
  22175. detail.setupItem(list, item, items[i], i);
  22176. });
  22177. });
  22178. };
  22179. var extra = detail.shell ? {
  22180. behaviours: [Replacing.config({})],
  22181. components: []
  22182. } : {
  22183. behaviours: [],
  22184. components: components
  22185. };
  22186. var getListContainer = function (component) {
  22187. return detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
  22188. };
  22189. return {
  22190. uid: detail.uid,
  22191. dom: detail.dom,
  22192. components: extra.components,
  22193. behaviours: augment(detail.listBehaviours, extra.behaviours),
  22194. apis: { setItems: setItems }
  22195. };
  22196. };
  22197. var CustomList = composite({
  22198. name: name(),
  22199. configFields: schema$f(),
  22200. partFields: parts$9(),
  22201. factory: factory$d,
  22202. apis: {
  22203. setItems: function (apis, list, items) {
  22204. apis.setItems(list, items);
  22205. }
  22206. }
  22207. });
  22208. var schema$e = constant$1([
  22209. required$1('dom'),
  22210. defaulted('shell', true),
  22211. field('toolbarBehaviours', [Replacing])
  22212. ]);
  22213. var enhanceGroups = function () {
  22214. return { behaviours: derive$1([Replacing.config({})]) };
  22215. };
  22216. var parts$8 = constant$1([optional({
  22217. name: 'groups',
  22218. overrides: enhanceGroups
  22219. })]);
  22220. var factory$c = function (detail, components, _spec, _externals) {
  22221. var setGroups = function (toolbar, groups) {
  22222. getGroupContainer(toolbar).fold(function () {
  22223. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  22224. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  22225. }, function (container) {
  22226. Replacing.set(container, groups);
  22227. });
  22228. };
  22229. var getGroupContainer = function (component) {
  22230. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  22231. };
  22232. var extra = detail.shell ? {
  22233. behaviours: [Replacing.config({})],
  22234. components: []
  22235. } : {
  22236. behaviours: [],
  22237. components: components
  22238. };
  22239. return {
  22240. uid: detail.uid,
  22241. dom: detail.dom,
  22242. components: extra.components,
  22243. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  22244. apis: { setGroups: setGroups },
  22245. domModification: { attributes: { role: 'group' } }
  22246. };
  22247. };
  22248. var Toolbar = composite({
  22249. name: 'Toolbar',
  22250. configFields: schema$e(),
  22251. partFields: parts$8(),
  22252. factory: factory$c,
  22253. apis: {
  22254. setGroups: function (apis, toolbar, groups) {
  22255. apis.setGroups(toolbar, groups);
  22256. }
  22257. }
  22258. });
  22259. var setup$a = noop;
  22260. var isDocked$2 = never;
  22261. var getBehaviours$1 = constant$1([]);
  22262. var StaticHeader = /*#__PURE__*/Object.freeze({
  22263. __proto__: null,
  22264. setup: setup$a,
  22265. isDocked: isDocked$2,
  22266. getBehaviours: getBehaviours$1
  22267. });
  22268. var getOffsetParent = function (element) {
  22269. var isFixed = is(getRaw(element, 'position'), 'fixed');
  22270. var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
  22271. return offsetParent$1.orThunk(function () {
  22272. var marker = SugarElement.fromTag('span');
  22273. return parent(element).bind(function (parent) {
  22274. append$2(parent, marker);
  22275. var offsetParent$1 = offsetParent(marker);
  22276. remove$7(marker);
  22277. return offsetParent$1;
  22278. });
  22279. });
  22280. };
  22281. var getOrigin = function (element) {
  22282. return getOffsetParent(element).map(absolute$3).getOrThunk(function () {
  22283. return SugarPosition(0, 0);
  22284. });
  22285. };
  22286. var morphAdt = Adt.generate([
  22287. { static: [] },
  22288. { absolute: ['positionCss'] },
  22289. { fixed: ['positionCss'] }
  22290. ]);
  22291. var appear = function (component, contextualInfo) {
  22292. var elem = component.element;
  22293. add$2(elem, contextualInfo.transitionClass);
  22294. remove$3(elem, contextualInfo.fadeOutClass);
  22295. add$2(elem, contextualInfo.fadeInClass);
  22296. contextualInfo.onShow(component);
  22297. };
  22298. var disappear = function (component, contextualInfo) {
  22299. var elem = component.element;
  22300. add$2(elem, contextualInfo.transitionClass);
  22301. remove$3(elem, contextualInfo.fadeInClass);
  22302. add$2(elem, contextualInfo.fadeOutClass);
  22303. contextualInfo.onHide(component);
  22304. };
  22305. var isPartiallyVisible = function (box, viewport) {
  22306. return box.y < viewport.bottom && box.bottom > viewport.y;
  22307. };
  22308. var isTopCompletelyVisible = function (box, viewport) {
  22309. return box.y >= viewport.y;
  22310. };
  22311. var isBottomCompletelyVisible = function (box, viewport) {
  22312. return box.bottom <= viewport.bottom;
  22313. };
  22314. var isVisibleForModes = function (modes, box, viewport) {
  22315. return forall(modes, function (mode) {
  22316. switch (mode) {
  22317. case 'bottom':
  22318. return isBottomCompletelyVisible(box, viewport);
  22319. case 'top':
  22320. return isTopCompletelyVisible(box, viewport);
  22321. }
  22322. });
  22323. };
  22324. var getPrior = function (elem, state) {
  22325. return state.getInitialPos().map(function (pos) {
  22326. return bounds(pos.bounds.x, pos.bounds.y, get$7(elem), get$8(elem));
  22327. });
  22328. };
  22329. var storePrior = function (elem, box, state) {
  22330. state.setInitialPos({
  22331. style: getAllRaw(elem),
  22332. position: get$a(elem, 'position') || 'static',
  22333. bounds: box
  22334. });
  22335. };
  22336. var revertToOriginal = function (elem, box, state) {
  22337. return state.getInitialPos().bind(function (position) {
  22338. state.clearInitialPos();
  22339. switch (position.position) {
  22340. case 'static':
  22341. return Optional.some(morphAdt.static());
  22342. case 'absolute':
  22343. var offsetBox_1 = getOffsetParent(elem).map(box$1).getOrThunk(function () {
  22344. return box$1(body());
  22345. });
  22346. return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$e(position.style, 'left').map(function (_left) {
  22347. return box.x - offsetBox_1.x;
  22348. }), get$e(position.style, 'top').map(function (_top) {
  22349. return box.y - offsetBox_1.y;
  22350. }), get$e(position.style, 'right').map(function (_right) {
  22351. return offsetBox_1.right - box.right;
  22352. }), get$e(position.style, 'bottom').map(function (_bottom) {
  22353. return offsetBox_1.bottom - box.bottom;
  22354. }))));
  22355. default:
  22356. return Optional.none();
  22357. }
  22358. });
  22359. };
  22360. var morphToOriginal = function (elem, viewport, state) {
  22361. return getPrior(elem, state).filter(function (box) {
  22362. return isVisibleForModes(state.getModes(), box, viewport);
  22363. }).bind(function (box) {
  22364. return revertToOriginal(elem, box, state);
  22365. });
  22366. };
  22367. var morphToFixed = function (elem, viewport, state) {
  22368. var box = box$1(elem);
  22369. if (!isVisibleForModes(state.getModes(), box, viewport)) {
  22370. storePrior(elem, box, state);
  22371. var winBox = win();
  22372. var left = box.x - winBox.x;
  22373. var top_1 = viewport.y - winBox.y;
  22374. var bottom = winBox.bottom - viewport.bottom;
  22375. var isTop = box.y <= viewport.y;
  22376. return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none())));
  22377. } else {
  22378. return Optional.none();
  22379. }
  22380. };
  22381. var getMorph = function (component, viewport, state) {
  22382. var elem = component.element;
  22383. var isDocked = is(getRaw(elem, 'position'), 'fixed');
  22384. return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  22385. };
  22386. var getMorphToOriginal = function (component, state) {
  22387. var elem = component.element;
  22388. return getPrior(elem, state).bind(function (box) {
  22389. return revertToOriginal(elem, box, state);
  22390. });
  22391. };
  22392. var morphToStatic = function (component, config) {
  22393. each$1([
  22394. 'left',
  22395. 'right',
  22396. 'top',
  22397. 'bottom',
  22398. 'position'
  22399. ], function (prop) {
  22400. return remove$1(component.element, prop);
  22401. });
  22402. config.onUndocked(component);
  22403. };
  22404. var morphToCoord = function (component, config, position) {
  22405. applyPositionCss(component.element, position);
  22406. var method = position.position === 'fixed' ? config.onDocked : config.onUndocked;
  22407. method(component);
  22408. };
  22409. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  22410. if (morphToDocked === void 0) {
  22411. morphToDocked = false;
  22412. }
  22413. config.contextual.each(function (contextInfo) {
  22414. contextInfo.lazyContext(component).each(function (box) {
  22415. var isVisible = isPartiallyVisible(box, viewport);
  22416. if (isVisible !== state.isVisible()) {
  22417. state.setVisible(isVisible);
  22418. if (morphToDocked && !isVisible) {
  22419. add$1(component.element, [contextInfo.fadeOutClass]);
  22420. contextInfo.onHide(component);
  22421. } else {
  22422. var method = isVisible ? appear : disappear;
  22423. method(component, contextInfo);
  22424. }
  22425. }
  22426. });
  22427. });
  22428. };
  22429. var refreshInternal = function (component, config, state) {
  22430. var viewport = config.lazyViewport(component);
  22431. var isDocked = state.isDocked();
  22432. if (isDocked) {
  22433. updateVisibility(component, config, state, viewport);
  22434. }
  22435. getMorph(component, viewport, state).each(function (morph) {
  22436. state.setDocked(!isDocked);
  22437. morph.fold(function () {
  22438. return morphToStatic(component, config);
  22439. }, function (position) {
  22440. return morphToCoord(component, config, position);
  22441. }, function (position) {
  22442. updateVisibility(component, config, state, viewport, true);
  22443. morphToCoord(component, config, position);
  22444. });
  22445. });
  22446. };
  22447. var resetInternal = function (component, config, state) {
  22448. var elem = component.element;
  22449. state.setDocked(false);
  22450. getMorphToOriginal(component, state).each(function (morph) {
  22451. morph.fold(function () {
  22452. return morphToStatic(component, config);
  22453. }, function (position) {
  22454. return morphToCoord(component, config, position);
  22455. }, noop);
  22456. });
  22457. state.setVisible(true);
  22458. config.contextual.each(function (contextInfo) {
  22459. remove$2(elem, [
  22460. contextInfo.fadeInClass,
  22461. contextInfo.fadeOutClass,
  22462. contextInfo.transitionClass
  22463. ]);
  22464. contextInfo.onShow(component);
  22465. });
  22466. refresh$4(component, config, state);
  22467. };
  22468. var refresh$4 = function (component, config, state) {
  22469. if (component.getSystem().isConnected()) {
  22470. refreshInternal(component, config, state);
  22471. }
  22472. };
  22473. var reset = function (component, config, state) {
  22474. if (state.isDocked()) {
  22475. resetInternal(component, config, state);
  22476. }
  22477. };
  22478. var isDocked$1 = function (component, config, state) {
  22479. return state.isDocked();
  22480. };
  22481. var setModes = function (component, config, state, modes) {
  22482. return state.setModes(modes);
  22483. };
  22484. var getModes = function (component, config, state) {
  22485. return state.getModes();
  22486. };
  22487. var DockingApis = /*#__PURE__*/Object.freeze({
  22488. __proto__: null,
  22489. refresh: refresh$4,
  22490. reset: reset,
  22491. isDocked: isDocked$1,
  22492. getModes: getModes,
  22493. setModes: setModes
  22494. });
  22495. var events$5 = function (dockInfo, dockState) {
  22496. return derive$2([
  22497. runOnSource(transitionend(), function (component, simulatedEvent) {
  22498. dockInfo.contextual.each(function (contextInfo) {
  22499. if (has(component.element, contextInfo.transitionClass)) {
  22500. remove$2(component.element, [
  22501. contextInfo.transitionClass,
  22502. contextInfo.fadeInClass
  22503. ]);
  22504. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  22505. notify(component);
  22506. }
  22507. simulatedEvent.stop();
  22508. });
  22509. }),
  22510. run$1(windowScroll(), function (component, _) {
  22511. refresh$4(component, dockInfo, dockState);
  22512. }),
  22513. run$1(windowResize(), function (component, _) {
  22514. reset(component, dockInfo, dockState);
  22515. })
  22516. ]);
  22517. };
  22518. var ActiveDocking = /*#__PURE__*/Object.freeze({
  22519. __proto__: null,
  22520. events: events$5
  22521. });
  22522. var DockingSchema = [
  22523. optionObjOf('contextual', [
  22524. requiredString('fadeInClass'),
  22525. requiredString('fadeOutClass'),
  22526. requiredString('transitionClass'),
  22527. requiredFunction('lazyContext'),
  22528. onHandler('onShow'),
  22529. onHandler('onShown'),
  22530. onHandler('onHide'),
  22531. onHandler('onHidden')
  22532. ]),
  22533. defaultedFunction('lazyViewport', win),
  22534. defaultedArrayOf('modes', [
  22535. 'top',
  22536. 'bottom'
  22537. ], string),
  22538. onHandler('onDocked'),
  22539. onHandler('onUndocked')
  22540. ];
  22541. var init$6 = function (spec) {
  22542. var docked = Cell(false);
  22543. var visible = Cell(true);
  22544. var initialBounds = value$1();
  22545. var modes = Cell(spec.modes);
  22546. var readState = function () {
  22547. return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
  22548. };
  22549. return nu$8({
  22550. isDocked: docked.get,
  22551. setDocked: docked.set,
  22552. getInitialPos: initialBounds.get,
  22553. setInitialPos: initialBounds.set,
  22554. clearInitialPos: initialBounds.clear,
  22555. isVisible: visible.get,
  22556. setVisible: visible.set,
  22557. getModes: modes.get,
  22558. setModes: modes.set,
  22559. readState: readState
  22560. });
  22561. };
  22562. var DockingState = /*#__PURE__*/Object.freeze({
  22563. __proto__: null,
  22564. init: init$6
  22565. });
  22566. var Docking = create$7({
  22567. fields: DockingSchema,
  22568. name: 'docking',
  22569. active: ActiveDocking,
  22570. apis: DockingApis,
  22571. state: DockingState
  22572. });
  22573. var toolbarHeightChange = constant$1(generate$6('toolbar-height-change'));
  22574. var visibility = {
  22575. fadeInClass: 'tox-editor-dock-fadein',
  22576. fadeOutClass: 'tox-editor-dock-fadeout',
  22577. transitionClass: 'tox-editor-dock-transition'
  22578. };
  22579. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  22580. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  22581. var scrollFromBehindHeader = function (e, containerHeader) {
  22582. var doc = owner$4(containerHeader);
  22583. var viewHeight = doc.dom.defaultView.innerHeight;
  22584. var scrollPos = get$6(doc);
  22585. var markerElement = SugarElement.fromDom(e.elm);
  22586. var markerPos = absolute$2(markerElement);
  22587. var markerHeight = get$8(markerElement);
  22588. var markerTop = markerPos.y;
  22589. var markerBottom = markerTop + markerHeight;
  22590. var editorHeaderPos = absolute$3(containerHeader);
  22591. var editorHeaderHeight = get$8(containerHeader);
  22592. var editorHeaderTop = editorHeaderPos.top;
  22593. var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  22594. var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
  22595. var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
  22596. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  22597. to(scrollPos.left, markerTop - editorHeaderHeight, doc);
  22598. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  22599. var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  22600. to(scrollPos.left, y, doc);
  22601. }
  22602. };
  22603. var isDockedMode = function (header, mode) {
  22604. return contains$2(Docking.getModes(header), mode);
  22605. };
  22606. var updateIframeContentFlow = function (header) {
  22607. var getOccupiedHeight = function (elm) {
  22608. return getOuter$1(elm) + (parseInt(get$a(elm, 'margin-top'), 10) || 0) + (parseInt(get$a(elm, 'margin-bottom'), 10) || 0);
  22609. };
  22610. var elm = header.element;
  22611. parent(elm).each(function (parentElem) {
  22612. var padding = 'padding-' + Docking.getModes(header)[0];
  22613. if (Docking.isDocked(header)) {
  22614. var parentWidth = get$7(parentElem);
  22615. set$6(elm, 'width', parentWidth + 'px');
  22616. set$6(parentElem, padding, getOccupiedHeight(elm) + 'px');
  22617. } else {
  22618. remove$1(elm, 'width');
  22619. remove$1(parentElem, padding);
  22620. }
  22621. });
  22622. };
  22623. var updateSinkVisibility = function (sinkElem, visible) {
  22624. if (visible) {
  22625. remove$3(sinkElem, visibility.fadeOutClass);
  22626. add$1(sinkElem, [
  22627. visibility.transitionClass,
  22628. visibility.fadeInClass
  22629. ]);
  22630. } else {
  22631. remove$3(sinkElem, visibility.fadeInClass);
  22632. add$1(sinkElem, [
  22633. visibility.fadeOutClass,
  22634. visibility.transitionClass
  22635. ]);
  22636. }
  22637. };
  22638. var updateEditorClasses = function (editor, docked) {
  22639. var editorContainer = SugarElement.fromDom(editor.getContainer());
  22640. if (docked) {
  22641. add$2(editorContainer, editorStickyOnClass);
  22642. remove$3(editorContainer, editorStickyOffClass);
  22643. } else {
  22644. add$2(editorContainer, editorStickyOffClass);
  22645. remove$3(editorContainer, editorStickyOnClass);
  22646. }
  22647. };
  22648. var restoreFocus = function (headerElem, focusedElem) {
  22649. var ownerDoc = owner$4(focusedElem);
  22650. active(ownerDoc).filter(function (activeElm) {
  22651. return !eq(focusedElem, activeElm);
  22652. }).filter(function (activeElm) {
  22653. return eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm);
  22654. }).each(function () {
  22655. return focus$3(focusedElem);
  22656. });
  22657. };
  22658. var findFocusedElem = function (rootElm, lazySink) {
  22659. return search(rootElm).orThunk(function () {
  22660. return lazySink().toOptional().bind(function (sink) {
  22661. return search(sink.element);
  22662. });
  22663. });
  22664. };
  22665. var setup$9 = function (editor, sharedBackstage, lazyHeader) {
  22666. if (!editor.inline) {
  22667. if (!sharedBackstage.header.isPositionedAtTop()) {
  22668. editor.on('ResizeEditor', function () {
  22669. lazyHeader().each(Docking.reset);
  22670. });
  22671. }
  22672. editor.on('ResizeWindow ResizeEditor', function () {
  22673. lazyHeader().each(updateIframeContentFlow);
  22674. });
  22675. editor.on('SkinLoaded', function () {
  22676. lazyHeader().each(function (comp) {
  22677. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  22678. });
  22679. });
  22680. editor.on('FullscreenStateChanged', function () {
  22681. lazyHeader().each(Docking.reset);
  22682. });
  22683. }
  22684. editor.on('AfterScrollIntoView', function (e) {
  22685. lazyHeader().each(function (header) {
  22686. Docking.refresh(header);
  22687. var headerElem = header.element;
  22688. if (isVisible(headerElem)) {
  22689. scrollFromBehindHeader(e, headerElem);
  22690. }
  22691. });
  22692. });
  22693. editor.on('PostRender', function () {
  22694. updateEditorClasses(editor, false);
  22695. });
  22696. };
  22697. var isDocked = function (lazyHeader) {
  22698. return lazyHeader().map(Docking.isDocked).getOr(false);
  22699. };
  22700. var getIframeBehaviours = function () {
  22701. var _a;
  22702. return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
  22703. };
  22704. var getBehaviours = function (editor, sharedBackstage) {
  22705. var focusedElm = value$1();
  22706. var lazySink = sharedBackstage.getSink;
  22707. var runOnSinkElement = function (f) {
  22708. lazySink().each(function (sink) {
  22709. return f(sink.element);
  22710. });
  22711. };
  22712. var onDockingSwitch = function (comp) {
  22713. if (!editor.inline) {
  22714. updateIframeContentFlow(comp);
  22715. }
  22716. updateEditorClasses(editor, Docking.isDocked(comp));
  22717. comp.getSystem().broadcastOn([repositionPopups()], {});
  22718. lazySink().each(function (sink) {
  22719. return sink.getSystem().broadcastOn([repositionPopups()], {});
  22720. });
  22721. };
  22722. var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  22723. return __spreadArray([
  22724. Focusing.config({}),
  22725. Docking.config({
  22726. contextual: __assign({
  22727. lazyContext: function (comp) {
  22728. var headerHeight = getOuter$1(comp.element);
  22729. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  22730. var box = box$1(SugarElement.fromDom(container));
  22731. var boxHeight = box.height - headerHeight;
  22732. var topBound = box.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  22733. return Optional.some(bounds(box.x, topBound, box.width, boxHeight));
  22734. },
  22735. onShow: function () {
  22736. runOnSinkElement(function (elem) {
  22737. return updateSinkVisibility(elem, true);
  22738. });
  22739. },
  22740. onShown: function (comp) {
  22741. runOnSinkElement(function (elem) {
  22742. return remove$2(elem, [
  22743. visibility.transitionClass,
  22744. visibility.fadeInClass
  22745. ]);
  22746. });
  22747. focusedElm.get().each(function (elem) {
  22748. restoreFocus(comp.element, elem);
  22749. focusedElm.clear();
  22750. });
  22751. },
  22752. onHide: function (comp) {
  22753. findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
  22754. runOnSinkElement(function (elem) {
  22755. return updateSinkVisibility(elem, false);
  22756. });
  22757. },
  22758. onHidden: function () {
  22759. runOnSinkElement(function (elem) {
  22760. return remove$2(elem, [visibility.transitionClass]);
  22761. });
  22762. }
  22763. }, visibility),
  22764. lazyViewport: function (comp) {
  22765. var win$1 = win();
  22766. var offset = getStickyToolbarOffset(editor);
  22767. var top = win$1.y + (isDockedMode(comp, 'top') ? offset : 0);
  22768. var height = win$1.height - (isDockedMode(comp, 'bottom') ? offset : 0);
  22769. return bounds(win$1.x, top, win$1.width, height);
  22770. },
  22771. modes: [sharedBackstage.header.getDockingMode()],
  22772. onDocked: onDockingSwitch,
  22773. onUndocked: onDockingSwitch
  22774. })
  22775. ], additionalBehaviours);
  22776. };
  22777. var StickyHeader = /*#__PURE__*/Object.freeze({
  22778. __proto__: null,
  22779. setup: setup$9,
  22780. isDocked: isDocked,
  22781. getBehaviours: getBehaviours
  22782. });
  22783. var renderHeader = function (spec) {
  22784. var editor = spec.editor;
  22785. var getBehaviours$2 = spec.sticky ? getBehaviours : getBehaviours$1;
  22786. return {
  22787. uid: spec.uid,
  22788. dom: spec.dom,
  22789. components: spec.components,
  22790. behaviours: derive$1(getBehaviours$2(editor, spec.sharedBackstage))
  22791. };
  22792. };
  22793. var groupToolbarButtonSchema = objOf([
  22794. requiredString('type'),
  22795. requiredOf('items', oneOf([
  22796. arrOfObj([
  22797. requiredString('name'),
  22798. requiredArrayOf('items', string)
  22799. ]),
  22800. string
  22801. ]))
  22802. ].concat(baseToolbarButtonFields));
  22803. var createGroupToolbarButton = function (spec) {
  22804. return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  22805. };
  22806. var baseMenuButtonFields = [
  22807. optionString('text'),
  22808. optionString('tooltip'),
  22809. optionString('icon'),
  22810. requiredFunction('fetch'),
  22811. defaultedFunction('onSetup', function () {
  22812. return noop;
  22813. })
  22814. ];
  22815. var MenuButtonSchema = objOf(__spreadArray([requiredString('type')], baseMenuButtonFields));
  22816. var createMenuButton = function (spec) {
  22817. return asRaw('menubutton', MenuButtonSchema, spec);
  22818. };
  22819. var splitButtonSchema = objOf([
  22820. requiredString('type'),
  22821. optionString('tooltip'),
  22822. optionString('icon'),
  22823. optionString('text'),
  22824. optionFunction('select'),
  22825. requiredFunction('fetch'),
  22826. defaultedFunction('onSetup', function () {
  22827. return noop;
  22828. }),
  22829. defaultedStringEnum('presets', 'normal', [
  22830. 'normal',
  22831. 'color',
  22832. 'listpreview'
  22833. ]),
  22834. defaulted('columns', 1),
  22835. requiredFunction('onAction'),
  22836. requiredFunction('onItemAction')
  22837. ]);
  22838. var createSplitButton = function (spec) {
  22839. return asRaw('SplitButton', splitButtonSchema, spec);
  22840. };
  22841. var factory$b = function (detail, spec) {
  22842. var setMenus = function (comp, menus) {
  22843. var newMenus = map$2(menus, function (m) {
  22844. var buttonSpec = {
  22845. type: 'menubutton',
  22846. text: m.text,
  22847. fetch: function (callback) {
  22848. callback(m.getItems());
  22849. }
  22850. };
  22851. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  22852. return formatError(errInfo);
  22853. }).getOrDie();
  22854. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
  22855. });
  22856. Replacing.set(comp, newMenus);
  22857. };
  22858. var apis = {
  22859. focus: Keying.focusIn,
  22860. setMenus: setMenus
  22861. };
  22862. return {
  22863. uid: detail.uid,
  22864. dom: detail.dom,
  22865. components: [],
  22866. behaviours: derive$1([
  22867. Replacing.config({}),
  22868. config('menubar-events', [
  22869. runOnAttached(function (component) {
  22870. detail.onSetup(component);
  22871. }),
  22872. run$1(mouseover(), function (comp, se) {
  22873. descendant(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) {
  22874. closest$1(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) {
  22875. if (!eq(activeButton, hoveredButton)) {
  22876. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  22877. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  22878. Dropdown.expand(hoveredComp);
  22879. Dropdown.close(activeComp);
  22880. Focusing.focus(hoveredComp);
  22881. });
  22882. });
  22883. }
  22884. });
  22885. });
  22886. }),
  22887. run$1(focusShifted(), function (comp, se) {
  22888. se.event.prevFocus.bind(function (prev) {
  22889. return comp.getSystem().getByDom(prev).toOptional();
  22890. }).each(function (prev) {
  22891. se.event.newFocus.bind(function (nu) {
  22892. return comp.getSystem().getByDom(nu).toOptional();
  22893. }).each(function (nu) {
  22894. if (Dropdown.isOpen(prev)) {
  22895. Dropdown.expand(nu);
  22896. Dropdown.close(prev);
  22897. }
  22898. });
  22899. });
  22900. })
  22901. ]),
  22902. Keying.config({
  22903. mode: 'flow',
  22904. selector: '.' + 'tox-mbtn',
  22905. onEscape: function (comp) {
  22906. detail.onEscape(comp);
  22907. return Optional.some(true);
  22908. }
  22909. }),
  22910. Tabstopping.config({})
  22911. ]),
  22912. apis: apis,
  22913. domModification: { attributes: { role: 'menubar' } }
  22914. };
  22915. };
  22916. var SilverMenubar = single({
  22917. factory: factory$b,
  22918. name: 'silver.Menubar',
  22919. configFields: [
  22920. required$1('dom'),
  22921. required$1('uid'),
  22922. required$1('onEscape'),
  22923. required$1('backstage'),
  22924. defaulted('onSetup', noop)
  22925. ],
  22926. apis: {
  22927. focus: function (apis, comp) {
  22928. apis.focus(comp);
  22929. },
  22930. setMenus: function (apis, comp, menus) {
  22931. apis.setMenus(comp, menus);
  22932. }
  22933. }
  22934. });
  22935. var getAnimationRoot = function (component, slideConfig) {
  22936. return slideConfig.getAnimationRoot.fold(function () {
  22937. return component.element;
  22938. }, function (get) {
  22939. return get(component);
  22940. });
  22941. };
  22942. var getDimensionProperty = function (slideConfig) {
  22943. return slideConfig.dimension.property;
  22944. };
  22945. var getDimension = function (slideConfig, elem) {
  22946. return slideConfig.dimension.getDimension(elem);
  22947. };
  22948. var disableTransitions = function (component, slideConfig) {
  22949. var root = getAnimationRoot(component, slideConfig);
  22950. remove$2(root, [
  22951. slideConfig.shrinkingClass,
  22952. slideConfig.growingClass
  22953. ]);
  22954. };
  22955. var setShrunk = function (component, slideConfig) {
  22956. remove$3(component.element, slideConfig.openClass);
  22957. add$2(component.element, slideConfig.closedClass);
  22958. set$6(component.element, getDimensionProperty(slideConfig), '0px');
  22959. reflow(component.element);
  22960. };
  22961. var setGrown = function (component, slideConfig) {
  22962. remove$3(component.element, slideConfig.closedClass);
  22963. add$2(component.element, slideConfig.openClass);
  22964. remove$1(component.element, getDimensionProperty(slideConfig));
  22965. };
  22966. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  22967. slideState.setCollapsed();
  22968. set$6(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  22969. reflow(component.element);
  22970. disableTransitions(component, slideConfig);
  22971. setShrunk(component, slideConfig);
  22972. slideConfig.onStartShrink(component);
  22973. slideConfig.onShrunk(component);
  22974. };
  22975. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  22976. var size = calculatedSize.getOrThunk(function () {
  22977. return getDimension(slideConfig, component.element);
  22978. });
  22979. slideState.setCollapsed();
  22980. set$6(component.element, getDimensionProperty(slideConfig), size);
  22981. reflow(component.element);
  22982. var root = getAnimationRoot(component, slideConfig);
  22983. remove$3(root, slideConfig.growingClass);
  22984. add$2(root, slideConfig.shrinkingClass);
  22985. setShrunk(component, slideConfig);
  22986. slideConfig.onStartShrink(component);
  22987. };
  22988. var doStartSmartShrink = function (component, slideConfig, slideState) {
  22989. var size = getDimension(slideConfig, component.element);
  22990. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  22991. shrinker(component, slideConfig, slideState, Optional.some(size));
  22992. };
  22993. var doStartGrow = function (component, slideConfig, slideState) {
  22994. var root = getAnimationRoot(component, slideConfig);
  22995. var wasShrinking = has(root, slideConfig.shrinkingClass);
  22996. var beforeSize = getDimension(slideConfig, component.element);
  22997. setGrown(component, slideConfig);
  22998. var fullSize = getDimension(slideConfig, component.element);
  22999. var startPartialGrow = function () {
  23000. set$6(component.element, getDimensionProperty(slideConfig), beforeSize);
  23001. reflow(component.element);
  23002. };
  23003. var startCompleteGrow = function () {
  23004. setShrunk(component, slideConfig);
  23005. };
  23006. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  23007. setStartSize();
  23008. remove$3(root, slideConfig.shrinkingClass);
  23009. add$2(root, slideConfig.growingClass);
  23010. setGrown(component, slideConfig);
  23011. set$6(component.element, getDimensionProperty(slideConfig), fullSize);
  23012. slideState.setExpanded();
  23013. slideConfig.onStartGrow(component);
  23014. };
  23015. var refresh$3 = function (component, slideConfig, slideState) {
  23016. if (slideState.isExpanded()) {
  23017. remove$1(component.element, getDimensionProperty(slideConfig));
  23018. var fullSize = getDimension(slideConfig, component.element);
  23019. set$6(component.element, getDimensionProperty(slideConfig), fullSize);
  23020. }
  23021. };
  23022. var grow = function (component, slideConfig, slideState) {
  23023. if (!slideState.isExpanded()) {
  23024. doStartGrow(component, slideConfig, slideState);
  23025. }
  23026. };
  23027. var shrink = function (component, slideConfig, slideState) {
  23028. if (slideState.isExpanded()) {
  23029. doStartSmartShrink(component, slideConfig, slideState);
  23030. }
  23031. };
  23032. var immediateShrink = function (component, slideConfig, slideState) {
  23033. if (slideState.isExpanded()) {
  23034. doImmediateShrink(component, slideConfig, slideState);
  23035. }
  23036. };
  23037. var hasGrown = function (component, slideConfig, slideState) {
  23038. return slideState.isExpanded();
  23039. };
  23040. var hasShrunk = function (component, slideConfig, slideState) {
  23041. return slideState.isCollapsed();
  23042. };
  23043. var isGrowing = function (component, slideConfig, _slideState) {
  23044. var root = getAnimationRoot(component, slideConfig);
  23045. return has(root, slideConfig.growingClass) === true;
  23046. };
  23047. var isShrinking = function (component, slideConfig, _slideState) {
  23048. var root = getAnimationRoot(component, slideConfig);
  23049. return has(root, slideConfig.shrinkingClass) === true;
  23050. };
  23051. var isTransitioning = function (component, slideConfig, slideState) {
  23052. return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  23053. };
  23054. var toggleGrow = function (component, slideConfig, slideState) {
  23055. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  23056. f(component, slideConfig, slideState);
  23057. };
  23058. var SlidingApis = /*#__PURE__*/Object.freeze({
  23059. __proto__: null,
  23060. refresh: refresh$3,
  23061. grow: grow,
  23062. shrink: shrink,
  23063. immediateShrink: immediateShrink,
  23064. hasGrown: hasGrown,
  23065. hasShrunk: hasShrunk,
  23066. isGrowing: isGrowing,
  23067. isShrinking: isShrinking,
  23068. isTransitioning: isTransitioning,
  23069. toggleGrow: toggleGrow,
  23070. disableTransitions: disableTransitions
  23071. });
  23072. var exhibit = function (base, slideConfig, _slideState) {
  23073. var expanded = slideConfig.expanded;
  23074. return expanded ? nu$7({
  23075. classes: [slideConfig.openClass],
  23076. styles: {}
  23077. }) : nu$7({
  23078. classes: [slideConfig.closedClass],
  23079. styles: wrap$1(slideConfig.dimension.property, '0px')
  23080. });
  23081. };
  23082. var events$4 = function (slideConfig, slideState) {
  23083. return derive$2([runOnSource(transitionend(), function (component, simulatedEvent) {
  23084. var raw = simulatedEvent.event.raw;
  23085. if (raw.propertyName === slideConfig.dimension.property) {
  23086. disableTransitions(component, slideConfig);
  23087. if (slideState.isExpanded()) {
  23088. remove$1(component.element, slideConfig.dimension.property);
  23089. }
  23090. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  23091. notify(component);
  23092. }
  23093. })]);
  23094. };
  23095. var ActiveSliding = /*#__PURE__*/Object.freeze({
  23096. __proto__: null,
  23097. exhibit: exhibit,
  23098. events: events$4
  23099. });
  23100. var SlidingSchema = [
  23101. required$1('closedClass'),
  23102. required$1('openClass'),
  23103. required$1('shrinkingClass'),
  23104. required$1('growingClass'),
  23105. option('getAnimationRoot'),
  23106. onHandler('onShrunk'),
  23107. onHandler('onStartShrink'),
  23108. onHandler('onGrown'),
  23109. onHandler('onStartGrow'),
  23110. defaulted('expanded', false),
  23111. requiredOf('dimension', choose$1('property', {
  23112. width: [
  23113. output$1('property', 'width'),
  23114. output$1('getDimension', function (elem) {
  23115. return get$7(elem) + 'px';
  23116. })
  23117. ],
  23118. height: [
  23119. output$1('property', 'height'),
  23120. output$1('getDimension', function (elem) {
  23121. return get$8(elem) + 'px';
  23122. })
  23123. ]
  23124. }))
  23125. ];
  23126. var init$5 = function (spec) {
  23127. var state = Cell(spec.expanded);
  23128. var readState = function () {
  23129. return 'expanded: ' + state.get();
  23130. };
  23131. return nu$8({
  23132. isExpanded: function () {
  23133. return state.get() === true;
  23134. },
  23135. isCollapsed: function () {
  23136. return state.get() === false;
  23137. },
  23138. setCollapsed: curry(state.set, false),
  23139. setExpanded: curry(state.set, true),
  23140. readState: readState
  23141. });
  23142. };
  23143. var SlidingState = /*#__PURE__*/Object.freeze({
  23144. __proto__: null,
  23145. init: init$5
  23146. });
  23147. var Sliding = create$7({
  23148. fields: SlidingSchema,
  23149. name: 'sliding',
  23150. active: ActiveSliding,
  23151. apis: SlidingApis,
  23152. state: SlidingState
  23153. });
  23154. var owner = 'container';
  23155. var schema$d = [field('slotBehaviours', [])];
  23156. var getPartName = function (name) {
  23157. return '<alloy.field.' + name + '>';
  23158. };
  23159. var sketch = function (sSpec) {
  23160. var parts = function () {
  23161. var record = [];
  23162. var slot = function (name, config) {
  23163. record.push(name);
  23164. return generateOne$1(owner, getPartName(name), config);
  23165. };
  23166. return {
  23167. slot: slot,
  23168. record: constant$1(record)
  23169. };
  23170. }();
  23171. var spec = sSpec(parts);
  23172. var partNames = parts.record();
  23173. var fieldParts = map$2(partNames, function (n) {
  23174. return required({
  23175. name: n,
  23176. pname: getPartName(n)
  23177. });
  23178. });
  23179. return composite$1(owner, schema$d, fieldParts, make$1, spec);
  23180. };
  23181. var make$1 = function (detail, components) {
  23182. var getSlotNames = function (_) {
  23183. return getAllPartNames(detail);
  23184. };
  23185. var getSlot = function (container, key) {
  23186. return getPart(container, detail, key);
  23187. };
  23188. var onSlot = function (f, def) {
  23189. return function (container, key) {
  23190. return getPart(container, detail, key).map(function (slot) {
  23191. return f(slot, key);
  23192. }).getOr(def);
  23193. };
  23194. };
  23195. var onSlots = function (f) {
  23196. return function (container, keys) {
  23197. each$1(keys, function (key) {
  23198. return f(container, key);
  23199. });
  23200. };
  23201. };
  23202. var doShowing = function (comp, _key) {
  23203. return get$c(comp.element, 'aria-hidden') !== 'true';
  23204. };
  23205. var doShow = function (comp, key) {
  23206. if (!doShowing(comp)) {
  23207. var element = comp.element;
  23208. remove$1(element, 'display');
  23209. remove$6(element, 'aria-hidden');
  23210. emitWith(comp, slotVisibility(), {
  23211. name: key,
  23212. visible: true
  23213. });
  23214. }
  23215. };
  23216. var doHide = function (comp, key) {
  23217. if (doShowing(comp)) {
  23218. var element = comp.element;
  23219. set$6(element, 'display', 'none');
  23220. set$7(element, 'aria-hidden', 'true');
  23221. emitWith(comp, slotVisibility(), {
  23222. name: key,
  23223. visible: false
  23224. });
  23225. }
  23226. };
  23227. var isShowing = onSlot(doShowing, false);
  23228. var hideSlot = onSlot(doHide);
  23229. var hideSlots = onSlots(hideSlot);
  23230. var hideAllSlots = function (container) {
  23231. return hideSlots(container, getSlotNames());
  23232. };
  23233. var showSlot = onSlot(doShow);
  23234. var apis = {
  23235. getSlotNames: getSlotNames,
  23236. getSlot: getSlot,
  23237. isShowing: isShowing,
  23238. hideSlot: hideSlot,
  23239. hideAllSlots: hideAllSlots,
  23240. showSlot: showSlot
  23241. };
  23242. return {
  23243. uid: detail.uid,
  23244. dom: detail.dom,
  23245. components: components,
  23246. behaviours: get$2(detail.slotBehaviours),
  23247. apis: apis
  23248. };
  23249. };
  23250. var slotApis = map({
  23251. getSlotNames: function (apis, c) {
  23252. return apis.getSlotNames(c);
  23253. },
  23254. getSlot: function (apis, c, key) {
  23255. return apis.getSlot(c, key);
  23256. },
  23257. isShowing: function (apis, c, key) {
  23258. return apis.isShowing(c, key);
  23259. },
  23260. hideSlot: function (apis, c, key) {
  23261. return apis.hideSlot(c, key);
  23262. },
  23263. hideAllSlots: function (apis, c) {
  23264. return apis.hideAllSlots(c);
  23265. },
  23266. showSlot: function (apis, c, key) {
  23267. return apis.showSlot(c, key);
  23268. }
  23269. }, function (value) {
  23270. return makeApi(value);
  23271. });
  23272. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch });
  23273. var sidebarSchema = objOf([
  23274. optionString('icon'),
  23275. optionString('tooltip'),
  23276. defaultedFunction('onShow', noop),
  23277. defaultedFunction('onHide', noop),
  23278. defaultedFunction('onSetup', function () {
  23279. return noop;
  23280. })
  23281. ]);
  23282. var createSidebar = function (spec) {
  23283. return asRaw('sidebar', sidebarSchema, spec);
  23284. };
  23285. var setup$8 = function (editor) {
  23286. var sidebars = editor.ui.registry.getAll().sidebars;
  23287. each$1(keys(sidebars), function (name) {
  23288. var spec = sidebars[name];
  23289. var isActive = function () {
  23290. return is(Optional.from(editor.queryCommandValue('ToggleSidebar')), name);
  23291. };
  23292. editor.ui.registry.addToggleButton(name, {
  23293. icon: spec.icon,
  23294. tooltip: spec.tooltip,
  23295. onAction: function (buttonApi) {
  23296. editor.execCommand('ToggleSidebar', false, name);
  23297. buttonApi.setActive(isActive());
  23298. },
  23299. onSetup: function (buttonApi) {
  23300. var handleToggle = function () {
  23301. return buttonApi.setActive(isActive());
  23302. };
  23303. editor.on('ToggleSidebar', handleToggle);
  23304. return function () {
  23305. editor.off('ToggleSidebar', handleToggle);
  23306. };
  23307. }
  23308. });
  23309. });
  23310. };
  23311. var getApi = function (comp) {
  23312. return {
  23313. element: function () {
  23314. return comp.element.dom;
  23315. }
  23316. };
  23317. };
  23318. var makePanels = function (parts, panelConfigs) {
  23319. var specs = map$2(keys(panelConfigs), function (name) {
  23320. var spec = panelConfigs[name];
  23321. var bridged = getOrDie(createSidebar(spec));
  23322. return {
  23323. name: name,
  23324. getApi: getApi,
  23325. onSetup: bridged.onSetup,
  23326. onShow: bridged.onShow,
  23327. onHide: bridged.onHide
  23328. };
  23329. });
  23330. return map$2(specs, function (spec) {
  23331. var editorOffCell = Cell(noop);
  23332. return parts.slot(spec.name, {
  23333. dom: {
  23334. tag: 'div',
  23335. classes: ['tox-sidebar__pane']
  23336. },
  23337. behaviours: SimpleBehaviours.unnamedEvents([
  23338. onControlAttached(spec, editorOffCell),
  23339. onControlDetached(spec, editorOffCell),
  23340. run$1(slotVisibility(), function (sidepanel, se) {
  23341. var data = se.event;
  23342. var optSidePanelSpec = find$5(specs, function (config) {
  23343. return config.name === data.name;
  23344. });
  23345. optSidePanelSpec.each(function (sidePanelSpec) {
  23346. var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  23347. handler(sidePanelSpec.getApi(sidepanel));
  23348. });
  23349. })
  23350. ])
  23351. });
  23352. });
  23353. };
  23354. var makeSidebar = function (panelConfigs) {
  23355. return SlotContainer.sketch(function (parts) {
  23356. return {
  23357. dom: {
  23358. tag: 'div',
  23359. classes: ['tox-sidebar__pane-container']
  23360. },
  23361. components: makePanels(parts, panelConfigs),
  23362. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  23363. return SlotContainer.hideAllSlots(slotContainer);
  23364. })])
  23365. };
  23366. });
  23367. };
  23368. var setSidebar = function (sidebar, panelConfigs) {
  23369. var optSlider = Composing.getCurrent(sidebar);
  23370. optSlider.each(function (slider) {
  23371. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  23372. });
  23373. };
  23374. var toggleSidebar = function (sidebar, name) {
  23375. var optSlider = Composing.getCurrent(sidebar);
  23376. optSlider.each(function (slider) {
  23377. var optSlotContainer = Composing.getCurrent(slider);
  23378. optSlotContainer.each(function (slotContainer) {
  23379. if (Sliding.hasGrown(slider)) {
  23380. if (SlotContainer.isShowing(slotContainer, name)) {
  23381. Sliding.shrink(slider);
  23382. } else {
  23383. SlotContainer.hideAllSlots(slotContainer);
  23384. SlotContainer.showSlot(slotContainer, name);
  23385. }
  23386. } else {
  23387. SlotContainer.hideAllSlots(slotContainer);
  23388. SlotContainer.showSlot(slotContainer, name);
  23389. Sliding.grow(slider);
  23390. }
  23391. });
  23392. });
  23393. };
  23394. var whichSidebar = function (sidebar) {
  23395. var optSlider = Composing.getCurrent(sidebar);
  23396. return optSlider.bind(function (slider) {
  23397. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  23398. if (sidebarOpen) {
  23399. var optSlotContainer = Composing.getCurrent(slider);
  23400. return optSlotContainer.bind(function (slotContainer) {
  23401. return find$5(SlotContainer.getSlotNames(slotContainer), function (name) {
  23402. return SlotContainer.isShowing(slotContainer, name);
  23403. });
  23404. });
  23405. } else {
  23406. return Optional.none();
  23407. }
  23408. });
  23409. };
  23410. var fixSize = generate$6('FixSizeEvent');
  23411. var autoSize = generate$6('AutoSizeEvent');
  23412. var renderSidebar = function (spec) {
  23413. return {
  23414. uid: spec.uid,
  23415. dom: {
  23416. tag: 'div',
  23417. classes: ['tox-sidebar'],
  23418. attributes: { role: 'complementary' }
  23419. },
  23420. components: [{
  23421. dom: {
  23422. tag: 'div',
  23423. classes: ['tox-sidebar__slider']
  23424. },
  23425. components: [],
  23426. behaviours: derive$1([
  23427. Tabstopping.config({}),
  23428. Focusing.config({}),
  23429. Sliding.config({
  23430. dimension: { property: 'width' },
  23431. closedClass: 'tox-sidebar--sliding-closed',
  23432. openClass: 'tox-sidebar--sliding-open',
  23433. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  23434. growingClass: 'tox-sidebar--sliding-growing',
  23435. onShrunk: function (slider) {
  23436. var optSlotContainer = Composing.getCurrent(slider);
  23437. optSlotContainer.each(SlotContainer.hideAllSlots);
  23438. emit(slider, autoSize);
  23439. },
  23440. onGrown: function (slider) {
  23441. emit(slider, autoSize);
  23442. },
  23443. onStartGrow: function (slider) {
  23444. emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
  23445. },
  23446. onStartShrink: function (slider) {
  23447. emitWith(slider, fixSize, { width: get$7(slider.element) + 'px' });
  23448. }
  23449. }),
  23450. Replacing.config({}),
  23451. Composing.config({
  23452. find: function (comp) {
  23453. var children = Replacing.contents(comp);
  23454. return head(children);
  23455. }
  23456. })
  23457. ])
  23458. }],
  23459. behaviours: derive$1([
  23460. ComposingConfigs.childAt(0),
  23461. config('sidebar-sliding-events', [
  23462. run$1(fixSize, function (comp, se) {
  23463. set$6(comp.element, 'width', se.event.width);
  23464. }),
  23465. run$1(autoSize, function (comp, _se) {
  23466. remove$1(comp.element, 'width');
  23467. })
  23468. ])
  23469. ])
  23470. };
  23471. };
  23472. var block = function (component, config, state, getBusySpec) {
  23473. set$7(component.element, 'aria-busy', true);
  23474. var root = config.getRoot(component).getOr(component);
  23475. var blockerBehaviours = derive$1([
  23476. Keying.config({
  23477. mode: 'special',
  23478. onTab: function () {
  23479. return Optional.some(true);
  23480. },
  23481. onShiftTab: function () {
  23482. return Optional.some(true);
  23483. }
  23484. }),
  23485. Focusing.config({})
  23486. ]);
  23487. var blockSpec = getBusySpec(root, blockerBehaviours);
  23488. var blocker = root.getSystem().build(blockSpec);
  23489. Replacing.append(root, premade(blocker));
  23490. if (blocker.hasConfigured(Keying) && config.focus) {
  23491. Keying.focusIn(blocker);
  23492. }
  23493. if (!state.isBlocked()) {
  23494. config.onBlock(component);
  23495. }
  23496. state.blockWith(function () {
  23497. return Replacing.remove(root, blocker);
  23498. });
  23499. };
  23500. var unblock = function (component, config, state) {
  23501. remove$6(component.element, 'aria-busy');
  23502. if (state.isBlocked()) {
  23503. config.onUnblock(component);
  23504. }
  23505. state.clear();
  23506. };
  23507. var BlockingApis = /*#__PURE__*/Object.freeze({
  23508. __proto__: null,
  23509. block: block,
  23510. unblock: unblock
  23511. });
  23512. var BlockingSchema = [
  23513. defaultedFunction('getRoot', Optional.none),
  23514. defaultedBoolean('focus', true),
  23515. onHandler('onBlock'),
  23516. onHandler('onUnblock')
  23517. ];
  23518. var init$4 = function () {
  23519. var blocker = destroyable();
  23520. var blockWith = function (destroy) {
  23521. blocker.set({ destroy: destroy });
  23522. };
  23523. return nu$8({
  23524. readState: blocker.isSet,
  23525. blockWith: blockWith,
  23526. clear: blocker.clear,
  23527. isBlocked: blocker.isSet
  23528. });
  23529. };
  23530. var BlockingState = /*#__PURE__*/Object.freeze({
  23531. __proto__: null,
  23532. init: init$4
  23533. });
  23534. var Blocking = create$7({
  23535. fields: BlockingSchema,
  23536. name: 'blocking',
  23537. apis: BlockingApis,
  23538. state: BlockingState
  23539. });
  23540. var getAttrs = function (elem) {
  23541. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  23542. return foldl(attributes, function (b, attr) {
  23543. var _a;
  23544. if (attr.name === 'class') {
  23545. return b;
  23546. } else {
  23547. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  23548. }
  23549. }, {});
  23550. };
  23551. var getClasses = function (elem) {
  23552. return Array.prototype.slice.call(elem.dom.classList, 0);
  23553. };
  23554. var fromHtml = function (html) {
  23555. var elem = SugarElement.fromHtml(html);
  23556. var children$1 = children(elem);
  23557. var attrs = getAttrs(elem);
  23558. var classes = getClasses(elem);
  23559. var contents = children$1.length === 0 ? {} : { innerHtml: get$d(elem) };
  23560. return __assign({
  23561. tag: name$2(elem),
  23562. classes: classes,
  23563. attributes: attrs
  23564. }, contents);
  23565. };
  23566. var getBusySpec$1 = function (providerBackstage) {
  23567. return function (_root, _behaviours) {
  23568. return {
  23569. dom: {
  23570. tag: 'div',
  23571. attributes: {
  23572. 'aria-label': providerBackstage.translate('Loading...'),
  23573. 'tabindex': '0'
  23574. },
  23575. classes: ['tox-throbber__busy-spinner']
  23576. },
  23577. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  23578. };
  23579. };
  23580. };
  23581. var focusBusyComponent = function (throbber) {
  23582. return Composing.getCurrent(throbber).each(function (comp) {
  23583. return focus$3(comp.element);
  23584. });
  23585. };
  23586. var toggleEditorTabIndex = function (editor, state) {
  23587. var tabIndexAttr = 'tabindex';
  23588. var dataTabIndexAttr = 'data-mce-' + tabIndexAttr;
  23589. Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function (iframe) {
  23590. if (state) {
  23591. getOpt(iframe, tabIndexAttr).each(function (tabIndex) {
  23592. return set$7(iframe, dataTabIndexAttr, tabIndex);
  23593. });
  23594. set$7(iframe, tabIndexAttr, -1);
  23595. } else {
  23596. remove$6(iframe, tabIndexAttr);
  23597. getOpt(iframe, dataTabIndexAttr).each(function (tabIndex) {
  23598. set$7(iframe, tabIndexAttr, tabIndex);
  23599. remove$6(iframe, dataTabIndexAttr);
  23600. });
  23601. }
  23602. });
  23603. };
  23604. var toggleThrobber = function (editor, comp, state, providerBackstage) {
  23605. var element = comp.element;
  23606. toggleEditorTabIndex(editor, state);
  23607. if (state) {
  23608. Blocking.block(comp, getBusySpec$1(providerBackstage));
  23609. remove$1(element, 'display');
  23610. remove$6(element, 'aria-hidden');
  23611. if (editor.hasFocus()) {
  23612. focusBusyComponent(comp);
  23613. }
  23614. } else {
  23615. var throbberFocus = Composing.getCurrent(comp).exists(function (busyComp) {
  23616. return hasFocus(busyComp.element);
  23617. });
  23618. Blocking.unblock(comp);
  23619. set$6(element, 'display', 'none');
  23620. set$7(element, 'aria-hidden', 'true');
  23621. if (throbberFocus) {
  23622. editor.focus();
  23623. }
  23624. }
  23625. };
  23626. var renderThrobber = function (spec) {
  23627. return {
  23628. uid: spec.uid,
  23629. dom: {
  23630. tag: 'div',
  23631. attributes: { 'aria-hidden': 'true' },
  23632. classes: ['tox-throbber'],
  23633. styles: { display: 'none' }
  23634. },
  23635. behaviours: derive$1([
  23636. Replacing.config({}),
  23637. Blocking.config({ focus: false }),
  23638. Composing.config({
  23639. find: function (comp) {
  23640. return head(comp.components());
  23641. }
  23642. })
  23643. ]),
  23644. components: []
  23645. };
  23646. };
  23647. var isFocusEvent = function (event) {
  23648. return event.type === 'focusin';
  23649. };
  23650. var isPasteBinTarget = function (event) {
  23651. if (isFocusEvent(event)) {
  23652. var node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
  23653. return node.map(SugarElement.fromDom).filter(isElement$2).exists(function (targetElm) {
  23654. return has(targetElm, 'mce-pastebin');
  23655. });
  23656. } else {
  23657. return false;
  23658. }
  23659. };
  23660. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  23661. var throbberState = Cell(false);
  23662. var timer = value$1();
  23663. var stealFocus = function (e) {
  23664. if (throbberState.get() && !isPasteBinTarget(e)) {
  23665. e.preventDefault();
  23666. focusBusyComponent(lazyThrobber());
  23667. editor.editorManager.setActive(editor);
  23668. }
  23669. };
  23670. if (!editor.inline) {
  23671. editor.on('PreInit', function () {
  23672. editor.dom.bind(editor.getWin(), 'focusin', stealFocus);
  23673. editor.on('BeforeExecCommand', function (e) {
  23674. if (e.command.toLowerCase() === 'mcefocus' && e.value !== true) {
  23675. stealFocus(e);
  23676. }
  23677. });
  23678. });
  23679. }
  23680. var toggle = function (state) {
  23681. if (state !== throbberState.get()) {
  23682. throbberState.set(state);
  23683. toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
  23684. editor.fire('AfterProgressState', { state: state });
  23685. }
  23686. };
  23687. editor.on('ProgressState', function (e) {
  23688. timer.on(global$g.clearTimeout);
  23689. if (isNumber(e.time)) {
  23690. var timerId = global$g.setEditorTimeout(editor, function () {
  23691. return toggle(e.state);
  23692. }, e.time);
  23693. timer.set(timerId);
  23694. } else {
  23695. toggle(e.state);
  23696. timer.clear();
  23697. }
  23698. });
  23699. };
  23700. var generate$1 = function (xs, f) {
  23701. var init = {
  23702. len: 0,
  23703. list: []
  23704. };
  23705. var r = foldl(xs, function (b, a) {
  23706. var value = f(a, b.len);
  23707. return value.fold(constant$1(b), function (v) {
  23708. return {
  23709. len: v.finish,
  23710. list: b.list.concat([v])
  23711. };
  23712. });
  23713. }, init);
  23714. return r.list;
  23715. };
  23716. var output = function (within, extra, withinWidth) {
  23717. return {
  23718. within: within,
  23719. extra: extra,
  23720. withinWidth: withinWidth
  23721. };
  23722. };
  23723. var apportion = function (units, total, len) {
  23724. var parray = generate$1(units, function (unit, current) {
  23725. var width = len(unit);
  23726. return Optional.some({
  23727. element: unit,
  23728. start: current,
  23729. finish: current + width,
  23730. width: width
  23731. });
  23732. });
  23733. var within = filter$2(parray, function (unit) {
  23734. return unit.finish <= total;
  23735. });
  23736. var withinWidth = foldr(within, function (acc, el) {
  23737. return acc + el.width;
  23738. }, 0);
  23739. var extra = parray.slice(within.length);
  23740. return {
  23741. within: within,
  23742. extra: extra,
  23743. withinWidth: withinWidth
  23744. };
  23745. };
  23746. var toUnit = function (parray) {
  23747. return map$2(parray, function (unit) {
  23748. return unit.element;
  23749. });
  23750. };
  23751. var fitLast = function (within, extra, withinWidth) {
  23752. var fits = toUnit(within.concat(extra));
  23753. return output(fits, [], withinWidth);
  23754. };
  23755. var overflow = function (within, extra, overflower, withinWidth) {
  23756. var fits = toUnit(within).concat([overflower]);
  23757. return output(fits, toUnit(extra), withinWidth);
  23758. };
  23759. var fitAll = function (within, extra, withinWidth) {
  23760. return output(toUnit(within), [], withinWidth);
  23761. };
  23762. var tryFit = function (total, units, len) {
  23763. var divide = apportion(units, total, len);
  23764. return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
  23765. };
  23766. var partition = function (total, units, len, overflower) {
  23767. var divide = tryFit(total, units, len).getOrThunk(function () {
  23768. return apportion(units, total - len(overflower), len);
  23769. });
  23770. var within = divide.within;
  23771. var extra = divide.extra;
  23772. var withinWidth = divide.withinWidth;
  23773. if (extra.length === 1 && extra[0].width <= len(overflower)) {
  23774. return fitLast(within, extra, withinWidth);
  23775. } else if (extra.length >= 1) {
  23776. return overflow(within, extra, overflower, withinWidth);
  23777. } else {
  23778. return fitAll(within, extra, withinWidth);
  23779. }
  23780. };
  23781. var setGroups$1 = function (toolbar, storedGroups) {
  23782. var bGroups = map$2(storedGroups, function (g) {
  23783. return premade(g);
  23784. });
  23785. Toolbar.setGroups(toolbar, bGroups);
  23786. };
  23787. var findFocusedComp = function (comps) {
  23788. return findMap(comps, function (comp) {
  23789. return search(comp.element).bind(function (focusedElm) {
  23790. return comp.getSystem().getByDom(focusedElm).toOptional();
  23791. });
  23792. });
  23793. };
  23794. var refresh$2 = function (toolbar, detail, setOverflow) {
  23795. var builtGroups = detail.builtGroups.get();
  23796. if (builtGroups.length === 0) {
  23797. return;
  23798. }
  23799. var primary = getPartOrDie(toolbar, detail, 'primary');
  23800. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  23801. set$6(primary.element, 'visibility', 'hidden');
  23802. var groups = builtGroups.concat([overflowGroup]);
  23803. var focusedComp = findFocusedComp(groups);
  23804. setOverflow([]);
  23805. setGroups$1(primary, groups);
  23806. var availableWidth = get$7(primary.element);
  23807. var overflows = partition(availableWidth, detail.builtGroups.get(), function (comp) {
  23808. return get$7(comp.element);
  23809. }, overflowGroup);
  23810. if (overflows.extra.length === 0) {
  23811. Replacing.remove(primary, overflowGroup);
  23812. setOverflow([]);
  23813. } else {
  23814. setGroups$1(primary, overflows.within);
  23815. setOverflow(overflows.extra);
  23816. }
  23817. remove$1(primary.element, 'visibility');
  23818. reflow(primary.element);
  23819. focusedComp.each(Focusing.focus);
  23820. };
  23821. var schema$c = constant$1([
  23822. field('splitToolbarBehaviours', [Coupling]),
  23823. customField('builtGroups', function () {
  23824. return Cell([]);
  23825. })
  23826. ]);
  23827. var schema$b = constant$1([
  23828. markers$1(['overflowToggledClass']),
  23829. optionFunction('getOverflowBounds'),
  23830. required$1('lazySink'),
  23831. customField('overflowGroups', function () {
  23832. return Cell([]);
  23833. })
  23834. ].concat(schema$c()));
  23835. var parts$7 = constant$1([
  23836. required({
  23837. factory: Toolbar,
  23838. schema: schema$e(),
  23839. name: 'primary'
  23840. }),
  23841. external$1({
  23842. schema: schema$e(),
  23843. name: 'overflow'
  23844. }),
  23845. external$1({ name: 'overflow-button' }),
  23846. external$1({ name: 'overflow-group' })
  23847. ]);
  23848. var expandable = constant$1(function (element, available) {
  23849. setMax(element, Math.floor(available));
  23850. });
  23851. var schema$a = constant$1([
  23852. markers$1(['toggledClass']),
  23853. required$1('lazySink'),
  23854. requiredFunction('fetch'),
  23855. optionFunction('getBounds'),
  23856. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  23857. schema$y()
  23858. ]);
  23859. var parts$6 = constant$1([
  23860. external$1({
  23861. name: 'button',
  23862. overrides: function (detail) {
  23863. return {
  23864. dom: { attributes: { 'aria-haspopup': 'true' } },
  23865. buttonBehaviours: derive$1([Toggling.config({
  23866. toggleClass: detail.markers.toggledClass,
  23867. aria: { mode: 'expanded' },
  23868. toggleOnExecute: false
  23869. })])
  23870. };
  23871. }
  23872. }),
  23873. external$1({
  23874. factory: Toolbar,
  23875. schema: schema$e(),
  23876. name: 'toolbar',
  23877. overrides: function (detail) {
  23878. return {
  23879. toolbarBehaviours: derive$1([Keying.config({
  23880. mode: 'cyclic',
  23881. onEscape: function (comp) {
  23882. getPart(comp, detail, 'button').each(Focusing.focus);
  23883. return Optional.none();
  23884. }
  23885. })])
  23886. };
  23887. }
  23888. })
  23889. ]);
  23890. var toggle = function (button, externals) {
  23891. var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  23892. if (Sandboxing.isOpen(toolbarSandbox)) {
  23893. Sandboxing.close(toolbarSandbox);
  23894. } else {
  23895. Sandboxing.open(toolbarSandbox, externals.toolbar());
  23896. }
  23897. };
  23898. var position = function (button, toolbar, detail, layouts) {
  23899. var bounds = detail.getBounds.map(function (bounder) {
  23900. return bounder();
  23901. });
  23902. var sink = detail.lazySink(button).getOrDie();
  23903. Positioning.positionWithinBounds(sink, toolbar, {
  23904. anchor: {
  23905. type: 'hotspot',
  23906. hotspot: button,
  23907. layouts: layouts,
  23908. overrides: { maxWidthFunction: expandable() }
  23909. }
  23910. }, bounds);
  23911. };
  23912. var setGroups = function (button, toolbar, detail, layouts, groups) {
  23913. Toolbar.setGroups(toolbar, groups);
  23914. position(button, toolbar, detail, layouts);
  23915. Toggling.on(button);
  23916. };
  23917. var makeSandbox = function (button, spec, detail) {
  23918. var ariaOwner = manager();
  23919. var onOpen = function (sandbox, toolbar) {
  23920. detail.fetch().get(function (groups) {
  23921. setGroups(button, toolbar, detail, spec.layouts, groups);
  23922. ariaOwner.link(button.element);
  23923. Keying.focusIn(toolbar);
  23924. });
  23925. };
  23926. var onClose = function () {
  23927. Toggling.off(button);
  23928. Focusing.focus(button);
  23929. ariaOwner.unlink(button.element);
  23930. };
  23931. return {
  23932. dom: {
  23933. tag: 'div',
  23934. attributes: { id: ariaOwner.id }
  23935. },
  23936. behaviours: derive$1([
  23937. Keying.config({
  23938. mode: 'special',
  23939. onEscape: function (comp) {
  23940. Sandboxing.close(comp);
  23941. return Optional.some(true);
  23942. }
  23943. }),
  23944. Sandboxing.config({
  23945. onOpen: onOpen,
  23946. onClose: onClose,
  23947. isPartOf: function (container, data, queryElem) {
  23948. return isPartOf$1(data, queryElem) || isPartOf$1(button, queryElem);
  23949. },
  23950. getAttachPoint: function () {
  23951. return detail.lazySink(button).getOrDie();
  23952. }
  23953. }),
  23954. Receiving.config({
  23955. channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
  23956. return { fireEventInstead: { event: fe.event } };
  23957. }).getOr({})))), receivingChannel({
  23958. doReposition: function () {
  23959. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23960. position(button, toolbar, detail, spec.layouts);
  23961. });
  23962. }
  23963. }))
  23964. })
  23965. ])
  23966. };
  23967. };
  23968. var factory$a = function (detail, components, spec, externals) {
  23969. return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  23970. action: function (button) {
  23971. toggle(button, externals);
  23972. },
  23973. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  23974. others: {
  23975. toolbarSandbox: function (button) {
  23976. return makeSandbox(button, spec, detail);
  23977. }
  23978. }
  23979. })])
  23980. }))), {
  23981. apis: {
  23982. setGroups: function (button, groups) {
  23983. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23984. setGroups(button, toolbar, detail, spec.layouts, groups);
  23985. });
  23986. },
  23987. reposition: function (button) {
  23988. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23989. position(button, toolbar, detail, spec.layouts);
  23990. });
  23991. },
  23992. toggle: function (button) {
  23993. toggle(button, externals);
  23994. },
  23995. getToolbar: function (button) {
  23996. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  23997. },
  23998. isOpen: function (button) {
  23999. return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
  24000. }
  24001. }
  24002. });
  24003. };
  24004. var FloatingToolbarButton = composite({
  24005. name: 'FloatingToolbarButton',
  24006. factory: factory$a,
  24007. configFields: schema$a(),
  24008. partFields: parts$6(),
  24009. apis: {
  24010. setGroups: function (apis, button, groups) {
  24011. apis.setGroups(button, groups);
  24012. },
  24013. reposition: function (apis, button) {
  24014. apis.reposition(button);
  24015. },
  24016. toggle: function (apis, button) {
  24017. apis.toggle(button);
  24018. },
  24019. getToolbar: function (apis, button) {
  24020. return apis.getToolbar(button);
  24021. },
  24022. isOpen: function (apis, button) {
  24023. return apis.isOpen(button);
  24024. }
  24025. }
  24026. });
  24027. var schema$9 = constant$1([
  24028. required$1('items'),
  24029. markers$1(['itemSelector']),
  24030. field('tgroupBehaviours', [Keying])
  24031. ]);
  24032. var parts$5 = constant$1([group({
  24033. name: 'items',
  24034. unit: 'item'
  24035. })]);
  24036. var factory$9 = function (detail, components, _spec, _externals) {
  24037. return {
  24038. uid: detail.uid,
  24039. dom: detail.dom,
  24040. components: components,
  24041. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  24042. mode: 'flow',
  24043. selector: detail.markers.itemSelector
  24044. })]),
  24045. domModification: { attributes: { role: 'toolbar' } }
  24046. };
  24047. };
  24048. var ToolbarGroup = composite({
  24049. name: 'ToolbarGroup',
  24050. configFields: schema$9(),
  24051. partFields: parts$5(),
  24052. factory: factory$9
  24053. });
  24054. var buildGroups = function (comps) {
  24055. return map$2(comps, function (g) {
  24056. return premade(g);
  24057. });
  24058. };
  24059. var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  24060. refresh$2(toolbar, detail, function (overflowGroups) {
  24061. detail.overflowGroups.set(overflowGroups);
  24062. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  24063. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  24064. });
  24065. });
  24066. };
  24067. var factory$8 = function (detail, components, spec, externals) {
  24068. var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  24069. fetch: function () {
  24070. return Future.nu(function (resolve) {
  24071. resolve(buildGroups(detail.overflowGroups.get()));
  24072. });
  24073. },
  24074. layouts: {
  24075. onLtr: function () {
  24076. return [
  24077. southwest$2,
  24078. southeast$2
  24079. ];
  24080. },
  24081. onRtl: function () {
  24082. return [
  24083. southeast$2,
  24084. southwest$2
  24085. ];
  24086. },
  24087. onBottomLtr: function () {
  24088. return [
  24089. northwest$2,
  24090. northeast$2
  24091. ];
  24092. },
  24093. onBottomRtl: function () {
  24094. return [
  24095. northeast$2,
  24096. northwest$2
  24097. ];
  24098. }
  24099. },
  24100. getBounds: spec.getOverflowBounds,
  24101. lazySink: detail.lazySink,
  24102. fireDismissalEventInstead: {},
  24103. markers: { toggledClass: detail.markers.overflowToggledClass },
  24104. parts: {
  24105. button: externals['overflow-button'](),
  24106. toolbar: externals.overflow()
  24107. }
  24108. }));
  24109. return {
  24110. uid: detail.uid,
  24111. dom: detail.dom,
  24112. components: components,
  24113. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  24114. others: {
  24115. overflowGroup: function () {
  24116. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  24117. }
  24118. }
  24119. })]),
  24120. apis: {
  24121. setGroups: function (toolbar, groups) {
  24122. detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
  24123. refresh$1(toolbar, memFloatingToolbarButton, detail);
  24124. },
  24125. refresh: function (toolbar) {
  24126. return refresh$1(toolbar, memFloatingToolbarButton, detail);
  24127. },
  24128. toggle: function (toolbar) {
  24129. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  24130. FloatingToolbarButton.toggle(floatingToolbarButton);
  24131. });
  24132. },
  24133. isOpen: function (toolbar) {
  24134. return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
  24135. },
  24136. reposition: function (toolbar) {
  24137. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  24138. FloatingToolbarButton.reposition(floatingToolbarButton);
  24139. });
  24140. },
  24141. getOverflow: function (toolbar) {
  24142. return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
  24143. }
  24144. },
  24145. domModification: { attributes: { role: 'group' } }
  24146. };
  24147. };
  24148. var SplitFloatingToolbar = composite({
  24149. name: 'SplitFloatingToolbar',
  24150. configFields: schema$b(),
  24151. partFields: parts$7(),
  24152. factory: factory$8,
  24153. apis: {
  24154. setGroups: function (apis, toolbar, groups) {
  24155. apis.setGroups(toolbar, groups);
  24156. },
  24157. refresh: function (apis, toolbar) {
  24158. apis.refresh(toolbar);
  24159. },
  24160. reposition: function (apis, toolbar) {
  24161. apis.reposition(toolbar);
  24162. },
  24163. toggle: function (apis, toolbar) {
  24164. apis.toggle(toolbar);
  24165. },
  24166. isOpen: function (apis, toolbar) {
  24167. return apis.isOpen(toolbar);
  24168. },
  24169. getOverflow: function (apis, toolbar) {
  24170. return apis.getOverflow(toolbar);
  24171. }
  24172. }
  24173. });
  24174. var schema$8 = constant$1([
  24175. markers$1([
  24176. 'closedClass',
  24177. 'openClass',
  24178. 'shrinkingClass',
  24179. 'growingClass',
  24180. 'overflowToggledClass'
  24181. ]),
  24182. onHandler('onOpened'),
  24183. onHandler('onClosed')
  24184. ].concat(schema$c()));
  24185. var parts$4 = constant$1([
  24186. required({
  24187. factory: Toolbar,
  24188. schema: schema$e(),
  24189. name: 'primary'
  24190. }),
  24191. required({
  24192. factory: Toolbar,
  24193. schema: schema$e(),
  24194. name: 'overflow',
  24195. overrides: function (detail) {
  24196. return {
  24197. toolbarBehaviours: derive$1([
  24198. Sliding.config({
  24199. dimension: { property: 'height' },
  24200. closedClass: detail.markers.closedClass,
  24201. openClass: detail.markers.openClass,
  24202. shrinkingClass: detail.markers.shrinkingClass,
  24203. growingClass: detail.markers.growingClass,
  24204. onShrunk: function (comp) {
  24205. getPart(comp, detail, 'overflow-button').each(function (button) {
  24206. Toggling.off(button);
  24207. Focusing.focus(button);
  24208. });
  24209. detail.onClosed(comp);
  24210. },
  24211. onGrown: function (comp) {
  24212. Keying.focusIn(comp);
  24213. detail.onOpened(comp);
  24214. },
  24215. onStartGrow: function (comp) {
  24216. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  24217. }
  24218. }),
  24219. Keying.config({
  24220. mode: 'acyclic',
  24221. onEscape: function (comp) {
  24222. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  24223. return Optional.some(true);
  24224. }
  24225. })
  24226. ])
  24227. };
  24228. }
  24229. }),
  24230. external$1({
  24231. name: 'overflow-button',
  24232. overrides: function (detail) {
  24233. return {
  24234. buttonBehaviours: derive$1([Toggling.config({
  24235. toggleClass: detail.markers.overflowToggledClass,
  24236. aria: { mode: 'pressed' },
  24237. toggleOnExecute: false
  24238. })])
  24239. };
  24240. }
  24241. }),
  24242. external$1({ name: 'overflow-group' })
  24243. ]);
  24244. var isOpen = function (toolbar, detail) {
  24245. return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
  24246. };
  24247. var toggleToolbar = function (toolbar, detail) {
  24248. getPart(toolbar, detail, 'overflow-button').bind(function () {
  24249. return getPart(toolbar, detail, 'overflow');
  24250. }).each(function (overf) {
  24251. refresh(toolbar, detail);
  24252. Sliding.toggleGrow(overf);
  24253. });
  24254. };
  24255. var refresh = function (toolbar, detail) {
  24256. getPart(toolbar, detail, 'overflow').each(function (overflow) {
  24257. refresh$2(toolbar, detail, function (groups) {
  24258. var builtGroups = map$2(groups, function (g) {
  24259. return premade(g);
  24260. });
  24261. Toolbar.setGroups(overflow, builtGroups);
  24262. });
  24263. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  24264. if (Sliding.hasGrown(overflow)) {
  24265. Toggling.on(button);
  24266. }
  24267. });
  24268. Sliding.refresh(overflow);
  24269. });
  24270. };
  24271. var factory$7 = function (detail, components, spec, externals) {
  24272. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  24273. var doSetGroups = function (toolbar, groups) {
  24274. var built = map$2(groups, toolbar.getSystem().build);
  24275. detail.builtGroups.set(built);
  24276. };
  24277. return {
  24278. uid: detail.uid,
  24279. dom: detail.dom,
  24280. components: components,
  24281. behaviours: augment(detail.splitToolbarBehaviours, [
  24282. Coupling.config({
  24283. others: {
  24284. overflowGroup: function (toolbar) {
  24285. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  24286. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  24287. action: function (_button) {
  24288. emit(toolbar, toolbarToggleEvent);
  24289. }
  24290. }))]
  24291. }));
  24292. }
  24293. }
  24294. }),
  24295. config('toolbar-toggle-events', [run$1(toolbarToggleEvent, function (toolbar) {
  24296. toggleToolbar(toolbar, detail);
  24297. })])
  24298. ]),
  24299. apis: {
  24300. setGroups: function (toolbar, groups) {
  24301. doSetGroups(toolbar, groups);
  24302. refresh(toolbar, detail);
  24303. },
  24304. refresh: function (toolbar) {
  24305. return refresh(toolbar, detail);
  24306. },
  24307. toggle: function (toolbar) {
  24308. return toggleToolbar(toolbar, detail);
  24309. },
  24310. isOpen: function (toolbar) {
  24311. return isOpen(toolbar, detail);
  24312. }
  24313. },
  24314. domModification: { attributes: { role: 'group' } }
  24315. };
  24316. };
  24317. var SplitSlidingToolbar = composite({
  24318. name: 'SplitSlidingToolbar',
  24319. configFields: schema$8(),
  24320. partFields: parts$4(),
  24321. factory: factory$7,
  24322. apis: {
  24323. setGroups: function (apis, toolbar, groups) {
  24324. apis.setGroups(toolbar, groups);
  24325. },
  24326. refresh: function (apis, toolbar) {
  24327. apis.refresh(toolbar);
  24328. },
  24329. toggle: function (apis, toolbar) {
  24330. apis.toggle(toolbar);
  24331. },
  24332. isOpen: function (apis, toolbar) {
  24333. return apis.isOpen(toolbar);
  24334. }
  24335. }
  24336. });
  24337. var renderToolbarGroupCommon = function (toolbarGroup) {
  24338. var attributes = toolbarGroup.title.fold(function () {
  24339. return {};
  24340. }, function (title) {
  24341. return { attributes: { title: title } };
  24342. });
  24343. return {
  24344. dom: __assign({
  24345. tag: 'div',
  24346. classes: ['tox-toolbar__group']
  24347. }, attributes),
  24348. components: [ToolbarGroup.parts.items({})],
  24349. items: toolbarGroup.items,
  24350. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  24351. tgroupBehaviours: derive$1([
  24352. Tabstopping.config({}),
  24353. Focusing.config({})
  24354. ])
  24355. };
  24356. };
  24357. var renderToolbarGroup = function (toolbarGroup) {
  24358. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  24359. };
  24360. var getToolbarbehaviours = function (toolbarSpec, modeName) {
  24361. var onAttached = runOnAttached(function (component) {
  24362. var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
  24363. Toolbar.setGroups(component, groups);
  24364. });
  24365. return derive$1([
  24366. DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
  24367. receivingConfig(),
  24368. Keying.config({
  24369. mode: modeName,
  24370. onEscape: toolbarSpec.onEscape,
  24371. selector: '.tox-toolbar__group'
  24372. }),
  24373. config('toolbar-events', [onAttached])
  24374. ]);
  24375. };
  24376. var renderMoreToolbarCommon = function (toolbarSpec) {
  24377. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  24378. return {
  24379. uid: toolbarSpec.uid,
  24380. dom: {
  24381. tag: 'div',
  24382. classes: ['tox-toolbar-overlord']
  24383. },
  24384. parts: {
  24385. 'overflow-group': renderToolbarGroupCommon({
  24386. title: Optional.none(),
  24387. items: []
  24388. }),
  24389. 'overflow-button': renderIconButtonSpec({
  24390. name: 'more',
  24391. icon: Optional.some('more-drawer'),
  24392. disabled: false,
  24393. tooltip: Optional.some('More...'),
  24394. primary: false,
  24395. borderless: false
  24396. }, Optional.none(), toolbarSpec.providers)
  24397. },
  24398. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  24399. };
  24400. };
  24401. var renderFloatingMoreToolbar = function (toolbarSpec) {
  24402. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  24403. var overflowXOffset = 4;
  24404. var primary = SplitFloatingToolbar.parts.primary({
  24405. dom: {
  24406. tag: 'div',
  24407. classes: ['tox-toolbar__primary']
  24408. }
  24409. });
  24410. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  24411. lazySink: toolbarSpec.getSink,
  24412. getOverflowBounds: function () {
  24413. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
  24414. var headerBounds = absolute$2(headerElem);
  24415. var docElem = documentElement(headerElem);
  24416. var docBounds = absolute$2(docElem);
  24417. var height = Math.max(docElem.dom.scrollHeight, docBounds.height);
  24418. return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  24419. },
  24420. parts: __assign(__assign({}, baseSpec.parts), {
  24421. overflow: {
  24422. dom: {
  24423. tag: 'div',
  24424. classes: ['tox-toolbar__overflow'],
  24425. attributes: toolbarSpec.attributes
  24426. }
  24427. }
  24428. }),
  24429. components: [primary],
  24430. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  24431. }));
  24432. };
  24433. var renderSlidingMoreToolbar = function (toolbarSpec) {
  24434. var primary = SplitSlidingToolbar.parts.primary({
  24435. dom: {
  24436. tag: 'div',
  24437. classes: ['tox-toolbar__primary']
  24438. }
  24439. });
  24440. var overflow = SplitSlidingToolbar.parts.overflow({
  24441. dom: {
  24442. tag: 'div',
  24443. classes: ['tox-toolbar__overflow']
  24444. }
  24445. });
  24446. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  24447. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  24448. components: [
  24449. primary,
  24450. overflow
  24451. ],
  24452. markers: {
  24453. openClass: 'tox-toolbar__overflow--open',
  24454. closedClass: 'tox-toolbar__overflow--closed',
  24455. growingClass: 'tox-toolbar__overflow--growing',
  24456. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  24457. overflowToggledClass: 'tox-tbtn--enabled'
  24458. },
  24459. onOpened: function (comp) {
  24460. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  24461. },
  24462. onClosed: function (comp) {
  24463. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  24464. }
  24465. }));
  24466. };
  24467. var renderToolbar = function (toolbarSpec) {
  24468. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  24469. return Toolbar.sketch({
  24470. uid: toolbarSpec.uid,
  24471. dom: {
  24472. tag: 'div',
  24473. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  24474. },
  24475. components: [Toolbar.parts.groups({})],
  24476. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  24477. });
  24478. };
  24479. var factory$6 = function (detail, components, _spec) {
  24480. var apis = {
  24481. getSocket: function (comp) {
  24482. return parts$a.getPart(comp, detail, 'socket');
  24483. },
  24484. setSidebar: function (comp, panelConfigs) {
  24485. parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  24486. return setSidebar(sidebar, panelConfigs);
  24487. });
  24488. },
  24489. toggleSidebar: function (comp, name) {
  24490. parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  24491. return toggleSidebar(sidebar, name);
  24492. });
  24493. },
  24494. whichSidebar: function (comp) {
  24495. return parts$a.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  24496. },
  24497. getHeader: function (comp) {
  24498. return parts$a.getPart(comp, detail, 'header');
  24499. },
  24500. getToolbar: function (comp) {
  24501. return parts$a.getPart(comp, detail, 'toolbar');
  24502. },
  24503. setToolbar: function (comp, groups) {
  24504. parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  24505. toolbar.getApis().setGroups(toolbar, groups);
  24506. });
  24507. },
  24508. setToolbars: function (comp, toolbars) {
  24509. parts$a.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  24510. CustomList.setItems(mToolbar, toolbars);
  24511. });
  24512. },
  24513. refreshToolbar: function (comp) {
  24514. var toolbar = parts$a.getPart(comp, detail, 'toolbar');
  24515. toolbar.each(function (toolbar) {
  24516. return toolbar.getApis().refresh(toolbar);
  24517. });
  24518. },
  24519. toggleToolbarDrawer: function (comp) {
  24520. parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  24521. mapFrom(toolbar.getApis().toggle, function (toggle) {
  24522. return toggle(toolbar);
  24523. });
  24524. });
  24525. },
  24526. isToolbarDrawerToggled: function (comp) {
  24527. return parts$a.getPart(comp, detail, 'toolbar').bind(function (toolbar) {
  24528. return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) {
  24529. return isOpen(toolbar);
  24530. });
  24531. }).getOr(false);
  24532. },
  24533. getThrobber: function (comp) {
  24534. return parts$a.getPart(comp, detail, 'throbber');
  24535. },
  24536. focusToolbar: function (comp) {
  24537. var optToolbar = parts$a.getPart(comp, detail, 'toolbar').orThunk(function () {
  24538. return parts$a.getPart(comp, detail, 'multiple-toolbar');
  24539. });
  24540. optToolbar.each(function (toolbar) {
  24541. Keying.focusIn(toolbar);
  24542. });
  24543. },
  24544. setMenubar: function (comp, menus) {
  24545. parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  24546. SilverMenubar.setMenus(menubar, menus);
  24547. });
  24548. },
  24549. focusMenubar: function (comp) {
  24550. parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  24551. SilverMenubar.focus(menubar);
  24552. });
  24553. }
  24554. };
  24555. return {
  24556. uid: detail.uid,
  24557. dom: detail.dom,
  24558. components: components,
  24559. apis: apis,
  24560. behaviours: detail.behaviours
  24561. };
  24562. };
  24563. var partMenubar = partType.optional({
  24564. factory: SilverMenubar,
  24565. name: 'menubar',
  24566. schema: [required$1('backstage')]
  24567. });
  24568. var toolbarFactory = function (spec) {
  24569. if (spec.type === ToolbarMode.sliding) {
  24570. return renderSlidingMoreToolbar;
  24571. } else if (spec.type === ToolbarMode.floating) {
  24572. return renderFloatingMoreToolbar;
  24573. } else {
  24574. return renderToolbar;
  24575. }
  24576. };
  24577. var partMultipleToolbar = partType.optional({
  24578. factory: {
  24579. sketch: function (spec) {
  24580. return CustomList.sketch({
  24581. uid: spec.uid,
  24582. dom: spec.dom,
  24583. listBehaviours: derive$1([Keying.config({
  24584. mode: 'acyclic',
  24585. selector: '.tox-toolbar'
  24586. })]),
  24587. makeItem: function () {
  24588. return renderToolbar({
  24589. type: spec.type,
  24590. uid: generate$6('multiple-toolbar-item'),
  24591. cyclicKeying: false,
  24592. initGroups: [],
  24593. providers: spec.providers,
  24594. onEscape: function () {
  24595. spec.onEscape();
  24596. return Optional.some(true);
  24597. }
  24598. });
  24599. },
  24600. setupItem: function (_mToolbar, tc, data, _index) {
  24601. Toolbar.setGroups(tc, data);
  24602. },
  24603. shell: true
  24604. });
  24605. }
  24606. },
  24607. name: 'multiple-toolbar',
  24608. schema: [
  24609. required$1('dom'),
  24610. required$1('onEscape')
  24611. ]
  24612. });
  24613. var partToolbar = partType.optional({
  24614. factory: {
  24615. sketch: function (spec) {
  24616. var renderer = toolbarFactory(spec);
  24617. var toolbarSpec = {
  24618. type: spec.type,
  24619. uid: spec.uid,
  24620. onEscape: function () {
  24621. spec.onEscape();
  24622. return Optional.some(true);
  24623. },
  24624. cyclicKeying: false,
  24625. initGroups: [],
  24626. getSink: spec.getSink,
  24627. providers: spec.providers,
  24628. moreDrawerData: {
  24629. lazyToolbar: spec.lazyToolbar,
  24630. lazyMoreButton: spec.lazyMoreButton,
  24631. lazyHeader: spec.lazyHeader
  24632. },
  24633. attributes: spec.attributes
  24634. };
  24635. return renderer(toolbarSpec);
  24636. }
  24637. },
  24638. name: 'toolbar',
  24639. schema: [
  24640. required$1('dom'),
  24641. required$1('onEscape'),
  24642. required$1('getSink')
  24643. ]
  24644. });
  24645. var partHeader = partType.optional({
  24646. factory: { sketch: renderHeader },
  24647. name: 'header',
  24648. schema: [required$1('dom')]
  24649. });
  24650. var partSocket = partType.optional({
  24651. name: 'socket',
  24652. schema: [required$1('dom')]
  24653. });
  24654. var partSidebar = partType.optional({
  24655. factory: { sketch: renderSidebar },
  24656. name: 'sidebar',
  24657. schema: [required$1('dom')]
  24658. });
  24659. var partThrobber = partType.optional({
  24660. factory: { sketch: renderThrobber },
  24661. name: 'throbber',
  24662. schema: [required$1('dom')]
  24663. });
  24664. var OuterContainer = composite({
  24665. name: 'OuterContainer',
  24666. factory: factory$6,
  24667. configFields: [
  24668. required$1('dom'),
  24669. required$1('behaviours')
  24670. ],
  24671. partFields: [
  24672. partHeader,
  24673. partMenubar,
  24674. partToolbar,
  24675. partMultipleToolbar,
  24676. partSocket,
  24677. partSidebar,
  24678. partThrobber
  24679. ],
  24680. apis: {
  24681. getSocket: function (apis, comp) {
  24682. return apis.getSocket(comp);
  24683. },
  24684. setSidebar: function (apis, comp, panelConfigs) {
  24685. apis.setSidebar(comp, panelConfigs);
  24686. },
  24687. toggleSidebar: function (apis, comp, name) {
  24688. apis.toggleSidebar(comp, name);
  24689. },
  24690. whichSidebar: function (apis, comp) {
  24691. return apis.whichSidebar(comp);
  24692. },
  24693. getHeader: function (apis, comp) {
  24694. return apis.getHeader(comp);
  24695. },
  24696. getToolbar: function (apis, comp) {
  24697. return apis.getToolbar(comp);
  24698. },
  24699. setToolbar: function (apis, comp, grps) {
  24700. var groups = map$2(grps, function (grp) {
  24701. return renderToolbarGroup(grp);
  24702. });
  24703. apis.setToolbar(comp, groups);
  24704. },
  24705. setToolbars: function (apis, comp, ts) {
  24706. var renderedToolbars = map$2(ts, function (g) {
  24707. return map$2(g, renderToolbarGroup);
  24708. });
  24709. apis.setToolbars(comp, renderedToolbars);
  24710. },
  24711. refreshToolbar: function (apis, comp) {
  24712. return apis.refreshToolbar(comp);
  24713. },
  24714. toggleToolbarDrawer: function (apis, comp) {
  24715. apis.toggleToolbarDrawer(comp);
  24716. },
  24717. isToolbarDrawerToggled: function (apis, comp) {
  24718. return apis.isToolbarDrawerToggled(comp);
  24719. },
  24720. getThrobber: function (apis, comp) {
  24721. return apis.getThrobber(comp);
  24722. },
  24723. setMenubar: function (apis, comp, menus) {
  24724. apis.setMenubar(comp, menus);
  24725. },
  24726. focusMenubar: function (apis, comp) {
  24727. apis.focusMenubar(comp);
  24728. },
  24729. focusToolbar: function (apis, comp) {
  24730. apis.focusToolbar(comp);
  24731. }
  24732. }
  24733. });
  24734. var defaultMenubar = 'file edit view insert format tools table help';
  24735. var defaultMenus = {
  24736. file: {
  24737. title: 'File',
  24738. items: 'newdocument restoredraft | preview | export print | deleteallconversations'
  24739. },
  24740. edit: {
  24741. title: 'Edit',
  24742. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  24743. },
  24744. view: {
  24745. title: 'View',
  24746. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  24747. },
  24748. insert: {
  24749. title: 'Insert',
  24750. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  24751. },
  24752. format: {
  24753. title: 'Format',
  24754. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat'
  24755. },
  24756. tools: {
  24757. title: 'Tools',
  24758. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  24759. },
  24760. table: {
  24761. title: 'Table',
  24762. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  24763. },
  24764. help: {
  24765. title: 'Help',
  24766. items: 'help'
  24767. }
  24768. };
  24769. var make = function (menu, registry, editor) {
  24770. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  24771. return {
  24772. text: menu.title,
  24773. getItems: function () {
  24774. return bind$3(menu.items, function (i) {
  24775. var itemName = i.toLowerCase();
  24776. if (itemName.trim().length === 0) {
  24777. return [];
  24778. } else if (exists(removedMenuItems, function (removedMenuItem) {
  24779. return removedMenuItem === itemName;
  24780. })) {
  24781. return [];
  24782. } else if (itemName === 'separator' || itemName === '|') {
  24783. return [{ type: 'separator' }];
  24784. } else if (registry.menuItems[itemName]) {
  24785. return [registry.menuItems[itemName]];
  24786. } else {
  24787. return [];
  24788. }
  24789. });
  24790. }
  24791. };
  24792. };
  24793. var parseItemsString = function (items) {
  24794. if (typeof items === 'string') {
  24795. return items.split(' ');
  24796. }
  24797. return items;
  24798. };
  24799. var identifyMenus = function (editor, registry) {
  24800. var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  24801. var userDefinedMenus = keys(registry.menus).length > 0;
  24802. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  24803. var validMenus = filter$2(menubar, function (menuName) {
  24804. var isDefaultMenu = has$2(defaultMenus, menuName);
  24805. if (userDefinedMenus) {
  24806. return isDefaultMenu || get$e(registry.menus, menuName).exists(function (menu) {
  24807. return has$2(menu, 'items');
  24808. });
  24809. } else {
  24810. return isDefaultMenu;
  24811. }
  24812. });
  24813. var menus = map$2(validMenus, function (menuName) {
  24814. var menuData = rawMenuData[menuName];
  24815. return make({
  24816. title: menuData.title,
  24817. items: parseItemsString(menuData.items)
  24818. }, registry, editor);
  24819. });
  24820. return filter$2(menus, function (menu) {
  24821. var isNotSeparator = function (item) {
  24822. return item.type !== 'separator';
  24823. };
  24824. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  24825. });
  24826. };
  24827. var fireSkinLoaded = function (editor) {
  24828. var done = function () {
  24829. editor._skinLoaded = true;
  24830. fireSkinLoaded$1(editor);
  24831. };
  24832. return function () {
  24833. if (editor.initialized) {
  24834. done();
  24835. } else {
  24836. editor.on('init', done);
  24837. }
  24838. };
  24839. };
  24840. var fireSkinLoadError = function (editor, err) {
  24841. return function () {
  24842. return fireSkinLoadError$1(editor, { message: err });
  24843. };
  24844. };
  24845. var loadStylesheet = function (editor, stylesheetUrl, styleSheetLoader) {
  24846. return new global$d(function (resolve, reject) {
  24847. styleSheetLoader.load(stylesheetUrl, resolve, reject);
  24848. editor.on('remove', function () {
  24849. return styleSheetLoader.unload(stylesheetUrl);
  24850. });
  24851. });
  24852. };
  24853. var loadUiSkins = function (editor, skinUrl) {
  24854. var skinUiCss = skinUrl + '/skin.min.css';
  24855. return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
  24856. };
  24857. var loadShadowDomUiSkins = function (editor, skinUrl) {
  24858. var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
  24859. if (isInShadowRoot$1) {
  24860. var shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css';
  24861. return loadStylesheet(editor, shadowDomSkinCss, global$c.DOM.styleSheetLoader);
  24862. } else {
  24863. return global$d.resolve();
  24864. }
  24865. };
  24866. var loadSkin = function (isInline, editor) {
  24867. var skinUrl = getSkinUrl(editor);
  24868. if (skinUrl) {
  24869. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  24870. }
  24871. if (isSkinDisabled(editor) === false && isString(skinUrl)) {
  24872. global$d.all([
  24873. loadUiSkins(editor, skinUrl),
  24874. loadShadowDomUiSkins(editor, skinUrl)
  24875. ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, 'Skin could not be loaded'));
  24876. } else {
  24877. fireSkinLoaded(editor)();
  24878. }
  24879. };
  24880. var iframe = curry(loadSkin, false);
  24881. var inline = curry(loadSkin, true);
  24882. var onSetupFormatToggle = function (editor, name) {
  24883. return function (api) {
  24884. var boundCallback = unbindable();
  24885. var init = function () {
  24886. api.setActive(editor.formatter.match(name));
  24887. var binding = editor.formatter.formatChanged(name, api.setActive);
  24888. boundCallback.set(binding);
  24889. };
  24890. editor.initialized ? init() : editor.once('init', init);
  24891. return function () {
  24892. editor.off('init', init);
  24893. boundCallback.clear();
  24894. };
  24895. };
  24896. };
  24897. var onSetupEvent = function (editor, event, f) {
  24898. return function (api) {
  24899. var handleEvent = function () {
  24900. return f(api);
  24901. };
  24902. var init = function () {
  24903. f(api);
  24904. editor.on(event, handleEvent);
  24905. };
  24906. editor.initialized ? init() : editor.once('init', init);
  24907. return function () {
  24908. editor.off('init', init);
  24909. editor.off(event, handleEvent);
  24910. };
  24911. };
  24912. };
  24913. var onActionToggleFormat$1 = function (editor) {
  24914. return function (rawItem) {
  24915. return function () {
  24916. editor.undoManager.transact(function () {
  24917. editor.focus();
  24918. editor.execCommand('mceToggleFormat', false, rawItem.format);
  24919. });
  24920. };
  24921. };
  24922. };
  24923. var onActionExecCommand = function (editor, command) {
  24924. return function () {
  24925. return editor.execCommand(command);
  24926. };
  24927. };
  24928. var generateSelectItems = function (_editor, backstage, spec) {
  24929. var generateItem = function (rawItem, response, disabled, value) {
  24930. var translatedText = backstage.shared.providers.translate(rawItem.title);
  24931. if (rawItem.type === 'separator') {
  24932. return Optional.some({
  24933. type: 'separator',
  24934. text: translatedText
  24935. });
  24936. } else if (rawItem.type === 'submenu') {
  24937. var items = bind$3(rawItem.getStyleItems(), function (si) {
  24938. return validate(si, response, value);
  24939. });
  24940. if (response === 0 && items.length <= 0) {
  24941. return Optional.none();
  24942. } else {
  24943. return Optional.some({
  24944. type: 'nestedmenuitem',
  24945. text: translatedText,
  24946. disabled: items.length <= 0,
  24947. getSubmenuItems: function () {
  24948. return bind$3(rawItem.getStyleItems(), function (si) {
  24949. return validate(si, response, value);
  24950. });
  24951. }
  24952. });
  24953. }
  24954. } else {
  24955. return Optional.some(__assign({
  24956. type: 'togglemenuitem',
  24957. text: translatedText,
  24958. icon: rawItem.icon,
  24959. active: rawItem.isSelected(value),
  24960. disabled: disabled,
  24961. onAction: spec.onAction(rawItem)
  24962. }, rawItem.getStylePreview().fold(function () {
  24963. return {};
  24964. }, function (preview) {
  24965. return { meta: { style: preview } };
  24966. })));
  24967. }
  24968. };
  24969. var validate = function (item, response, value) {
  24970. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  24971. if (response === 0) {
  24972. return invalid ? [] : generateItem(item, response, false, value).toArray();
  24973. } else {
  24974. return generateItem(item, response, invalid, value).toArray();
  24975. }
  24976. };
  24977. var validateItems = function (preItems) {
  24978. var value = spec.getCurrentValue();
  24979. var response = spec.shouldHide ? 0 : 1;
  24980. return bind$3(preItems, function (item) {
  24981. return validate(item, response, value);
  24982. });
  24983. };
  24984. var getFetch = function (backstage, getStyleItems) {
  24985. return function (comp, callback) {
  24986. var preItems = getStyleItems();
  24987. var items = validateItems(preItems);
  24988. var menu = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  24989. callback(menu);
  24990. };
  24991. };
  24992. return {
  24993. validateItems: validateItems,
  24994. getFetch: getFetch
  24995. };
  24996. };
  24997. var createMenuItems = function (editor, backstage, spec) {
  24998. var dataset = spec.dataset;
  24999. var getStyleItems = dataset.type === 'basic' ? function () {
  25000. return map$2(dataset.data, function (d) {
  25001. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  25002. });
  25003. } : dataset.getData;
  25004. return {
  25005. items: generateSelectItems(editor, backstage, spec),
  25006. getStyleItems: getStyleItems
  25007. };
  25008. };
  25009. var createSelectButton = function (editor, backstage, spec) {
  25010. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  25011. var getApi = function (comp) {
  25012. return { getComponent: constant$1(comp) };
  25013. };
  25014. var onSetup = onSetupEvent(editor, 'NodeChange', function (api) {
  25015. var comp = api.getComponent();
  25016. spec.updateText(comp);
  25017. });
  25018. return renderCommonDropdown({
  25019. text: spec.icon.isSome() ? Optional.none() : spec.text,
  25020. icon: spec.icon,
  25021. tooltip: Optional.from(spec.tooltip),
  25022. role: Optional.none(),
  25023. fetch: items.getFetch(backstage, getStyleItems),
  25024. onSetup: onSetup,
  25025. getApi: getApi,
  25026. columns: 1,
  25027. presets: 'normal',
  25028. classes: spec.icon.isSome() ? [] : ['bespoke'],
  25029. dropdownBehaviours: []
  25030. }, 'tox-tbtn', backstage.shared);
  25031. };
  25032. var process = function (rawFormats) {
  25033. return map$2(rawFormats, function (item) {
  25034. var title = item, format = item;
  25035. var values = item.split('=');
  25036. if (values.length > 1) {
  25037. title = values[0];
  25038. format = values[1];
  25039. }
  25040. return {
  25041. title: title,
  25042. format: format
  25043. };
  25044. });
  25045. };
  25046. var buildBasicStaticDataset = function (data) {
  25047. return {
  25048. type: 'basic',
  25049. data: data
  25050. };
  25051. };
  25052. var Delimiter;
  25053. (function (Delimiter) {
  25054. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  25055. Delimiter[Delimiter['Space'] = 1] = 'Space';
  25056. }(Delimiter || (Delimiter = {})));
  25057. var split = function (rawFormats, delimiter) {
  25058. if (delimiter === Delimiter.SemiColon) {
  25059. return rawFormats.replace(/;$/, '').split(';');
  25060. } else {
  25061. return rawFormats.split(' ');
  25062. }
  25063. };
  25064. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  25065. var rawFormats = editor.getParam(settingName, defaults, 'string');
  25066. var data = process(split(rawFormats, delimiter));
  25067. return {
  25068. type: 'basic',
  25069. data: data
  25070. };
  25071. };
  25072. var alignMenuItems = [
  25073. {
  25074. title: 'Left',
  25075. icon: 'align-left',
  25076. format: 'alignleft',
  25077. command: 'JustifyLeft'
  25078. },
  25079. {
  25080. title: 'Center',
  25081. icon: 'align-center',
  25082. format: 'aligncenter',
  25083. command: 'JustifyCenter'
  25084. },
  25085. {
  25086. title: 'Right',
  25087. icon: 'align-right',
  25088. format: 'alignright',
  25089. command: 'JustifyRight'
  25090. },
  25091. {
  25092. title: 'Justify',
  25093. icon: 'align-justify',
  25094. format: 'alignjustify',
  25095. command: 'JustifyFull'
  25096. }
  25097. ];
  25098. var getSpec$4 = function (editor) {
  25099. var getMatchingValue = function () {
  25100. return find$5(alignMenuItems, function (item) {
  25101. return editor.formatter.match(item.format);
  25102. });
  25103. };
  25104. var isSelectedFor = function (format) {
  25105. return function () {
  25106. return editor.formatter.match(format);
  25107. };
  25108. };
  25109. var getPreviewFor = function (_format) {
  25110. return Optional.none;
  25111. };
  25112. var updateSelectMenuIcon = function (comp) {
  25113. var match = getMatchingValue();
  25114. var alignment = match.fold(constant$1('left'), function (item) {
  25115. return item.title.toLowerCase();
  25116. });
  25117. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  25118. };
  25119. var dataset = buildBasicStaticDataset(alignMenuItems);
  25120. var onAction = function (rawItem) {
  25121. return function () {
  25122. return find$5(alignMenuItems, function (item) {
  25123. return item.format === rawItem.format;
  25124. }).each(function (item) {
  25125. return editor.execCommand(item.command);
  25126. });
  25127. };
  25128. };
  25129. return {
  25130. tooltip: 'Align',
  25131. text: Optional.none(),
  25132. icon: Optional.some('align-left'),
  25133. isSelectedFor: isSelectedFor,
  25134. getCurrentValue: Optional.none,
  25135. getPreviewFor: getPreviewFor,
  25136. onAction: onAction,
  25137. updateText: updateSelectMenuIcon,
  25138. dataset: dataset,
  25139. shouldHide: false,
  25140. isInvalid: function (item) {
  25141. return !editor.formatter.canApply(item.format);
  25142. }
  25143. };
  25144. };
  25145. var createAlignSelect = function (editor, backstage) {
  25146. return createSelectButton(editor, backstage, getSpec$4(editor));
  25147. };
  25148. var alignSelectMenu = function (editor, backstage) {
  25149. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
  25150. editor.ui.registry.addNestedMenuItem('align', {
  25151. text: backstage.shared.providers.translate('Align'),
  25152. getSubmenuItems: function () {
  25153. return menuItems.items.validateItems(menuItems.getStyleItems());
  25154. }
  25155. });
  25156. };
  25157. var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats';
  25158. var systemStackFonts = [
  25159. '-apple-system',
  25160. 'Segoe UI',
  25161. 'Roboto',
  25162. 'Helvetica Neue',
  25163. 'sans-serif'
  25164. ];
  25165. var splitFonts = function (fontFamily) {
  25166. var fonts = fontFamily.split(/\s*,\s*/);
  25167. return map$2(fonts, function (font) {
  25168. return font.replace(/^['"]+|['"]+$/g, '');
  25169. });
  25170. };
  25171. var isSystemFontStack = function (fontFamily) {
  25172. var matchesSystemStack = function () {
  25173. var fonts = splitFonts(fontFamily.toLowerCase());
  25174. return forall(systemStackFonts, function (font) {
  25175. return fonts.indexOf(font.toLowerCase()) > -1;
  25176. });
  25177. };
  25178. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  25179. };
  25180. var getSpec$3 = function (editor) {
  25181. var systemFont = 'System Font';
  25182. var getMatchingValue = function () {
  25183. var getFirstFont = function (fontFamily) {
  25184. return fontFamily ? splitFonts(fontFamily)[0] : '';
  25185. };
  25186. var fontFamily = editor.queryCommandValue('FontName');
  25187. var items = dataset.data;
  25188. var font = fontFamily ? fontFamily.toLowerCase() : '';
  25189. var matchOpt = find$5(items, function (item) {
  25190. var format = item.format;
  25191. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  25192. }).orThunk(function () {
  25193. return someIf(isSystemFontStack(font), {
  25194. title: systemFont,
  25195. format: font
  25196. });
  25197. });
  25198. return {
  25199. matchOpt: matchOpt,
  25200. font: fontFamily
  25201. };
  25202. };
  25203. var isSelectedFor = function (item) {
  25204. return function (valueOpt) {
  25205. return valueOpt.exists(function (value) {
  25206. return value.format === item;
  25207. });
  25208. };
  25209. };
  25210. var getCurrentValue = function () {
  25211. var matchOpt = getMatchingValue().matchOpt;
  25212. return matchOpt;
  25213. };
  25214. var getPreviewFor = function (item) {
  25215. return function () {
  25216. return Optional.some({
  25217. tag: 'div',
  25218. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  25219. });
  25220. };
  25221. };
  25222. var onAction = function (rawItem) {
  25223. return function () {
  25224. editor.undoManager.transact(function () {
  25225. editor.focus();
  25226. editor.execCommand('FontName', false, rawItem.format);
  25227. });
  25228. };
  25229. };
  25230. var updateSelectMenuText = function (comp) {
  25231. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  25232. var text = matchOpt.fold(constant$1(font), function (item) {
  25233. return item.title;
  25234. });
  25235. emitWith(comp, updateMenuText, { text: text });
  25236. };
  25237. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  25238. return {
  25239. tooltip: 'Fonts',
  25240. text: Optional.some(systemFont),
  25241. icon: Optional.none(),
  25242. isSelectedFor: isSelectedFor,
  25243. getCurrentValue: getCurrentValue,
  25244. getPreviewFor: getPreviewFor,
  25245. onAction: onAction,
  25246. updateText: updateSelectMenuText,
  25247. dataset: dataset,
  25248. shouldHide: false,
  25249. isInvalid: never
  25250. };
  25251. };
  25252. var createFontSelect = function (editor, backstage) {
  25253. return createSelectButton(editor, backstage, getSpec$3(editor));
  25254. };
  25255. var fontSelectMenu = function (editor, backstage) {
  25256. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  25257. editor.ui.registry.addNestedMenuItem('fontformats', {
  25258. text: backstage.shared.providers.translate('Fonts'),
  25259. getSubmenuItems: function () {
  25260. return menuItems.items.validateItems(menuItems.getStyleItems());
  25261. }
  25262. });
  25263. };
  25264. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  25265. var legacyFontSizes = {
  25266. '8pt': '1',
  25267. '10pt': '2',
  25268. '12pt': '3',
  25269. '14pt': '4',
  25270. '18pt': '5',
  25271. '24pt': '6',
  25272. '36pt': '7'
  25273. };
  25274. var keywordFontSizes = {
  25275. 'xx-small': '7pt',
  25276. 'x-small': '8pt',
  25277. 'small': '10pt',
  25278. 'medium': '12pt',
  25279. 'large': '14pt',
  25280. 'x-large': '18pt',
  25281. 'xx-large': '24pt'
  25282. };
  25283. var round = function (number, precision) {
  25284. var factor = Math.pow(10, precision);
  25285. return Math.round(number * factor) / factor;
  25286. };
  25287. var toPt = function (fontSize, precision) {
  25288. if (/[0-9.]+px$/.test(fontSize)) {
  25289. return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  25290. } else {
  25291. return get$e(keywordFontSizes, fontSize).getOr(fontSize);
  25292. }
  25293. };
  25294. var toLegacy = function (fontSize) {
  25295. return get$e(legacyFontSizes, fontSize).getOr('');
  25296. };
  25297. var getSpec$2 = function (editor) {
  25298. var getMatchingValue = function () {
  25299. var matchOpt = Optional.none();
  25300. var items = dataset.data;
  25301. var fontSize = editor.queryCommandValue('FontSize');
  25302. if (fontSize) {
  25303. var _loop_1 = function (precision) {
  25304. var pt = toPt(fontSize, precision);
  25305. var legacy = toLegacy(pt);
  25306. matchOpt = find$5(items, function (item) {
  25307. return item.format === fontSize || item.format === pt || item.format === legacy;
  25308. });
  25309. };
  25310. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  25311. _loop_1(precision);
  25312. }
  25313. }
  25314. return {
  25315. matchOpt: matchOpt,
  25316. size: fontSize
  25317. };
  25318. };
  25319. var isSelectedFor = function (item) {
  25320. return function (valueOpt) {
  25321. return valueOpt.exists(function (value) {
  25322. return value.format === item;
  25323. });
  25324. };
  25325. };
  25326. var getCurrentValue = function () {
  25327. var matchOpt = getMatchingValue().matchOpt;
  25328. return matchOpt;
  25329. };
  25330. var getPreviewFor = constant$1(Optional.none);
  25331. var onAction = function (rawItem) {
  25332. return function () {
  25333. editor.undoManager.transact(function () {
  25334. editor.focus();
  25335. editor.execCommand('FontSize', false, rawItem.format);
  25336. });
  25337. };
  25338. };
  25339. var updateSelectMenuText = function (comp) {
  25340. var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  25341. var text = matchOpt.fold(constant$1(size), function (match) {
  25342. return match.title;
  25343. });
  25344. emitWith(comp, updateMenuText, { text: text });
  25345. };
  25346. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  25347. return {
  25348. tooltip: 'Font sizes',
  25349. text: Optional.some('12pt'),
  25350. icon: Optional.none(),
  25351. isSelectedFor: isSelectedFor,
  25352. getPreviewFor: getPreviewFor,
  25353. getCurrentValue: getCurrentValue,
  25354. onAction: onAction,
  25355. updateText: updateSelectMenuText,
  25356. dataset: dataset,
  25357. shouldHide: false,
  25358. isInvalid: never
  25359. };
  25360. };
  25361. var createFontsizeSelect = function (editor, backstage) {
  25362. return createSelectButton(editor, backstage, getSpec$2(editor));
  25363. };
  25364. var fontsizeSelectMenu = function (editor, backstage) {
  25365. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  25366. editor.ui.registry.addNestedMenuItem('fontsizes', {
  25367. text: 'Font sizes',
  25368. getSubmenuItems: function () {
  25369. return menuItems.items.validateItems(menuItems.getStyleItems());
  25370. }
  25371. });
  25372. };
  25373. var findNearest = function (editor, getStyles) {
  25374. var styles = getStyles();
  25375. var formats = map$2(styles, function (style) {
  25376. return style.format;
  25377. });
  25378. return Optional.from(editor.formatter.closest(formats)).bind(function (fmt) {
  25379. return find$5(styles, function (data) {
  25380. return data.format === fmt;
  25381. });
  25382. }).orThunk(function () {
  25383. return someIf(editor.formatter.match('p'), {
  25384. title: 'Paragraph',
  25385. format: 'p'
  25386. });
  25387. });
  25388. };
  25389. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  25390. var getSpec$1 = function (editor) {
  25391. var fallbackFormat = 'Paragraph';
  25392. var isSelectedFor = function (format) {
  25393. return function () {
  25394. return editor.formatter.match(format);
  25395. };
  25396. };
  25397. var getPreviewFor = function (format) {
  25398. return function () {
  25399. var fmt = editor.formatter.get(format);
  25400. return Optional.some({
  25401. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  25402. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  25403. });
  25404. };
  25405. };
  25406. var updateSelectMenuText = function (comp) {
  25407. var detectedFormat = findNearest(editor, function () {
  25408. return dataset.data;
  25409. });
  25410. var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  25411. return fmt.title;
  25412. });
  25413. emitWith(comp, updateMenuText, { text: text });
  25414. };
  25415. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  25416. return {
  25417. tooltip: 'Blocks',
  25418. text: Optional.some(fallbackFormat),
  25419. icon: Optional.none(),
  25420. isSelectedFor: isSelectedFor,
  25421. getCurrentValue: Optional.none,
  25422. getPreviewFor: getPreviewFor,
  25423. onAction: onActionToggleFormat$1(editor),
  25424. updateText: updateSelectMenuText,
  25425. dataset: dataset,
  25426. shouldHide: false,
  25427. isInvalid: function (item) {
  25428. return !editor.formatter.canApply(item.format);
  25429. }
  25430. };
  25431. };
  25432. var createFormatSelect = function (editor, backstage) {
  25433. return createSelectButton(editor, backstage, getSpec$1(editor));
  25434. };
  25435. var formatSelectMenu = function (editor, backstage) {
  25436. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  25437. editor.ui.registry.addNestedMenuItem('blockformats', {
  25438. text: 'Blocks',
  25439. getSubmenuItems: function () {
  25440. return menuItems.items.validateItems(menuItems.getStyleItems());
  25441. }
  25442. });
  25443. };
  25444. var getSpec = function (editor, dataset) {
  25445. var fallbackFormat = 'Paragraph';
  25446. var isSelectedFor = function (format) {
  25447. return function () {
  25448. return editor.formatter.match(format);
  25449. };
  25450. };
  25451. var getPreviewFor = function (format) {
  25452. return function () {
  25453. var fmt = editor.formatter.get(format);
  25454. return fmt !== undefined ? Optional.some({
  25455. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  25456. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  25457. }) : Optional.none();
  25458. };
  25459. };
  25460. var updateSelectMenuText = function (comp) {
  25461. var getFormatItems = function (fmt) {
  25462. var subs = fmt.items;
  25463. return subs !== undefined && subs.length > 0 ? bind$3(subs, getFormatItems) : [{
  25464. title: fmt.title,
  25465. format: fmt.format
  25466. }];
  25467. };
  25468. var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
  25469. var detectedFormat = findNearest(editor, constant$1(flattenedItems));
  25470. var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  25471. return fmt.title;
  25472. });
  25473. emitWith(comp, updateMenuText, { text: text });
  25474. };
  25475. return {
  25476. tooltip: 'Formats',
  25477. text: Optional.some(fallbackFormat),
  25478. icon: Optional.none(),
  25479. isSelectedFor: isSelectedFor,
  25480. getCurrentValue: Optional.none,
  25481. getPreviewFor: getPreviewFor,
  25482. onAction: onActionToggleFormat$1(editor),
  25483. updateText: updateSelectMenuText,
  25484. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  25485. isInvalid: function (item) {
  25486. return !editor.formatter.canApply(item.format);
  25487. },
  25488. dataset: dataset
  25489. };
  25490. };
  25491. var createStyleSelect = function (editor, backstage) {
  25492. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  25493. return createSelectButton(editor, backstage, getSpec(editor, dataset));
  25494. };
  25495. var styleSelectMenu = function (editor, backstage) {
  25496. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  25497. var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset));
  25498. editor.ui.registry.addNestedMenuItem('formats', {
  25499. text: 'Formats',
  25500. getSubmenuItems: function () {
  25501. return menuItems.items.validateItems(menuItems.getStyleItems());
  25502. }
  25503. });
  25504. };
  25505. var events$3 = function (reflectingConfig, reflectingState) {
  25506. var update = function (component, data) {
  25507. reflectingConfig.updateState.each(function (updateState) {
  25508. var newState = updateState(component, data);
  25509. reflectingState.set(newState);
  25510. });
  25511. reflectingConfig.renderComponents.each(function (renderComponents) {
  25512. var newComponents = renderComponents(data, reflectingState.get());
  25513. var newChildren = map$2(newComponents, component.getSystem().build);
  25514. replaceChildren(component, newChildren);
  25515. });
  25516. };
  25517. return derive$2([
  25518. run$1(receive(), function (component, message) {
  25519. var receivingData = message;
  25520. if (!receivingData.universal) {
  25521. var channel = reflectingConfig.channel;
  25522. if (contains$2(receivingData.channels, channel)) {
  25523. update(component, receivingData.data);
  25524. }
  25525. }
  25526. }),
  25527. runOnAttached(function (comp, _se) {
  25528. reflectingConfig.initialData.each(function (rawData) {
  25529. update(comp, rawData);
  25530. });
  25531. })
  25532. ]);
  25533. };
  25534. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  25535. __proto__: null,
  25536. events: events$3
  25537. });
  25538. var getState = function (component, replaceConfig, reflectState) {
  25539. return reflectState;
  25540. };
  25541. var ReflectingApis = /*#__PURE__*/Object.freeze({
  25542. __proto__: null,
  25543. getState: getState
  25544. });
  25545. var ReflectingSchema = [
  25546. required$1('channel'),
  25547. option('renderComponents'),
  25548. option('updateState'),
  25549. option('initialData')
  25550. ];
  25551. var init$3 = function () {
  25552. var cell = Cell(Optional.none());
  25553. var clear = function () {
  25554. return cell.set(Optional.none());
  25555. };
  25556. var readState = function () {
  25557. return cell.get().getOr('none');
  25558. };
  25559. return {
  25560. readState: readState,
  25561. get: cell.get,
  25562. set: cell.set,
  25563. clear: clear
  25564. };
  25565. };
  25566. var ReflectingState = /*#__PURE__*/Object.freeze({
  25567. __proto__: null,
  25568. init: init$3
  25569. });
  25570. var Reflecting = create$7({
  25571. fields: ReflectingSchema,
  25572. name: 'reflecting',
  25573. active: ActiveReflecting,
  25574. apis: ReflectingApis,
  25575. state: ReflectingState
  25576. });
  25577. var schema$7 = constant$1([
  25578. required$1('toggleClass'),
  25579. required$1('fetch'),
  25580. onStrictHandler('onExecute'),
  25581. defaulted('getHotspot', Optional.some),
  25582. defaulted('getAnchorOverrides', constant$1({})),
  25583. schema$y(),
  25584. onStrictHandler('onItemExecute'),
  25585. option('lazySink'),
  25586. required$1('dom'),
  25587. onHandler('onOpen'),
  25588. field('splitDropdownBehaviours', [
  25589. Coupling,
  25590. Keying,
  25591. Focusing
  25592. ]),
  25593. defaulted('matchWidth', false),
  25594. defaulted('useMinWidth', false),
  25595. defaulted('eventOrder', {}),
  25596. option('role')
  25597. ].concat(sandboxFields()));
  25598. var arrowPart = required({
  25599. factory: Button,
  25600. schema: [required$1('dom')],
  25601. name: 'arrow',
  25602. defaults: function () {
  25603. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  25604. },
  25605. overrides: function (detail) {
  25606. return {
  25607. dom: {
  25608. tag: 'span',
  25609. attributes: { role: 'presentation' }
  25610. },
  25611. action: function (arrow) {
  25612. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  25613. },
  25614. buttonBehaviours: derive$1([Toggling.config({
  25615. toggleOnExecute: false,
  25616. toggleClass: detail.toggleClass
  25617. })])
  25618. };
  25619. }
  25620. });
  25621. var buttonPart = required({
  25622. factory: Button,
  25623. schema: [required$1('dom')],
  25624. name: 'button',
  25625. defaults: function () {
  25626. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  25627. },
  25628. overrides: function (detail) {
  25629. return {
  25630. dom: {
  25631. tag: 'span',
  25632. attributes: { role: 'presentation' }
  25633. },
  25634. action: function (btn) {
  25635. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  25636. detail.onExecute(splitDropdown, btn);
  25637. });
  25638. }
  25639. };
  25640. }
  25641. });
  25642. var parts$3 = constant$1([
  25643. arrowPart,
  25644. buttonPart,
  25645. optional({
  25646. factory: {
  25647. sketch: function (spec) {
  25648. return {
  25649. uid: spec.uid,
  25650. dom: {
  25651. tag: 'span',
  25652. styles: { display: 'none' },
  25653. attributes: { 'aria-hidden': 'true' },
  25654. innerHtml: spec.text
  25655. }
  25656. };
  25657. }
  25658. },
  25659. schema: [required$1('text')],
  25660. name: 'aria-descriptor'
  25661. }),
  25662. external$1({
  25663. schema: [tieredMenuMarkers()],
  25664. name: 'menu',
  25665. defaults: function (detail) {
  25666. return {
  25667. onExecute: function (tmenu, item) {
  25668. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  25669. detail.onItemExecute(splitDropdown, tmenu, item);
  25670. });
  25671. }
  25672. };
  25673. }
  25674. }),
  25675. partType$1()
  25676. ]);
  25677. var factory$5 = function (detail, components, spec, externals) {
  25678. var _a;
  25679. var switchToMenu = function (sandbox) {
  25680. Composing.getCurrent(sandbox).each(function (current) {
  25681. Highlighting.highlightFirst(current);
  25682. Keying.focusIn(current);
  25683. });
  25684. };
  25685. var action = function (component) {
  25686. var onOpenSync = switchToMenu;
  25687. togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  25688. };
  25689. var openMenu = function (comp) {
  25690. action(comp);
  25691. return Optional.some(true);
  25692. };
  25693. var executeOnButton = function (comp) {
  25694. var button = getPartOrDie(comp, detail, 'button');
  25695. emitExecute(button);
  25696. return Optional.some(true);
  25697. };
  25698. var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function (component, _simulatedEvent) {
  25699. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  25700. ariaDescriptor.each(function (descriptor) {
  25701. var descriptorId = generate$6('aria');
  25702. set$7(descriptor.element, 'id', descriptorId);
  25703. set$7(component.element, 'aria-describedby', descriptorId);
  25704. });
  25705. })])), events$a(Optional.some(action)));
  25706. var apis = {
  25707. repositionMenus: function (comp) {
  25708. if (Toggling.isOn(comp)) {
  25709. repositionMenus(comp);
  25710. }
  25711. }
  25712. };
  25713. return {
  25714. uid: detail.uid,
  25715. dom: detail.dom,
  25716. components: components,
  25717. apis: apis,
  25718. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  25719. 'disabling',
  25720. 'toggling',
  25721. 'alloy.base.behaviour'
  25722. ], _a)),
  25723. events: buttonEvents,
  25724. behaviours: augment(detail.splitDropdownBehaviours, [
  25725. Coupling.config({
  25726. others: {
  25727. sandbox: function (hotspot) {
  25728. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  25729. var extras = {
  25730. onOpen: function () {
  25731. Toggling.on(arrow);
  25732. Toggling.on(hotspot);
  25733. },
  25734. onClose: function () {
  25735. Toggling.off(arrow);
  25736. Toggling.off(hotspot);
  25737. }
  25738. };
  25739. return makeSandbox$1(detail, hotspot, extras);
  25740. }
  25741. }
  25742. }),
  25743. Keying.config({
  25744. mode: 'special',
  25745. onSpace: executeOnButton,
  25746. onEnter: executeOnButton,
  25747. onDown: openMenu
  25748. }),
  25749. Focusing.config({}),
  25750. Toggling.config({
  25751. toggleOnExecute: false,
  25752. aria: { mode: 'expanded' }
  25753. })
  25754. ]),
  25755. domModification: {
  25756. attributes: {
  25757. 'role': detail.role.getOr('button'),
  25758. 'aria-haspopup': true
  25759. }
  25760. }
  25761. };
  25762. };
  25763. var SplitDropdown = composite({
  25764. name: 'SplitDropdown',
  25765. configFields: schema$7(),
  25766. partFields: parts$3(),
  25767. factory: factory$5,
  25768. apis: {
  25769. repositionMenus: function (apis, comp) {
  25770. return apis.repositionMenus(comp);
  25771. }
  25772. }
  25773. });
  25774. var getButtonApi = function (component) {
  25775. return {
  25776. isDisabled: function () {
  25777. return Disabling.isDisabled(component);
  25778. },
  25779. setDisabled: function (state) {
  25780. return Disabling.set(component, state);
  25781. }
  25782. };
  25783. };
  25784. var getToggleApi = function (component) {
  25785. return {
  25786. setActive: function (state) {
  25787. Toggling.set(component, state);
  25788. },
  25789. isActive: function () {
  25790. return Toggling.isOn(component);
  25791. },
  25792. isDisabled: function () {
  25793. return Disabling.isDisabled(component);
  25794. },
  25795. setDisabled: function (state) {
  25796. return Disabling.set(component, state);
  25797. }
  25798. };
  25799. };
  25800. var getTooltipAttributes = function (tooltip, providersBackstage) {
  25801. return tooltip.map(function (tooltip) {
  25802. return {
  25803. 'aria-label': providersBackstage.translate(tooltip),
  25804. 'title': providersBackstage.translate(tooltip)
  25805. };
  25806. }).getOr({});
  25807. };
  25808. var focusButtonEvent = generate$6('focus-button');
  25809. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  25810. var _d;
  25811. return {
  25812. dom: {
  25813. tag: 'button',
  25814. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []),
  25815. attributes: getTooltipAttributes(tooltip, providersBackstage)
  25816. },
  25817. components: componentRenderPipeline([
  25818. icon.map(function (iconName) {
  25819. return renderIconFromPack(iconName, providersBackstage.icons);
  25820. }),
  25821. text.map(function (text) {
  25822. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  25823. })
  25824. ]),
  25825. eventOrder: (_d = {}, _d[mousedown()] = [
  25826. 'focusing',
  25827. 'alloy.base.behaviour',
  25828. 'common-button-display-events'
  25829. ], _d),
  25830. buttonBehaviours: derive$1([
  25831. DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
  25832. receivingConfig(),
  25833. config('common-button-display-events', [run$1(mousedown(), function (button, se) {
  25834. se.event.prevent();
  25835. emit(button, focusButtonEvent);
  25836. })])
  25837. ].concat(receiver.map(function (r) {
  25838. return Reflecting.config({
  25839. channel: r,
  25840. initialData: {
  25841. icon: icon,
  25842. text: text
  25843. },
  25844. renderComponents: function (data, _state) {
  25845. return componentRenderPipeline([
  25846. data.icon.map(function (iconName) {
  25847. return renderIconFromPack(iconName, providersBackstage.icons);
  25848. }),
  25849. data.text.map(function (text) {
  25850. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  25851. })
  25852. ]);
  25853. }
  25854. });
  25855. }).toArray()).concat(behaviours.getOr([])))
  25856. };
  25857. };
  25858. var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  25859. var sharedBackstage = backstage.shared;
  25860. return FloatingToolbarButton.sketch({
  25861. lazySink: sharedBackstage.getSink,
  25862. fetch: function () {
  25863. return Future.nu(function (resolve) {
  25864. resolve(map$2(identifyButtons(spec.items), renderToolbarGroup));
  25865. });
  25866. },
  25867. markers: { toggledClass: 'tox-tbtn--enabled' },
  25868. parts: {
  25869. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
  25870. toolbar: {
  25871. dom: {
  25872. tag: 'div',
  25873. classes: ['tox-toolbar__overflow'],
  25874. attributes: attributes
  25875. }
  25876. }
  25877. }
  25878. });
  25879. };
  25880. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  25881. var editorOffCell = Cell(noop);
  25882. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
  25883. return Button.sketch({
  25884. dom: structure.dom,
  25885. components: structure.components,
  25886. eventOrder: toolbarButtonEventOrder,
  25887. buttonBehaviours: derive$1([
  25888. config('toolbar-button-events', [
  25889. onToolbarButtonExecute({
  25890. onAction: spec.onAction,
  25891. getApi: specialisation.getApi
  25892. }),
  25893. onControlAttached(specialisation, editorOffCell),
  25894. onControlDetached(specialisation, editorOffCell)
  25895. ]),
  25896. DisablingConfigs.toolbarButton(function () {
  25897. return spec.disabled || providersBackstage.isDisabled();
  25898. }),
  25899. receivingConfig()
  25900. ].concat(specialisation.toolbarButtonBehaviours))
  25901. });
  25902. };
  25903. var renderToolbarButton = function (spec, providersBackstage) {
  25904. return renderToolbarButtonWith(spec, providersBackstage, []);
  25905. };
  25906. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  25907. return renderCommonToolbarButton(spec, {
  25908. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  25909. getApi: getButtonApi,
  25910. onSetup: spec.onSetup
  25911. }, providersBackstage);
  25912. };
  25913. var renderToolbarToggleButton = function (spec, providersBackstage) {
  25914. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  25915. };
  25916. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  25917. return deepMerge(renderCommonToolbarButton(spec, {
  25918. toolbarButtonBehaviours: [
  25919. Replacing.config({}),
  25920. Toggling.config({
  25921. toggleClass: 'tox-tbtn--enabled',
  25922. aria: { mode: 'pressed' },
  25923. toggleOnExecute: false
  25924. })
  25925. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  25926. getApi: getToggleApi,
  25927. onSetup: spec.onSetup
  25928. }, providersBackstage));
  25929. };
  25930. var fetchChoices = function (getApi, spec, providersBackstage) {
  25931. return function (comp) {
  25932. return Future.nu(function (callback) {
  25933. return spec.fetch(callback);
  25934. }).map(function (items) {
  25935. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  25936. spec.onItemAction(getApi(comp), value);
  25937. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
  25938. movement: deriveMenuMovement(spec.columns, spec.presets),
  25939. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  25940. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
  25941. var numRows = _d.numRows, numColumns = _d.numColumns;
  25942. Keying.setGridSize(comp, numRows, numColumns);
  25943. });
  25944. })])
  25945. })));
  25946. });
  25947. };
  25948. };
  25949. var renderSplitButton = function (spec, sharedBackstage) {
  25950. var _d;
  25951. var displayChannel = generate$6('channel-update-split-dropdown-display');
  25952. var getApi = function (comp) {
  25953. return {
  25954. isDisabled: function () {
  25955. return Disabling.isDisabled(comp);
  25956. },
  25957. setDisabled: function (state) {
  25958. return Disabling.set(comp, state);
  25959. },
  25960. setIconFill: function (id, value) {
  25961. descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  25962. set$7(underlinePath, 'fill', value);
  25963. });
  25964. },
  25965. setIconStroke: function (id, value) {
  25966. descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  25967. set$7(underlinePath, 'stroke', value);
  25968. });
  25969. },
  25970. setActive: function (state) {
  25971. set$7(comp.element, 'aria-pressed', state);
  25972. descendant(comp.element, 'span').each(function (button) {
  25973. comp.getSystem().getByDom(button).each(function (buttonComp) {
  25974. return Toggling.set(buttonComp, state);
  25975. });
  25976. });
  25977. },
  25978. isActive: function () {
  25979. return descendant(comp.element, 'span').exists(function (button) {
  25980. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  25981. });
  25982. }
  25983. };
  25984. };
  25985. var editorOffCell = Cell(noop);
  25986. var specialisation = {
  25987. getApi: getApi,
  25988. onSetup: spec.onSetup
  25989. };
  25990. return SplitDropdown.sketch({
  25991. dom: {
  25992. tag: 'div',
  25993. classes: ['tox-split-button'],
  25994. attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  25995. },
  25996. onExecute: function (button) {
  25997. spec.onAction(getApi(button));
  25998. },
  25999. onItemExecute: function (_a, _b, _c) {
  26000. },
  26001. splitDropdownBehaviours: derive$1([
  26002. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  26003. receivingConfig(),
  26004. config('split-dropdown-events', [
  26005. run$1(focusButtonEvent, Focusing.focus),
  26006. onControlAttached(specialisation, editorOffCell),
  26007. onControlDetached(specialisation, editorOffCell)
  26008. ]),
  26009. Unselecting.config({})
  26010. ]),
  26011. eventOrder: (_d = {}, _d[attachedToDom()] = [
  26012. 'alloy.base.behaviour',
  26013. 'split-dropdown-events'
  26014. ], _d),
  26015. toggleClass: 'tox-tbtn--enabled',
  26016. lazySink: sharedBackstage.getSink,
  26017. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  26018. parts: { menu: part(false, spec.columns, spec.presets) },
  26019. components: [
  26020. SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
  26021. toggleClass: 'tox-tbtn--enabled',
  26022. toggleOnExecute: false
  26023. })]), sharedBackstage.providers)),
  26024. SplitDropdown.parts.arrow({
  26025. dom: {
  26026. tag: 'button',
  26027. classes: [
  26028. 'tox-tbtn',
  26029. 'tox-split-button__chevron'
  26030. ],
  26031. innerHtml: get$1('chevron-down', sharedBackstage.providers.icons)
  26032. },
  26033. buttonBehaviours: derive$1([
  26034. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  26035. receivingConfig(),
  26036. addFocusableBehaviour()
  26037. ])
  26038. }),
  26039. SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  26040. ]
  26041. });
  26042. };
  26043. var defaultToolbar = [
  26044. {
  26045. name: 'history',
  26046. items: [
  26047. 'undo',
  26048. 'redo'
  26049. ]
  26050. },
  26051. {
  26052. name: 'styles',
  26053. items: ['styleselect']
  26054. },
  26055. {
  26056. name: 'formatting',
  26057. items: [
  26058. 'bold',
  26059. 'italic'
  26060. ]
  26061. },
  26062. {
  26063. name: 'alignment',
  26064. items: [
  26065. 'alignleft',
  26066. 'aligncenter',
  26067. 'alignright',
  26068. 'alignjustify'
  26069. ]
  26070. },
  26071. {
  26072. name: 'indentation',
  26073. items: [
  26074. 'outdent',
  26075. 'indent'
  26076. ]
  26077. },
  26078. {
  26079. name: 'permanent pen',
  26080. items: ['permanentpen']
  26081. },
  26082. {
  26083. name: 'comments',
  26084. items: ['addcomment']
  26085. }
  26086. ];
  26087. var renderFromBridge = function (bridgeBuilder, render) {
  26088. return function (spec, extras, editor) {
  26089. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  26090. return formatError(errInfo);
  26091. }).getOrDie();
  26092. return render(internal, extras, editor);
  26093. };
  26094. };
  26095. var types = {
  26096. button: renderFromBridge(createToolbarButton, function (s, extras) {
  26097. return renderToolbarButton(s, extras.backstage.shared.providers);
  26098. }),
  26099. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  26100. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  26101. }),
  26102. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  26103. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none());
  26104. }),
  26105. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  26106. return renderSplitButton(s, extras.backstage.shared);
  26107. }),
  26108. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  26109. var _a;
  26110. var buttons = editor.ui.registry.getAll().buttons;
  26111. var identify = function (toolbar) {
  26112. return identifyButtons(editor, {
  26113. buttons: buttons,
  26114. toolbar: toolbar,
  26115. allowToolbarGroups: false
  26116. }, extras, Optional.none());
  26117. };
  26118. var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  26119. switch (getToolbarMode(editor)) {
  26120. case ToolbarMode.floating:
  26121. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  26122. default:
  26123. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  26124. }
  26125. }),
  26126. styleSelectButton: function (editor, extras) {
  26127. return createStyleSelect(editor, extras.backstage);
  26128. },
  26129. fontsizeSelectButton: function (editor, extras) {
  26130. return createFontsizeSelect(editor, extras.backstage);
  26131. },
  26132. fontSelectButton: function (editor, extras) {
  26133. return createFontSelect(editor, extras.backstage);
  26134. },
  26135. formatButton: function (editor, extras) {
  26136. return createFormatSelect(editor, extras.backstage);
  26137. },
  26138. alignMenuButton: function (editor, extras) {
  26139. return createAlignSelect(editor, extras.backstage);
  26140. }
  26141. };
  26142. var extractFrom = function (spec, extras, editor) {
  26143. return get$e(types, spec.type).fold(function () {
  26144. console.error('skipping button defined by', spec);
  26145. return Optional.none();
  26146. }, function (render) {
  26147. return Optional.some(render(spec, extras, editor));
  26148. });
  26149. };
  26150. var bespokeButtons = {
  26151. styleselect: types.styleSelectButton,
  26152. fontsizeselect: types.fontsizeSelectButton,
  26153. fontselect: types.fontSelectButton,
  26154. formatselect: types.formatButton,
  26155. align: types.alignMenuButton
  26156. };
  26157. var removeUnusedDefaults = function (buttons) {
  26158. var filteredItemGroups = map$2(defaultToolbar, function (group) {
  26159. var items = filter$2(group.items, function (subItem) {
  26160. return has$2(buttons, subItem) || has$2(bespokeButtons, subItem);
  26161. });
  26162. return {
  26163. name: group.name,
  26164. items: items
  26165. };
  26166. });
  26167. return filter$2(filteredItemGroups, function (group) {
  26168. return group.items.length > 0;
  26169. });
  26170. };
  26171. var convertStringToolbar = function (strToolbar) {
  26172. var groupsStrings = strToolbar.split('|');
  26173. return map$2(groupsStrings, function (g) {
  26174. return { items: g.trim().split(' ') };
  26175. });
  26176. };
  26177. var isToolbarGroupSettingArray = function (toolbar) {
  26178. return isArrayOf(toolbar, function (t) {
  26179. return has$2(t, 'name') && has$2(t, 'items');
  26180. });
  26181. };
  26182. var createToolbar = function (toolbarConfig) {
  26183. var toolbar = toolbarConfig.toolbar;
  26184. var buttons = toolbarConfig.buttons;
  26185. if (toolbar === false) {
  26186. return [];
  26187. } else if (toolbar === undefined || toolbar === true) {
  26188. return removeUnusedDefaults(buttons);
  26189. } else if (isString(toolbar)) {
  26190. return convertStringToolbar(toolbar);
  26191. } else if (isToolbarGroupSettingArray(toolbar)) {
  26192. return toolbar;
  26193. } else {
  26194. console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  26195. return [];
  26196. }
  26197. };
  26198. var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  26199. return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  26200. return prefixes.bind(function (ps) {
  26201. return findMap(ps, function (prefix) {
  26202. return get$e(buttons, prefix + toolbarItem.toLowerCase());
  26203. });
  26204. });
  26205. }).fold(function () {
  26206. return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  26207. return r(editor, extras);
  26208. }).orThunk(function () {
  26209. return Optional.none();
  26210. });
  26211. }, function (spec) {
  26212. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  26213. console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  26214. return Optional.none();
  26215. } else {
  26216. return extractFrom(spec, extras, editor);
  26217. }
  26218. });
  26219. };
  26220. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  26221. var toolbarGroups = createToolbar(toolbarConfig);
  26222. var groups = map$2(toolbarGroups, function (group) {
  26223. var items = bind$3(group.items, function (toolbarItem) {
  26224. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  26225. });
  26226. return {
  26227. title: Optional.from(editor.translate(group.name)),
  26228. items: items
  26229. };
  26230. });
  26231. return filter$2(groups, function (group) {
  26232. return group.items.length > 0;
  26233. });
  26234. };
  26235. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  26236. var comp = uiComponents.outerContainer;
  26237. var toolbarConfig = rawUiConfig.toolbar;
  26238. var toolbarButtonsConfig = rawUiConfig.buttons;
  26239. if (isArrayOf(toolbarConfig, isString)) {
  26240. var toolbars = toolbarConfig.map(function (t) {
  26241. var config = {
  26242. toolbar: t,
  26243. buttons: toolbarButtonsConfig,
  26244. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  26245. };
  26246. return identifyButtons(editor, config, { backstage: backstage }, Optional.none());
  26247. });
  26248. OuterContainer.setToolbars(comp, toolbars);
  26249. } else {
  26250. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none()));
  26251. }
  26252. };
  26253. var detection = detect$1();
  26254. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  26255. var setupEvents$1 = function (editor, uiComponents) {
  26256. var dom = editor.dom;
  26257. var contentWindow = editor.getWin();
  26258. var initialDocEle = editor.getDoc().documentElement;
  26259. var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  26260. var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  26261. var resizeWindow = function () {
  26262. var outer = lastWindowDimensions.get();
  26263. if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
  26264. lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  26265. fireResizeContent(editor);
  26266. }
  26267. };
  26268. var resizeDocument = function () {
  26269. var docEle = editor.getDoc().documentElement;
  26270. var inner = lastDocumentDimensions.get();
  26271. if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
  26272. lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
  26273. fireResizeContent(editor);
  26274. }
  26275. };
  26276. var scroll = function (e) {
  26277. return fireScrollContent(editor, e);
  26278. };
  26279. dom.bind(contentWindow, 'resize', resizeWindow);
  26280. dom.bind(contentWindow, 'scroll', scroll);
  26281. var elementLoad = capture(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
  26282. var mothership = uiComponents.uiMothership.element;
  26283. editor.on('hide', function () {
  26284. set$6(mothership, 'display', 'none');
  26285. });
  26286. editor.on('show', function () {
  26287. remove$1(mothership, 'display');
  26288. });
  26289. editor.on('NodeChange', resizeDocument);
  26290. editor.on('remove', function () {
  26291. elementLoad.unbind();
  26292. dom.unbind(contentWindow, 'resize', resizeWindow);
  26293. dom.unbind(contentWindow, 'scroll', scroll);
  26294. contentWindow = null;
  26295. });
  26296. };
  26297. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26298. var lastToolbarWidth = Cell(0);
  26299. var outerContainer = uiComponents.outerContainer;
  26300. iframe(editor);
  26301. var eTargetNode = SugarElement.fromDom(args.targetNode);
  26302. var uiRoot = getContentContainer(getRootNode(eTargetNode));
  26303. attachSystemAfter(eTargetNode, uiComponents.mothership);
  26304. attachSystem(uiRoot, uiComponents.uiMothership);
  26305. editor.on('PostRender', function () {
  26306. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26307. lastToolbarWidth.set(editor.getWin().innerWidth);
  26308. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26309. OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
  26310. setupEvents$1(editor, uiComponents);
  26311. });
  26312. var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
  26313. if (isiOS12) {
  26314. setAll(socket.element, {
  26315. 'overflow': 'scroll',
  26316. '-webkit-overflow-scrolling': 'touch'
  26317. });
  26318. var limit = first(function () {
  26319. editor.fire('ScrollContent');
  26320. }, 20);
  26321. var unbinder = bind(socket.element, 'scroll', limit.throttle);
  26322. editor.on('remove', unbinder.unbind);
  26323. }
  26324. setupReadonlyModeSwitch(editor, uiComponents);
  26325. editor.addCommand('ToggleSidebar', function (_ui, value) {
  26326. OuterContainer.toggleSidebar(outerContainer, value);
  26327. editor.fire('ToggleSidebar');
  26328. });
  26329. editor.addQueryValueHandler('ToggleSidebar', function () {
  26330. return OuterContainer.whichSidebar(outerContainer);
  26331. });
  26332. var toolbarMode = getToolbarMode(editor);
  26333. var refreshDrawer = function () {
  26334. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  26335. };
  26336. if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  26337. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  26338. var width = editor.getWin().innerWidth;
  26339. if (width !== lastToolbarWidth.get()) {
  26340. refreshDrawer();
  26341. lastToolbarWidth.set(width);
  26342. }
  26343. });
  26344. }
  26345. var api = {
  26346. enable: function () {
  26347. broadcastReadonly(uiComponents, false);
  26348. },
  26349. disable: function () {
  26350. broadcastReadonly(uiComponents, true);
  26351. },
  26352. isDisabled: function () {
  26353. return Disabling.isDisabled(outerContainer);
  26354. }
  26355. };
  26356. return {
  26357. iframeContainer: socket.element.dom,
  26358. editorContainer: outerContainer.element.dom,
  26359. api: api
  26360. };
  26361. };
  26362. var Iframe = /*#__PURE__*/Object.freeze({
  26363. __proto__: null,
  26364. render: render$1
  26365. });
  26366. var parseToInt = function (val) {
  26367. var re = /^[0-9\.]+(|px)$/i;
  26368. if (re.test('' + val)) {
  26369. return Optional.some(parseInt('' + val, 10));
  26370. }
  26371. return Optional.none();
  26372. };
  26373. var numToPx = function (val) {
  26374. return isNumber(val) ? val + 'px' : val;
  26375. };
  26376. var calcCappedSize = function (size, minSize, maxSize) {
  26377. var minOverride = minSize.filter(function (min) {
  26378. return size < min;
  26379. });
  26380. var maxOverride = maxSize.filter(function (max) {
  26381. return size > max;
  26382. });
  26383. return minOverride.or(maxOverride).getOr(size);
  26384. };
  26385. var getHeight = function (editor) {
  26386. var baseHeight = getHeightSetting(editor);
  26387. var minHeight = getMinHeightSetting(editor);
  26388. var maxHeight = getMaxHeightSetting(editor);
  26389. return parseToInt(baseHeight).map(function (height) {
  26390. return calcCappedSize(height, minHeight, maxHeight);
  26391. });
  26392. };
  26393. var getHeightWithFallback = function (editor) {
  26394. var height = getHeight(editor);
  26395. return height.getOr(getHeightSetting(editor));
  26396. };
  26397. var getWidth = function (editor) {
  26398. var baseWidth = getWidthSetting(editor);
  26399. var minWidth = getMinWidthSetting(editor);
  26400. var maxWidth = getMaxWidthSetting(editor);
  26401. return parseToInt(baseWidth).map(function (width) {
  26402. return calcCappedSize(width, minWidth, maxWidth);
  26403. });
  26404. };
  26405. var getWidthWithFallback = function (editor) {
  26406. var width = getWidth(editor);
  26407. return width.getOr(getWidthSetting(editor));
  26408. };
  26409. var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
  26410. var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26411. var DOM = global$c.DOM;
  26412. var useFixedToolbarContainer = useFixedContainer(editor);
  26413. var isSticky = isStickyToolbar(editor);
  26414. var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor));
  26415. var headerBackstage = backstage.shared.header;
  26416. var isPositionedAtTop = headerBackstage.isPositionedAtTop;
  26417. var toolbarMode = getToolbarMode(editor);
  26418. var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  26419. var visible = Cell(false);
  26420. var isVisible = function () {
  26421. return visible.get() && !editor.removed;
  26422. };
  26423. var calcToolbarOffset = function (toolbar) {
  26424. return isSplitToolbar ? toolbar.fold(constant$1(0), function (tbar) {
  26425. return tbar.components().length > 1 ? get$8(tbar.components()[1].element) : 0;
  26426. }) : 0;
  26427. };
  26428. var calcMode = function (container) {
  26429. switch (getToolbarLocation(editor)) {
  26430. case ToolbarLocation.auto:
  26431. var toolbar_1 = OuterContainer.getToolbar(outerContainer);
  26432. var offset = calcToolbarOffset(toolbar_1);
  26433. var toolbarHeight = get$8(container.element) - offset;
  26434. var targetBounds = box$1(targetElm);
  26435. var roomAtTop = targetBounds.y > toolbarHeight;
  26436. if (roomAtTop) {
  26437. return 'top';
  26438. } else {
  26439. var doc = documentElement(targetElm);
  26440. var docHeight = Math.max(doc.dom.scrollHeight, get$8(doc));
  26441. var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  26442. if (roomAtBottom) {
  26443. return 'bottom';
  26444. } else {
  26445. var winBounds = win();
  26446. var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  26447. return isRoomAtBottomViewport ? 'bottom' : 'top';
  26448. }
  26449. }
  26450. case ToolbarLocation.bottom:
  26451. return 'bottom';
  26452. case ToolbarLocation.top:
  26453. default:
  26454. return 'top';
  26455. }
  26456. };
  26457. var setupMode = function (mode) {
  26458. var container = floatContainer.get();
  26459. Docking.setModes(container, [mode]);
  26460. headerBackstage.setDockingMode(mode);
  26461. var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  26462. set$7(container.element, Attribute, verticalDir);
  26463. };
  26464. var updateChromeWidth = function () {
  26465. var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  26466. var bodyMargin = parseToInt(get$a(body(), 'margin-left')).getOr(0);
  26467. return get$7(body()) - absolute$3(targetElm).left + bodyMargin;
  26468. });
  26469. set$6(floatContainer.get().element, 'max-width', maxWidth + 'px');
  26470. };
  26471. var updateChromePosition = function () {
  26472. var toolbar = OuterContainer.getToolbar(outerContainer);
  26473. var offset = calcToolbarOffset(toolbar);
  26474. var targetBounds = box$1(targetElm);
  26475. var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$8(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
  26476. setAll(outerContainer.element, {
  26477. position: 'absolute',
  26478. top: Math.round(top) + 'px',
  26479. left: Math.round(targetBounds.x) + 'px'
  26480. });
  26481. };
  26482. var repositionPopups$1 = function () {
  26483. uiMothership.broadcastOn([repositionPopups()], {});
  26484. };
  26485. var updateChromeUi = function (resetDocking) {
  26486. if (resetDocking === void 0) {
  26487. resetDocking = false;
  26488. }
  26489. if (!isVisible()) {
  26490. return;
  26491. }
  26492. if (!useFixedToolbarContainer) {
  26493. updateChromeWidth();
  26494. }
  26495. if (isSplitToolbar) {
  26496. OuterContainer.refreshToolbar(outerContainer);
  26497. }
  26498. if (!useFixedToolbarContainer) {
  26499. updateChromePosition();
  26500. }
  26501. if (isSticky) {
  26502. var floatContainerComp = floatContainer.get();
  26503. resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  26504. }
  26505. repositionPopups$1();
  26506. };
  26507. var updateMode = function (updateUi) {
  26508. if (updateUi === void 0) {
  26509. updateUi = true;
  26510. }
  26511. if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  26512. return;
  26513. }
  26514. var currentMode = headerBackstage.getDockingMode();
  26515. var newMode = calcMode(floatContainer.get());
  26516. if (newMode !== currentMode) {
  26517. setupMode(newMode);
  26518. if (updateUi) {
  26519. updateChromeUi(true);
  26520. }
  26521. }
  26522. };
  26523. var show = function () {
  26524. visible.set(true);
  26525. set$6(outerContainer.element, 'display', 'flex');
  26526. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  26527. remove$1(uiMothership.element, 'display');
  26528. updateMode(false);
  26529. updateChromeUi();
  26530. };
  26531. var hide = function () {
  26532. visible.set(false);
  26533. if (uiComponents.outerContainer) {
  26534. set$6(outerContainer.element, 'display', 'none');
  26535. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  26536. }
  26537. set$6(uiMothership.element, 'display', 'none');
  26538. };
  26539. return {
  26540. isVisible: isVisible,
  26541. isPositionedAtTop: isPositionedAtTop,
  26542. show: show,
  26543. hide: hide,
  26544. update: updateChromeUi,
  26545. updateMode: updateMode,
  26546. repositionPopups: repositionPopups$1
  26547. };
  26548. };
  26549. var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
  26550. var bounds = box$1(targetElm);
  26551. return {
  26552. pos: isToolbarTop ? bounds.y : bounds.bottom,
  26553. bounds: bounds
  26554. };
  26555. };
  26556. var setupEvents = function (editor, targetElm, ui, toolbarPersist) {
  26557. var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  26558. var resizeContent = function (e) {
  26559. var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
  26560. var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
  26561. var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  26562. prevPosAndBounds.set({
  26563. pos: pos,
  26564. bounds: bounds
  26565. });
  26566. if (hasResized) {
  26567. fireResizeContent(editor, e);
  26568. }
  26569. if (ui.isVisible()) {
  26570. if (prevPos !== pos) {
  26571. ui.update(true);
  26572. } else if (hasResized) {
  26573. ui.updateMode();
  26574. ui.repositionPopups();
  26575. }
  26576. }
  26577. };
  26578. if (!toolbarPersist) {
  26579. editor.on('activate', ui.show);
  26580. editor.on('deactivate', ui.hide);
  26581. }
  26582. editor.on('SkinLoaded ResizeWindow', function () {
  26583. return ui.update(true);
  26584. });
  26585. editor.on('NodeChange keydown', function (e) {
  26586. global$g.requestAnimationFrame(function () {
  26587. return resizeContent(e);
  26588. });
  26589. });
  26590. editor.on('ScrollWindow', function () {
  26591. return ui.updateMode();
  26592. });
  26593. var elementLoad = unbindable();
  26594. elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
  26595. editor.on('remove', function () {
  26596. elementLoad.clear();
  26597. });
  26598. };
  26599. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26600. var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26601. var floatContainer = Cell(null);
  26602. var targetElm = SugarElement.fromDom(args.targetNode);
  26603. var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  26604. var toolbarPersist = isToolbarPersist(editor);
  26605. inline(editor);
  26606. var render = function () {
  26607. if (floatContainer.get()) {
  26608. ui.show();
  26609. return;
  26610. }
  26611. floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  26612. var uiContainer = getUiContainer(editor);
  26613. attachSystem(uiContainer, mothership);
  26614. attachSystem(uiContainer, uiMothership);
  26615. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26616. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26617. ui.show();
  26618. setupEvents(editor, targetElm, ui, toolbarPersist);
  26619. editor.nodeChanged();
  26620. };
  26621. var delayedRender = function () {
  26622. return global$g.setEditorTimeout(editor, render, 0);
  26623. };
  26624. editor.on('show', render);
  26625. editor.on('hide', ui.hide);
  26626. if (!toolbarPersist) {
  26627. editor.on('focus', delayedRender);
  26628. editor.on('blur', ui.hide);
  26629. }
  26630. editor.on('init', function () {
  26631. if (editor.hasFocus() || toolbarPersist) {
  26632. delayedRender();
  26633. }
  26634. });
  26635. setupReadonlyModeSwitch(editor, uiComponents);
  26636. var api = {
  26637. show: function () {
  26638. ui.show();
  26639. },
  26640. hide: function () {
  26641. ui.hide();
  26642. },
  26643. enable: function () {
  26644. broadcastReadonly(uiComponents, false);
  26645. },
  26646. disable: function () {
  26647. broadcastReadonly(uiComponents, true);
  26648. },
  26649. isDisabled: function () {
  26650. return Disabling.isDisabled(outerContainer);
  26651. }
  26652. };
  26653. return {
  26654. editorContainer: outerContainer.element.dom,
  26655. api: api
  26656. };
  26657. };
  26658. var Inline = /*#__PURE__*/Object.freeze({
  26659. __proto__: null,
  26660. render: render
  26661. });
  26662. var showContextToolbarEvent = 'contexttoolbar-show';
  26663. var hideContextToolbarEvent = 'contexttoolbar-hide';
  26664. var getFormApi = function (input) {
  26665. return {
  26666. hide: function () {
  26667. return emit(input, sandboxClose());
  26668. },
  26669. getValue: function () {
  26670. return Representing.getValue(input);
  26671. }
  26672. };
  26673. };
  26674. var runOnExecute = function (memInput, original) {
  26675. return run$1(internalToolbarButtonExecute, function (comp, se) {
  26676. var input = memInput.get(comp);
  26677. var formApi = getFormApi(input);
  26678. original.onAction(formApi, se.event.buttonApi);
  26679. });
  26680. };
  26681. var renderContextButton = function (memInput, button, extras) {
  26682. var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  26683. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  26684. type: 'button',
  26685. onAction: noop
  26686. })));
  26687. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  26688. };
  26689. var renderContextToggleButton = function (memInput, button, extras) {
  26690. var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  26691. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  26692. type: 'togglebutton',
  26693. onAction: noop
  26694. })));
  26695. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  26696. };
  26697. var generateOne = function (memInput, button, providersBackstage) {
  26698. var extras = { backstage: { shared: { providers: providersBackstage } } };
  26699. if (button.type === 'contextformtogglebutton') {
  26700. return renderContextToggleButton(memInput, button, extras);
  26701. } else {
  26702. return renderContextButton(memInput, button, extras);
  26703. }
  26704. };
  26705. var generate = function (memInput, buttons, providersBackstage) {
  26706. var mementos = map$2(buttons, function (button) {
  26707. return record(generateOne(memInput, button, providersBackstage));
  26708. });
  26709. var asSpecs = function () {
  26710. return map$2(mementos, function (mem) {
  26711. return mem.asSpec();
  26712. });
  26713. };
  26714. var findPrimary = function (compInSystem) {
  26715. return findMap(buttons, function (button, i) {
  26716. if (button.primary) {
  26717. return Optional.from(mementos[i]).bind(function (mem) {
  26718. return mem.getOpt(compInSystem);
  26719. }).filter(not(Disabling.isDisabled));
  26720. } else {
  26721. return Optional.none();
  26722. }
  26723. });
  26724. };
  26725. return {
  26726. asSpecs: asSpecs,
  26727. findPrimary: findPrimary
  26728. };
  26729. };
  26730. var buildInitGroups = function (ctx, providers) {
  26731. var inputAttributes = ctx.label.fold(function () {
  26732. return {};
  26733. }, function (label) {
  26734. return { 'aria-label': label };
  26735. });
  26736. var memInput = record(Input.sketch({
  26737. inputClasses: [
  26738. 'tox-toolbar-textfield',
  26739. 'tox-toolbar-nav-js'
  26740. ],
  26741. data: ctx.initValue(),
  26742. inputAttributes: inputAttributes,
  26743. selectOnFocus: true,
  26744. inputBehaviours: derive$1([Keying.config({
  26745. mode: 'special',
  26746. onEnter: function (input) {
  26747. return commands.findPrimary(input).map(function (primary) {
  26748. emitExecute(primary);
  26749. return true;
  26750. });
  26751. },
  26752. onLeft: function (comp, se) {
  26753. se.cut();
  26754. return Optional.none();
  26755. },
  26756. onRight: function (comp, se) {
  26757. se.cut();
  26758. return Optional.none();
  26759. }
  26760. })])
  26761. }));
  26762. var commands = generate(memInput, ctx.commands, providers);
  26763. return [
  26764. {
  26765. title: Optional.none(),
  26766. items: [memInput.asSpec()]
  26767. },
  26768. {
  26769. title: Optional.none(),
  26770. items: commands.asSpecs()
  26771. }
  26772. ];
  26773. };
  26774. var renderContextForm = function (toolbarType, ctx, providers) {
  26775. return renderToolbar({
  26776. type: toolbarType,
  26777. uid: generate$6('context-toolbar'),
  26778. initGroups: buildInitGroups(ctx, providers),
  26779. onEscape: Optional.none,
  26780. cyclicKeying: true,
  26781. providers: providers
  26782. });
  26783. };
  26784. var ContextForm = {
  26785. renderContextForm: renderContextForm,
  26786. buildInitGroups: buildInitGroups
  26787. };
  26788. var isVerticalOverlap = function (a, b, threshold) {
  26789. if (threshold === void 0) {
  26790. threshold = 0.01;
  26791. }
  26792. return b.bottom - a.y >= threshold && a.bottom - b.y >= threshold;
  26793. };
  26794. var getRangeRect = function (rng) {
  26795. var rect = rng.getBoundingClientRect();
  26796. if (rect.height <= 0 && rect.width <= 0) {
  26797. var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
  26798. var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
  26799. return elm.filter(isElement$2).map(function (e) {
  26800. return e.dom.getBoundingClientRect();
  26801. }).getOr(rect);
  26802. } else {
  26803. return rect;
  26804. }
  26805. };
  26806. var getSelectionBounds = function (editor) {
  26807. var rng = editor.selection.getRng();
  26808. var rect = getRangeRect(rng);
  26809. if (editor.inline) {
  26810. var scroll_1 = get$6();
  26811. return bounds(scroll_1.left + rect.left, scroll_1.top + rect.top, rect.width, rect.height);
  26812. } else {
  26813. var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
  26814. return bounds(bodyPos.x + rect.left, bodyPos.y + rect.top, rect.width, rect.height);
  26815. }
  26816. };
  26817. var getAnchorElementBounds = function (editor, lastElement) {
  26818. return lastElement.filter(inBody).map(absolute$2).getOrThunk(function () {
  26819. return getSelectionBounds(editor);
  26820. });
  26821. };
  26822. var getHorizontalBounds = function (contentAreaBox, viewportBounds, margin) {
  26823. var x = Math.max(contentAreaBox.x + margin, viewportBounds.x);
  26824. var right = Math.min(contentAreaBox.right - margin, viewportBounds.right);
  26825. return {
  26826. x: x,
  26827. width: right - x
  26828. };
  26829. };
  26830. var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) {
  26831. var container = SugarElement.fromDom(editor.getContainer());
  26832. var header = descendant(container, '.tox-editor-header').getOr(container);
  26833. var headerBox = box$1(header);
  26834. var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  26835. var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  26836. if (editor.inline && isToolbarAbove) {
  26837. return {
  26838. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  26839. bottom: viewportBounds.bottom
  26840. };
  26841. }
  26842. if (editor.inline && !isToolbarAbove) {
  26843. return {
  26844. y: viewportBounds.y,
  26845. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  26846. };
  26847. }
  26848. var containerBounds = toolbarType === 'line' ? box$1(container) : contentAreaBox;
  26849. if (isToolbarAbove) {
  26850. return {
  26851. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  26852. bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
  26853. };
  26854. }
  26855. return {
  26856. y: Math.max(containerBounds.y + margin, viewportBounds.y),
  26857. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  26858. };
  26859. };
  26860. var getContextToolbarBounds = function (editor, sharedBackstage, toolbarType, margin) {
  26861. if (margin === void 0) {
  26862. margin = 0;
  26863. }
  26864. var viewportBounds = getBounds$3(window);
  26865. var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  26866. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  26867. var _a = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x = _a.x, width = _a.width;
  26868. if (editor.inline && !toolbarOrMenubarEnabled) {
  26869. return bounds(x, viewportBounds.y, width, viewportBounds.height);
  26870. } else {
  26871. var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  26872. var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y = _b.y, bottom = _b.bottom;
  26873. return bounds(x, y, width, bottom - y);
  26874. }
  26875. };
  26876. var bubbleSize$1 = 12;
  26877. var bubbleAlignments$1 = {
  26878. valignCentre: [],
  26879. alignCentre: [],
  26880. alignLeft: ['tox-pop--align-left'],
  26881. alignRight: ['tox-pop--align-right'],
  26882. right: ['tox-pop--right'],
  26883. left: ['tox-pop--left'],
  26884. bottom: ['tox-pop--bottom'],
  26885. top: ['tox-pop--top'],
  26886. inset: ['tox-pop--inset']
  26887. };
  26888. var anchorOverrides = {
  26889. maxHeightFunction: expandable$1(),
  26890. maxWidthFunction: expandable()
  26891. };
  26892. var isEntireElementSelected = function (editor, elem) {
  26893. var rng = editor.selection.getRng();
  26894. var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  26895. return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem);
  26896. };
  26897. var preservePosition = function (elem, position, f) {
  26898. var currentPosition = getRaw(elem, 'position');
  26899. set$6(elem, 'position', position);
  26900. var result = f(elem);
  26901. currentPosition.each(function (pos) {
  26902. return set$6(elem, 'position', pos);
  26903. });
  26904. return result;
  26905. };
  26906. var shouldUseInsetLayouts = function (position) {
  26907. return position === 'node';
  26908. };
  26909. var determineInsetLayout = function (editor, contextbar, elem, data, bounds) {
  26910. var selectionBounds = getSelectionBounds(editor);
  26911. var isSameAnchorElement = data.lastElement().exists(function (prev) {
  26912. return eq(elem, prev);
  26913. });
  26914. if (isEntireElementSelected(editor, elem)) {
  26915. return isSameAnchorElement ? preserve : north;
  26916. } else if (isSameAnchorElement) {
  26917. return preservePosition(contextbar, data.getMode(), function () {
  26918. var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
  26919. return isOverlapping && !data.isReposition() ? flip$2 : preserve;
  26920. });
  26921. } else {
  26922. var yBounds = data.getMode() === 'fixed' ? bounds.y + get$6().top : bounds.y;
  26923. var contextbarHeight = get$8(contextbar) + bubbleSize$1;
  26924. return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
  26925. }
  26926. };
  26927. var getAnchorSpec$2 = function (editor, mobile, data, position) {
  26928. var smartInsetLayout = function (elem) {
  26929. return function (anchor, element, bubbles, placee, bounds) {
  26930. var layout = determineInsetLayout(editor, placee, elem, data, bounds);
  26931. var newAnchor = __assign(__assign({}, anchor), {
  26932. y: bounds.y,
  26933. height: bounds.height
  26934. });
  26935. return __assign(__assign({}, layout(newAnchor, element, bubbles, placee, bounds)), { alwaysFit: true });
  26936. };
  26937. };
  26938. var getInsetLayouts = function (elem) {
  26939. return shouldUseInsetLayouts(position) ? [smartInsetLayout(elem)] : [];
  26940. };
  26941. var desktopAnchorSpecLayouts = {
  26942. onLtr: function (elem) {
  26943. return [
  26944. north$2,
  26945. south$2,
  26946. northeast$2,
  26947. southeast$2,
  26948. northwest$2,
  26949. southwest$2
  26950. ].concat(getInsetLayouts(elem));
  26951. },
  26952. onRtl: function (elem) {
  26953. return [
  26954. north$2,
  26955. south$2,
  26956. northwest$2,
  26957. southwest$2,
  26958. northeast$2,
  26959. southeast$2
  26960. ].concat(getInsetLayouts(elem));
  26961. }
  26962. };
  26963. var mobileAnchorSpecLayouts = {
  26964. onLtr: function (elem) {
  26965. return [
  26966. south$2,
  26967. southeast$2,
  26968. southwest$2,
  26969. northeast$2,
  26970. northwest$2,
  26971. north$2
  26972. ].concat(getInsetLayouts(elem));
  26973. },
  26974. onRtl: function (elem) {
  26975. return [
  26976. south$2,
  26977. southwest$2,
  26978. southeast$2,
  26979. northwest$2,
  26980. northeast$2,
  26981. north$2
  26982. ].concat(getInsetLayouts(elem));
  26983. }
  26984. };
  26985. return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
  26986. };
  26987. var getAnchorLayout = function (editor, position, isTouch, data) {
  26988. if (position === 'line') {
  26989. return {
  26990. bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
  26991. layouts: {
  26992. onLtr: function () {
  26993. return [east$2];
  26994. },
  26995. onRtl: function () {
  26996. return [west$2];
  26997. }
  26998. },
  26999. overrides: anchorOverrides
  27000. };
  27001. } else {
  27002. return {
  27003. bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
  27004. layouts: getAnchorSpec$2(editor, isTouch, data, position),
  27005. overrides: anchorOverrides
  27006. };
  27007. }
  27008. };
  27009. var matchTargetWith = function (elem, candidates) {
  27010. var ctxs = filter$2(candidates, function (toolbarApi) {
  27011. return toolbarApi.predicate(elem.dom);
  27012. });
  27013. var _a = partition$3(ctxs, function (t) {
  27014. return t.type === 'contexttoolbar';
  27015. }), pass = _a.pass, fail = _a.fail;
  27016. return {
  27017. contextToolbars: pass,
  27018. contextForms: fail
  27019. };
  27020. };
  27021. var filterByPositionForStartNode = function (toolbars) {
  27022. if (toolbars.length <= 1) {
  27023. return toolbars;
  27024. } else {
  27025. var doesPositionExist = function (value) {
  27026. return exists(toolbars, function (t) {
  27027. return t.position === value;
  27028. });
  27029. };
  27030. var filterToolbarsByPosition = function (value) {
  27031. return filter$2(toolbars, function (t) {
  27032. return t.position === value;
  27033. });
  27034. };
  27035. var hasSelectionToolbars = doesPositionExist('selection');
  27036. var hasNodeToolbars = doesPositionExist('node');
  27037. if (hasSelectionToolbars || hasNodeToolbars) {
  27038. if (hasNodeToolbars && hasSelectionToolbars) {
  27039. var nodeToolbars = filterToolbarsByPosition('node');
  27040. var selectionToolbars = map$2(filterToolbarsByPosition('selection'), function (t) {
  27041. return __assign(__assign({}, t), { position: 'node' });
  27042. });
  27043. return nodeToolbars.concat(selectionToolbars);
  27044. } else {
  27045. return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  27046. }
  27047. } else {
  27048. return filterToolbarsByPosition('line');
  27049. }
  27050. }
  27051. };
  27052. var filterByPositionForAncestorNode = function (toolbars) {
  27053. if (toolbars.length <= 1) {
  27054. return toolbars;
  27055. } else {
  27056. var findPosition_1 = function (value) {
  27057. return find$5(toolbars, function (t) {
  27058. return t.position === value;
  27059. });
  27060. };
  27061. var basePosition = findPosition_1('selection').orThunk(function () {
  27062. return findPosition_1('node');
  27063. }).orThunk(function () {
  27064. return findPosition_1('line');
  27065. }).map(function (t) {
  27066. return t.position;
  27067. });
  27068. return basePosition.fold(function () {
  27069. return [];
  27070. }, function (pos) {
  27071. return filter$2(toolbars, function (t) {
  27072. return t.position === pos;
  27073. });
  27074. });
  27075. }
  27076. };
  27077. var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
  27078. var nodeMatches = matchTargetWith(elem, nodeCandidates);
  27079. if (nodeMatches.contextForms.length > 0) {
  27080. return Optional.some({
  27081. elem: elem,
  27082. toolbars: [nodeMatches.contextForms[0]]
  27083. });
  27084. } else {
  27085. var editorMatches = matchTargetWith(elem, editorCandidates);
  27086. if (editorMatches.contextForms.length > 0) {
  27087. return Optional.some({
  27088. elem: elem,
  27089. toolbars: [editorMatches.contextForms[0]]
  27090. });
  27091. } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  27092. var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  27093. return Optional.some({
  27094. elem: elem,
  27095. toolbars: toolbars
  27096. });
  27097. } else {
  27098. return Optional.none();
  27099. }
  27100. }
  27101. };
  27102. var matchAncestor = function (isRoot, startNode, scopes) {
  27103. if (isRoot(startNode)) {
  27104. return Optional.none();
  27105. } else {
  27106. return ancestor$2(startNode, function (ancestorElem) {
  27107. if (isElement$2(ancestorElem)) {
  27108. var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
  27109. var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  27110. return toolbars.length > 0 ? Optional.some({
  27111. elem: ancestorElem,
  27112. toolbars: toolbars
  27113. }) : Optional.none();
  27114. } else {
  27115. return Optional.none();
  27116. }
  27117. }, isRoot);
  27118. }
  27119. };
  27120. var lookup$1 = function (scopes, editor) {
  27121. var rootElem = SugarElement.fromDom(editor.getBody());
  27122. var isRoot = function (elem) {
  27123. return eq(elem, rootElem);
  27124. };
  27125. var isOutsideRoot = function (startNode) {
  27126. return !isRoot(startNode) && !contains(rootElem, startNode);
  27127. };
  27128. var startNode = SugarElement.fromDom(editor.selection.getNode());
  27129. if (isOutsideRoot(startNode)) {
  27130. return Optional.none();
  27131. }
  27132. return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
  27133. return matchAncestor(isRoot, startNode, scopes);
  27134. });
  27135. };
  27136. var categorise = function (contextToolbars, navigate) {
  27137. var forms = {};
  27138. var inNodeScope = [];
  27139. var inEditorScope = [];
  27140. var formNavigators = {};
  27141. var lookupTable = {};
  27142. var registerForm = function (key, toolbarSpec) {
  27143. var contextForm = getOrDie(createContextForm(toolbarSpec));
  27144. forms[key] = contextForm;
  27145. contextForm.launch.map(function (launch) {
  27146. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), {
  27147. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  27148. onAction: function () {
  27149. navigate(contextForm);
  27150. }
  27151. });
  27152. });
  27153. if (contextForm.scope === 'editor') {
  27154. inEditorScope.push(contextForm);
  27155. } else {
  27156. inNodeScope.push(contextForm);
  27157. }
  27158. lookupTable[key] = contextForm;
  27159. };
  27160. var registerToolbar = function (key, toolbarSpec) {
  27161. createContextToolbar(toolbarSpec).each(function (contextToolbar) {
  27162. if (toolbarSpec.scope === 'editor') {
  27163. inEditorScope.push(contextToolbar);
  27164. } else {
  27165. inNodeScope.push(contextToolbar);
  27166. }
  27167. lookupTable[key] = contextToolbar;
  27168. });
  27169. };
  27170. var keys$1 = keys(contextToolbars);
  27171. each$1(keys$1, function (key) {
  27172. var toolbarApi = contextToolbars[key];
  27173. if (toolbarApi.type === 'contextform') {
  27174. registerForm(key, toolbarApi);
  27175. } else if (toolbarApi.type === 'contexttoolbar') {
  27176. registerToolbar(key, toolbarApi);
  27177. }
  27178. });
  27179. return {
  27180. forms: forms,
  27181. inNodeScope: inNodeScope,
  27182. inEditorScope: inEditorScope,
  27183. lookupTable: lookupTable,
  27184. formNavigators: formNavigators
  27185. };
  27186. };
  27187. var forwardSlideEvent = generate$6('forward-slide');
  27188. var backSlideEvent = generate$6('backward-slide');
  27189. var changeSlideEvent = generate$6('change-slide-event');
  27190. var resizingClass = 'tox-pop--resizing';
  27191. var renderContextToolbar = function (spec) {
  27192. var stack = Cell([]);
  27193. return InlineView.sketch({
  27194. dom: {
  27195. tag: 'div',
  27196. classes: ['tox-pop']
  27197. },
  27198. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  27199. onShow: function (comp) {
  27200. stack.set([]);
  27201. InlineView.getContent(comp).each(function (c) {
  27202. remove$1(c.element, 'visibility');
  27203. });
  27204. remove$3(comp.element, resizingClass);
  27205. remove$1(comp.element, 'width');
  27206. },
  27207. inlineBehaviours: derive$1([
  27208. config('context-toolbar-events', [
  27209. runOnSource(transitionend(), function (comp, se) {
  27210. if (se.event.raw.propertyName === 'width') {
  27211. remove$3(comp.element, resizingClass);
  27212. remove$1(comp.element, 'width');
  27213. }
  27214. }),
  27215. run$1(changeSlideEvent, function (comp, se) {
  27216. var elem = comp.element;
  27217. remove$1(elem, 'width');
  27218. var currentWidth = get$7(elem);
  27219. InlineView.setContent(comp, se.event.contents);
  27220. add$2(elem, resizingClass);
  27221. var newWidth = get$7(elem);
  27222. set$6(elem, 'width', currentWidth + 'px');
  27223. InlineView.getContent(comp).each(function (newContents) {
  27224. se.event.focus.bind(function (f) {
  27225. focus$3(f);
  27226. return search(elem);
  27227. }).orThunk(function () {
  27228. Keying.focusIn(newContents);
  27229. return active(getRootNode(elem));
  27230. });
  27231. });
  27232. global$g.setTimeout(function () {
  27233. set$6(comp.element, 'width', newWidth + 'px');
  27234. }, 0);
  27235. }),
  27236. run$1(forwardSlideEvent, function (comp, se) {
  27237. InlineView.getContent(comp).each(function (oldContents) {
  27238. stack.set(stack.get().concat([{
  27239. bar: oldContents,
  27240. focus: active(getRootNode(comp.element))
  27241. }]));
  27242. });
  27243. emitWith(comp, changeSlideEvent, {
  27244. contents: se.event.forwardContents,
  27245. focus: Optional.none()
  27246. });
  27247. }),
  27248. run$1(backSlideEvent, function (comp, _se) {
  27249. last$2(stack.get()).each(function (last) {
  27250. stack.set(stack.get().slice(0, stack.get().length - 1));
  27251. emitWith(comp, changeSlideEvent, {
  27252. contents: premade(last.bar),
  27253. focus: last.focus
  27254. });
  27255. });
  27256. })
  27257. ]),
  27258. Keying.config({
  27259. mode: 'special',
  27260. onEscape: function (comp) {
  27261. return last$2(stack.get()).fold(function () {
  27262. return spec.onEscape();
  27263. }, function (_) {
  27264. emit(comp, backSlideEvent);
  27265. return Optional.some(true);
  27266. });
  27267. }
  27268. })
  27269. ]),
  27270. lazySink: function () {
  27271. return Result.value(spec.sink);
  27272. }
  27273. });
  27274. };
  27275. var transitionClass = 'tox-pop--transition';
  27276. var register$7 = function (editor, registryContextToolbars, sink, extras) {
  27277. var backstage = extras.backstage;
  27278. var sharedBackstage = backstage.shared;
  27279. var isTouch = detect$1().deviceType.isTouch;
  27280. var lastElement = value$1();
  27281. var lastTrigger = value$1();
  27282. var lastContextPosition = value$1();
  27283. var contextbar = build$1(renderContextToolbar({
  27284. sink: sink,
  27285. onEscape: function () {
  27286. editor.focus();
  27287. return Optional.some(true);
  27288. }
  27289. }));
  27290. var getBounds = function () {
  27291. var position = lastContextPosition.get().getOr('node');
  27292. var margin = shouldUseInsetLayouts(position) ? 1 : 0;
  27293. return getContextToolbarBounds(editor, sharedBackstage, position, margin);
  27294. };
  27295. var canLaunchToolbar = function () {
  27296. return !editor.removed && !(isTouch() && backstage.isContextMenuOpen());
  27297. };
  27298. var isSameLaunchElement = function (elem) {
  27299. return is(lift2(elem, lastElement.get(), eq), true);
  27300. };
  27301. var shouldContextToolbarHide = function () {
  27302. if (!canLaunchToolbar()) {
  27303. return true;
  27304. } else {
  27305. var contextToolbarBounds = getBounds();
  27306. var anchorBounds = is(lastContextPosition.get(), 'node') ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
  27307. return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
  27308. }
  27309. };
  27310. var close = function () {
  27311. lastElement.clear();
  27312. lastTrigger.clear();
  27313. lastContextPosition.clear();
  27314. InlineView.hide(contextbar);
  27315. };
  27316. var hideOrRepositionIfNecessary = function () {
  27317. if (InlineView.isOpen(contextbar)) {
  27318. var contextBarEle = contextbar.element;
  27319. remove$1(contextBarEle, 'display');
  27320. if (shouldContextToolbarHide()) {
  27321. set$6(contextBarEle, 'display', 'none');
  27322. } else {
  27323. lastTrigger.set(0);
  27324. InlineView.reposition(contextbar);
  27325. }
  27326. }
  27327. };
  27328. var wrapInPopDialog = function (toolbarSpec) {
  27329. return {
  27330. dom: {
  27331. tag: 'div',
  27332. classes: ['tox-pop__dialog']
  27333. },
  27334. components: [toolbarSpec],
  27335. behaviours: derive$1([
  27336. Keying.config({ mode: 'acyclic' }),
  27337. config('pop-dialog-wrap-events', [
  27338. runOnAttached(function (comp) {
  27339. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  27340. return Keying.focusIn(comp);
  27341. });
  27342. }),
  27343. runOnDetached(function (_comp) {
  27344. editor.shortcuts.remove('ctrl+F9');
  27345. })
  27346. ])
  27347. ])
  27348. };
  27349. };
  27350. var getScopes = cached(function () {
  27351. return categorise(registryContextToolbars, function (toolbarApi) {
  27352. var alloySpec = buildToolbar([toolbarApi]);
  27353. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  27354. });
  27355. });
  27356. var buildContextToolbarGroups = function (allButtons, ctx) {
  27357. return identifyButtons(editor, {
  27358. buttons: allButtons,
  27359. toolbar: ctx.items,
  27360. allowToolbarGroups: false
  27361. }, extras, Optional.some(['form:']));
  27362. };
  27363. var buildContextFormGroups = function (ctx, providers) {
  27364. return ContextForm.buildInitGroups(ctx, providers);
  27365. };
  27366. var buildToolbar = function (toolbars) {
  27367. var buttons = editor.ui.registry.getAll().buttons;
  27368. var scopes = getScopes();
  27369. var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  27370. var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  27371. var initGroups = flatten(map$2(toolbars, function (ctx) {
  27372. return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers);
  27373. }));
  27374. return renderToolbar({
  27375. type: toolbarType,
  27376. uid: generate$6('context-toolbar'),
  27377. initGroups: initGroups,
  27378. onEscape: Optional.none,
  27379. cyclicKeying: true,
  27380. providers: sharedBackstage.providers
  27381. });
  27382. };
  27383. var getAnchor = function (position, element) {
  27384. var anchorage = position === 'node' ? sharedBackstage.anchors.node(element) : sharedBackstage.anchors.cursor();
  27385. var anchorLayout = getAnchorLayout(editor, position, isTouch(), {
  27386. lastElement: lastElement.get,
  27387. isReposition: function () {
  27388. return is(lastTrigger.get(), 0);
  27389. },
  27390. getMode: function () {
  27391. return Positioning.getMode(sink);
  27392. }
  27393. });
  27394. return deepMerge(anchorage, anchorLayout);
  27395. };
  27396. var launchContext = function (toolbarApi, elem) {
  27397. launchContextToolbar.cancel();
  27398. if (!canLaunchToolbar()) {
  27399. return;
  27400. }
  27401. var toolbarSpec = buildToolbar(toolbarApi);
  27402. var position = toolbarApi[0].position;
  27403. var anchor = getAnchor(position, elem);
  27404. lastContextPosition.set(position);
  27405. lastTrigger.set(1);
  27406. var contextBarEle = contextbar.element;
  27407. remove$1(contextBarEle, 'display');
  27408. if (!isSameLaunchElement(elem)) {
  27409. remove$3(contextBarEle, transitionClass);
  27410. Positioning.reset(sink, contextbar);
  27411. }
  27412. InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
  27413. anchor: anchor,
  27414. transition: {
  27415. classes: [transitionClass],
  27416. mode: 'placement'
  27417. }
  27418. }, function () {
  27419. return Optional.some(getBounds());
  27420. });
  27421. elem.fold(lastElement.clear, lastElement.set);
  27422. if (shouldContextToolbarHide()) {
  27423. set$6(contextBarEle, 'display', 'none');
  27424. }
  27425. };
  27426. var launchContextToolbar = last(function () {
  27427. if (!editor.hasFocus() || editor.removed) {
  27428. return;
  27429. }
  27430. if (has(contextbar.element, transitionClass)) {
  27431. launchContextToolbar.throttle();
  27432. } else {
  27433. var scopes = getScopes();
  27434. lookup$1(scopes, editor).fold(close, function (info) {
  27435. launchContext(info.toolbars, Optional.some(info.elem));
  27436. });
  27437. }
  27438. }, 17);
  27439. editor.on('init', function () {
  27440. editor.on('remove', close);
  27441. editor.on('ScrollContent ScrollWindow ObjectResized ResizeEditor longpress', hideOrRepositionIfNecessary);
  27442. editor.on('click keyup focus SetContent', launchContextToolbar.throttle);
  27443. editor.on(hideContextToolbarEvent, close);
  27444. editor.on(showContextToolbarEvent, function (e) {
  27445. var scopes = getScopes();
  27446. get$e(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  27447. launchContext([ctx], someIf(e.target !== editor, e.target));
  27448. InlineView.getContent(contextbar).each(Keying.focusIn);
  27449. });
  27450. });
  27451. editor.on('focusout', function (_e) {
  27452. global$g.setEditorTimeout(editor, function () {
  27453. if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
  27454. close();
  27455. }
  27456. }, 0);
  27457. });
  27458. editor.on('SwitchMode', function () {
  27459. if (editor.mode.isReadOnly()) {
  27460. close();
  27461. }
  27462. });
  27463. editor.on('AfterProgressState', function (event) {
  27464. if (event.state) {
  27465. close();
  27466. } else if (editor.hasFocus()) {
  27467. launchContextToolbar.throttle();
  27468. }
  27469. });
  27470. editor.on('NodeChange', function (_e) {
  27471. search(contextbar.element).fold(launchContextToolbar.throttle, noop);
  27472. });
  27473. });
  27474. };
  27475. var register$6 = function (editor) {
  27476. var alignToolbarButtons = [
  27477. {
  27478. name: 'alignleft',
  27479. text: 'Align left',
  27480. cmd: 'JustifyLeft',
  27481. icon: 'align-left'
  27482. },
  27483. {
  27484. name: 'aligncenter',
  27485. text: 'Align center',
  27486. cmd: 'JustifyCenter',
  27487. icon: 'align-center'
  27488. },
  27489. {
  27490. name: 'alignright',
  27491. text: 'Align right',
  27492. cmd: 'JustifyRight',
  27493. icon: 'align-right'
  27494. },
  27495. {
  27496. name: 'alignjustify',
  27497. text: 'Justify',
  27498. cmd: 'JustifyFull',
  27499. icon: 'align-justify'
  27500. }
  27501. ];
  27502. each$1(alignToolbarButtons, function (item) {
  27503. editor.ui.registry.addToggleButton(item.name, {
  27504. tooltip: item.text,
  27505. icon: item.icon,
  27506. onAction: onActionExecCommand(editor, item.cmd),
  27507. onSetup: onSetupFormatToggle(editor, item.name)
  27508. });
  27509. });
  27510. editor.ui.registry.addButton('alignnone', {
  27511. tooltip: 'No alignment',
  27512. icon: 'align-none',
  27513. onAction: onActionExecCommand(editor, 'JustifyNone')
  27514. });
  27515. };
  27516. var units = {
  27517. unsupportedLength: [
  27518. 'em',
  27519. 'ex',
  27520. 'cap',
  27521. 'ch',
  27522. 'ic',
  27523. 'rem',
  27524. 'lh',
  27525. 'rlh',
  27526. 'vw',
  27527. 'vh',
  27528. 'vi',
  27529. 'vb',
  27530. 'vmin',
  27531. 'vmax',
  27532. 'cm',
  27533. 'mm',
  27534. 'Q',
  27535. 'in',
  27536. 'pc',
  27537. 'pt',
  27538. 'px'
  27539. ],
  27540. fixed: [
  27541. 'px',
  27542. 'pt'
  27543. ],
  27544. relative: ['%'],
  27545. empty: ['']
  27546. };
  27547. var pattern = function () {
  27548. var decimalDigits = '[0-9]+';
  27549. var signedInteger = '[+-]?' + decimalDigits;
  27550. var exponentPart = '[eE]' + signedInteger;
  27551. var dot = '\\.';
  27552. var opt = function (input) {
  27553. return '(?:' + input + ')?';
  27554. };
  27555. var unsignedDecimalLiteral = [
  27556. 'Infinity',
  27557. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  27558. dot + decimalDigits + opt(exponentPart),
  27559. decimalDigits + opt(exponentPart)
  27560. ].join('|');
  27561. var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  27562. return new RegExp('^(' + float + ')(.*)$');
  27563. }();
  27564. var isUnit = function (unit, accepted) {
  27565. return exists(accepted, function (acc) {
  27566. return exists(units[acc], function (check) {
  27567. return unit === check;
  27568. });
  27569. });
  27570. };
  27571. var parse = function (input, accepted) {
  27572. var match = Optional.from(pattern.exec(input));
  27573. return match.bind(function (array) {
  27574. var value = Number(array[1]);
  27575. var unitRaw = array[2];
  27576. if (isUnit(unitRaw, accepted)) {
  27577. return Optional.some({
  27578. value: value,
  27579. unit: unitRaw
  27580. });
  27581. } else {
  27582. return Optional.none();
  27583. }
  27584. });
  27585. };
  27586. var normalise = function (input, accepted) {
  27587. return parse(input, accepted).map(function (_a) {
  27588. var value = _a.value, unit = _a.unit;
  27589. return value + unit;
  27590. });
  27591. };
  27592. var registerController = function (editor, spec) {
  27593. var getMenuItems = function () {
  27594. var options = spec.getOptions(editor);
  27595. var initial = spec.getCurrent(editor).map(spec.hash);
  27596. var current = value$1();
  27597. return map$2(options, function (value) {
  27598. return {
  27599. type: 'togglemenuitem',
  27600. text: spec.display(value),
  27601. onSetup: function (api) {
  27602. var setActive = function (active) {
  27603. if (active) {
  27604. current.on(function (oldApi) {
  27605. return oldApi.setActive(false);
  27606. });
  27607. current.set(api);
  27608. }
  27609. api.setActive(active);
  27610. };
  27611. setActive(is(initial, spec.hash(value)));
  27612. var unbindWatcher = spec.watcher(editor, value, setActive);
  27613. return function () {
  27614. current.clear();
  27615. unbindWatcher();
  27616. };
  27617. },
  27618. onAction: function () {
  27619. return spec.setCurrent(editor, value);
  27620. }
  27621. };
  27622. });
  27623. };
  27624. editor.ui.registry.addMenuButton(spec.name, {
  27625. tooltip: spec.text,
  27626. icon: spec.icon,
  27627. fetch: function (callback) {
  27628. return callback(getMenuItems());
  27629. },
  27630. onSetup: spec.onToolbarSetup
  27631. });
  27632. editor.ui.registry.addNestedMenuItem(spec.name, {
  27633. type: 'nestedmenuitem',
  27634. text: spec.text,
  27635. getSubmenuItems: getMenuItems,
  27636. onSetup: spec.onMenuSetup
  27637. });
  27638. };
  27639. var lineHeightSpec = {
  27640. name: 'lineheight',
  27641. text: 'Line height',
  27642. icon: 'line-height',
  27643. getOptions: getLineHeightFormats,
  27644. hash: function (input) {
  27645. return normalise(input, [
  27646. 'fixed',
  27647. 'relative',
  27648. 'empty'
  27649. ]).getOr(input);
  27650. },
  27651. display: identity$1,
  27652. watcher: function (editor, value, callback) {
  27653. return editor.formatter.formatChanged('lineheight', callback, false, { value: value }).unbind;
  27654. },
  27655. getCurrent: function (editor) {
  27656. return Optional.from(editor.queryCommandValue('LineHeight'));
  27657. },
  27658. setCurrent: function (editor, value) {
  27659. return editor.execCommand('LineHeight', false, value);
  27660. }
  27661. };
  27662. var languageSpec = function (editor) {
  27663. var settingsOpt = Optional.from(getContentLanguages(editor));
  27664. return settingsOpt.map(function (settings) {
  27665. return {
  27666. name: 'language',
  27667. text: 'Language',
  27668. icon: 'language',
  27669. getOptions: constant$1(settings),
  27670. hash: function (input) {
  27671. return isUndefined(input.customCode) ? input.code : input.code + '/' + input.customCode;
  27672. },
  27673. display: function (input) {
  27674. return input.title;
  27675. },
  27676. watcher: function (editor, value, callback) {
  27677. return editor.formatter.formatChanged('lang', callback, false, {
  27678. value: value.code,
  27679. customValue: value.customCode
  27680. }).unbind;
  27681. },
  27682. getCurrent: function (editor) {
  27683. var node = SugarElement.fromDom(editor.selection.getNode());
  27684. return closest$4(node, function (n) {
  27685. return Optional.some(n).filter(isElement$2).bind(function (ele) {
  27686. var codeOpt = getOpt(ele, 'lang');
  27687. return codeOpt.map(function (code) {
  27688. var customCode = getOpt(ele, 'data-mce-lang').getOrUndefined();
  27689. return {
  27690. code: code,
  27691. customCode: customCode,
  27692. title: ''
  27693. };
  27694. });
  27695. });
  27696. });
  27697. },
  27698. setCurrent: function (editor, lang) {
  27699. return editor.execCommand('Lang', false, lang);
  27700. },
  27701. onToolbarSetup: function (api) {
  27702. var unbinder = unbindable();
  27703. api.setActive(editor.formatter.match('lang', {}, undefined, true));
  27704. unbinder.set(editor.formatter.formatChanged('lang', api.setActive, true));
  27705. return unbinder.clear;
  27706. }
  27707. };
  27708. });
  27709. };
  27710. var register$5 = function (editor) {
  27711. registerController(editor, lineHeightSpec);
  27712. languageSpec(editor).each(function (spec) {
  27713. return registerController(editor, spec);
  27714. });
  27715. };
  27716. var register$4 = function (editor, backstage) {
  27717. alignSelectMenu(editor, backstage);
  27718. fontSelectMenu(editor, backstage);
  27719. styleSelectMenu(editor, backstage);
  27720. formatSelectMenu(editor, backstage);
  27721. fontsizeSelectMenu(editor, backstage);
  27722. };
  27723. var onSetupOutdentState = function (editor) {
  27724. return onSetupEvent(editor, 'NodeChange', function (api) {
  27725. api.setDisabled(!editor.queryCommandState('outdent'));
  27726. });
  27727. };
  27728. var registerButtons$2 = function (editor) {
  27729. editor.ui.registry.addButton('outdent', {
  27730. tooltip: 'Decrease indent',
  27731. icon: 'outdent',
  27732. onSetup: onSetupOutdentState(editor),
  27733. onAction: onActionExecCommand(editor, 'outdent')
  27734. });
  27735. editor.ui.registry.addButton('indent', {
  27736. tooltip: 'Increase indent',
  27737. icon: 'indent',
  27738. onAction: onActionExecCommand(editor, 'indent')
  27739. });
  27740. };
  27741. var register$3 = function (editor) {
  27742. registerButtons$2(editor);
  27743. };
  27744. var onActionToggleFormat = function (editor, fmt) {
  27745. return function () {
  27746. editor.execCommand('mceToggleFormat', false, fmt);
  27747. };
  27748. };
  27749. var registerFormatButtons = function (editor) {
  27750. global$6.each([
  27751. {
  27752. name: 'bold',
  27753. text: 'Bold',
  27754. icon: 'bold'
  27755. },
  27756. {
  27757. name: 'italic',
  27758. text: 'Italic',
  27759. icon: 'italic'
  27760. },
  27761. {
  27762. name: 'underline',
  27763. text: 'Underline',
  27764. icon: 'underline'
  27765. },
  27766. {
  27767. name: 'strikethrough',
  27768. text: 'Strikethrough',
  27769. icon: 'strike-through'
  27770. },
  27771. {
  27772. name: 'subscript',
  27773. text: 'Subscript',
  27774. icon: 'subscript'
  27775. },
  27776. {
  27777. name: 'superscript',
  27778. text: 'Superscript',
  27779. icon: 'superscript'
  27780. }
  27781. ], function (btn, _idx) {
  27782. editor.ui.registry.addToggleButton(btn.name, {
  27783. tooltip: btn.text,
  27784. icon: btn.icon,
  27785. onSetup: onSetupFormatToggle(editor, btn.name),
  27786. onAction: onActionToggleFormat(editor, btn.name)
  27787. });
  27788. });
  27789. for (var i = 1; i <= 6; i++) {
  27790. var name_1 = 'h' + i;
  27791. editor.ui.registry.addToggleButton(name_1, {
  27792. text: name_1.toUpperCase(),
  27793. tooltip: 'Heading ' + i,
  27794. onSetup: onSetupFormatToggle(editor, name_1),
  27795. onAction: onActionToggleFormat(editor, name_1)
  27796. });
  27797. }
  27798. };
  27799. var registerCommandButtons = function (editor) {
  27800. global$6.each([
  27801. {
  27802. name: 'cut',
  27803. text: 'Cut',
  27804. action: 'Cut',
  27805. icon: 'cut'
  27806. },
  27807. {
  27808. name: 'copy',
  27809. text: 'Copy',
  27810. action: 'Copy',
  27811. icon: 'copy'
  27812. },
  27813. {
  27814. name: 'paste',
  27815. text: 'Paste',
  27816. action: 'Paste',
  27817. icon: 'paste'
  27818. },
  27819. {
  27820. name: 'help',
  27821. text: 'Help',
  27822. action: 'mceHelp',
  27823. icon: 'help'
  27824. },
  27825. {
  27826. name: 'selectall',
  27827. text: 'Select all',
  27828. action: 'SelectAll',
  27829. icon: 'select-all'
  27830. },
  27831. {
  27832. name: 'newdocument',
  27833. text: 'New document',
  27834. action: 'mceNewDocument',
  27835. icon: 'new-document'
  27836. },
  27837. {
  27838. name: 'removeformat',
  27839. text: 'Clear formatting',
  27840. action: 'RemoveFormat',
  27841. icon: 'remove-formatting'
  27842. },
  27843. {
  27844. name: 'remove',
  27845. text: 'Remove',
  27846. action: 'Delete',
  27847. icon: 'remove'
  27848. }
  27849. ], function (btn) {
  27850. editor.ui.registry.addButton(btn.name, {
  27851. tooltip: btn.text,
  27852. icon: btn.icon,
  27853. onAction: onActionExecCommand(editor, btn.action)
  27854. });
  27855. });
  27856. };
  27857. var registerCommandToggleButtons = function (editor) {
  27858. global$6.each([{
  27859. name: 'blockquote',
  27860. text: 'Blockquote',
  27861. action: 'mceBlockQuote',
  27862. icon: 'quote'
  27863. }], function (btn) {
  27864. editor.ui.registry.addToggleButton(btn.name, {
  27865. tooltip: btn.text,
  27866. icon: btn.icon,
  27867. onAction: onActionExecCommand(editor, btn.action),
  27868. onSetup: onSetupFormatToggle(editor, btn.name)
  27869. });
  27870. });
  27871. };
  27872. var registerButtons$1 = function (editor) {
  27873. registerFormatButtons(editor);
  27874. registerCommandButtons(editor);
  27875. registerCommandToggleButtons(editor);
  27876. };
  27877. var registerMenuItems$2 = function (editor) {
  27878. global$6.each([
  27879. {
  27880. name: 'bold',
  27881. text: 'Bold',
  27882. action: 'Bold',
  27883. icon: 'bold',
  27884. shortcut: 'Meta+B'
  27885. },
  27886. {
  27887. name: 'italic',
  27888. text: 'Italic',
  27889. action: 'Italic',
  27890. icon: 'italic',
  27891. shortcut: 'Meta+I'
  27892. },
  27893. {
  27894. name: 'underline',
  27895. text: 'Underline',
  27896. action: 'Underline',
  27897. icon: 'underline',
  27898. shortcut: 'Meta+U'
  27899. },
  27900. {
  27901. name: 'strikethrough',
  27902. text: 'Strikethrough',
  27903. action: 'Strikethrough',
  27904. icon: 'strike-through',
  27905. shortcut: ''
  27906. },
  27907. {
  27908. name: 'subscript',
  27909. text: 'Subscript',
  27910. action: 'Subscript',
  27911. icon: 'subscript',
  27912. shortcut: ''
  27913. },
  27914. {
  27915. name: 'superscript',
  27916. text: 'Superscript',
  27917. action: 'Superscript',
  27918. icon: 'superscript',
  27919. shortcut: ''
  27920. },
  27921. {
  27922. name: 'removeformat',
  27923. text: 'Clear formatting',
  27924. action: 'RemoveFormat',
  27925. icon: 'remove-formatting',
  27926. shortcut: ''
  27927. },
  27928. {
  27929. name: 'newdocument',
  27930. text: 'New document',
  27931. action: 'mceNewDocument',
  27932. icon: 'new-document',
  27933. shortcut: ''
  27934. },
  27935. {
  27936. name: 'cut',
  27937. text: 'Cut',
  27938. action: 'Cut',
  27939. icon: 'cut',
  27940. shortcut: 'Meta+X'
  27941. },
  27942. {
  27943. name: 'copy',
  27944. text: 'Copy',
  27945. action: 'Copy',
  27946. icon: 'copy',
  27947. shortcut: 'Meta+C'
  27948. },
  27949. {
  27950. name: 'paste',
  27951. text: 'Paste',
  27952. action: 'Paste',
  27953. icon: 'paste',
  27954. shortcut: 'Meta+V'
  27955. },
  27956. {
  27957. name: 'selectall',
  27958. text: 'Select all',
  27959. action: 'SelectAll',
  27960. icon: 'select-all',
  27961. shortcut: 'Meta+A'
  27962. }
  27963. ], function (btn) {
  27964. editor.ui.registry.addMenuItem(btn.name, {
  27965. text: btn.text,
  27966. icon: btn.icon,
  27967. shortcut: btn.shortcut,
  27968. onAction: onActionExecCommand(editor, btn.action)
  27969. });
  27970. });
  27971. editor.ui.registry.addMenuItem('codeformat', {
  27972. text: 'Code',
  27973. icon: 'sourcecode',
  27974. onAction: onActionToggleFormat(editor, 'code')
  27975. });
  27976. };
  27977. var register$2 = function (editor) {
  27978. registerButtons$1(editor);
  27979. registerMenuItems$2(editor);
  27980. };
  27981. var onSetupUndoRedoState = function (editor, type) {
  27982. return onSetupEvent(editor, 'Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function (api) {
  27983. api.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type]());
  27984. });
  27985. };
  27986. var registerMenuItems$1 = function (editor) {
  27987. editor.ui.registry.addMenuItem('undo', {
  27988. text: 'Undo',
  27989. icon: 'undo',
  27990. shortcut: 'Meta+Z',
  27991. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  27992. onAction: onActionExecCommand(editor, 'undo')
  27993. });
  27994. editor.ui.registry.addMenuItem('redo', {
  27995. text: 'Redo',
  27996. icon: 'redo',
  27997. shortcut: 'Meta+Y',
  27998. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  27999. onAction: onActionExecCommand(editor, 'redo')
  28000. });
  28001. };
  28002. var registerButtons = function (editor) {
  28003. editor.ui.registry.addButton('undo', {
  28004. tooltip: 'Undo',
  28005. icon: 'undo',
  28006. disabled: true,
  28007. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  28008. onAction: onActionExecCommand(editor, 'undo')
  28009. });
  28010. editor.ui.registry.addButton('redo', {
  28011. tooltip: 'Redo',
  28012. icon: 'redo',
  28013. disabled: true,
  28014. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  28015. onAction: onActionExecCommand(editor, 'redo')
  28016. });
  28017. };
  28018. var register$1 = function (editor) {
  28019. registerMenuItems$1(editor);
  28020. registerButtons(editor);
  28021. };
  28022. var onSetupVisualAidState = function (editor) {
  28023. return onSetupEvent(editor, 'VisualAid', function (api) {
  28024. api.setActive(editor.hasVisual);
  28025. });
  28026. };
  28027. var registerMenuItems = function (editor) {
  28028. editor.ui.registry.addToggleMenuItem('visualaid', {
  28029. text: 'Visual aids',
  28030. onSetup: onSetupVisualAidState(editor),
  28031. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  28032. });
  28033. };
  28034. var registerToolbarButton = function (editor) {
  28035. editor.ui.registry.addButton('visualaid', {
  28036. tooltip: 'Visual aids',
  28037. text: 'Visual aids',
  28038. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  28039. });
  28040. };
  28041. var register = function (editor) {
  28042. registerToolbarButton(editor);
  28043. registerMenuItems(editor);
  28044. };
  28045. var setup$6 = function (editor, backstage) {
  28046. register$6(editor);
  28047. register$2(editor);
  28048. register$4(editor, backstage);
  28049. register$1(editor);
  28050. register$a(editor);
  28051. register(editor);
  28052. register$3(editor);
  28053. register$5(editor);
  28054. };
  28055. var nu = function (x, y) {
  28056. return {
  28057. type: 'makeshift',
  28058. x: x,
  28059. y: y
  28060. };
  28061. };
  28062. var transpose = function (pos, dx, dy) {
  28063. return nu(pos.x + dx, pos.y + dy);
  28064. };
  28065. var isTouchEvent = function (e) {
  28066. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  28067. };
  28068. var fromPageXY = function (e) {
  28069. if (isTouchEvent(e)) {
  28070. var touch = e.touches[0];
  28071. return nu(touch.pageX, touch.pageY);
  28072. } else {
  28073. return nu(e.pageX, e.pageY);
  28074. }
  28075. };
  28076. var fromClientXY = function (e) {
  28077. if (isTouchEvent(e)) {
  28078. var touch = e.touches[0];
  28079. return nu(touch.clientX, touch.clientY);
  28080. } else {
  28081. return nu(e.clientX, e.clientY);
  28082. }
  28083. };
  28084. var transposeContentAreaContainer = function (element, pos) {
  28085. var containerPos = global$c.DOM.getPos(element);
  28086. return transpose(pos, containerPos.x, containerPos.y);
  28087. };
  28088. var getPointAnchor = function (editor, e) {
  28089. if (e.type === 'contextmenu' || e.type === 'longpress') {
  28090. if (editor.inline) {
  28091. return fromPageXY(e);
  28092. } else {
  28093. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  28094. }
  28095. } else {
  28096. return getSelectionAnchor(editor);
  28097. }
  28098. };
  28099. var getSelectionAnchor = function (editor) {
  28100. return {
  28101. type: 'selection',
  28102. root: SugarElement.fromDom(editor.selection.getNode())
  28103. };
  28104. };
  28105. var getNodeAnchor = function (editor) {
  28106. return {
  28107. type: 'node',
  28108. node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
  28109. root: SugarElement.fromDom(editor.getBody())
  28110. };
  28111. };
  28112. var getAnchorSpec$1 = function (editor, e, anchorType) {
  28113. switch (anchorType) {
  28114. case 'node':
  28115. return getNodeAnchor(editor);
  28116. case 'point':
  28117. return getPointAnchor(editor, e);
  28118. case 'selection':
  28119. return getSelectionAnchor(editor);
  28120. }
  28121. };
  28122. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  28123. var items = buildMenu();
  28124. var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  28125. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  28126. e.preventDefault();
  28127. InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
  28128. menu: { markers: markers('normal') },
  28129. data: menuData
  28130. });
  28131. });
  28132. };
  28133. var layouts = {
  28134. onLtr: function () {
  28135. return [
  28136. south$2,
  28137. southeast$2,
  28138. southwest$2,
  28139. northeast$2,
  28140. northwest$2,
  28141. north$2,
  28142. north,
  28143. south,
  28144. northeast,
  28145. southeast,
  28146. northwest,
  28147. southwest
  28148. ];
  28149. },
  28150. onRtl: function () {
  28151. return [
  28152. south$2,
  28153. southwest$2,
  28154. southeast$2,
  28155. northwest$2,
  28156. northeast$2,
  28157. north$2,
  28158. north,
  28159. south,
  28160. northwest,
  28161. southwest,
  28162. northeast,
  28163. southeast
  28164. ];
  28165. }
  28166. };
  28167. var bubbleSize = 12;
  28168. var bubbleAlignments = {
  28169. valignCentre: [],
  28170. alignCentre: [],
  28171. alignLeft: ['tox-pop--align-left'],
  28172. alignRight: ['tox-pop--align-right'],
  28173. right: ['tox-pop--right'],
  28174. left: ['tox-pop--left'],
  28175. bottom: ['tox-pop--bottom'],
  28176. top: ['tox-pop--top']
  28177. };
  28178. var isTouchWithinSelection = function (editor, e) {
  28179. var selection = editor.selection;
  28180. if (selection.isCollapsed() || e.touches.length < 1) {
  28181. return false;
  28182. } else {
  28183. var touch_1 = e.touches[0];
  28184. var rng = selection.getRng();
  28185. var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
  28186. return rngRectOpt.exists(function (rngRect) {
  28187. return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
  28188. });
  28189. }
  28190. };
  28191. var setupiOSOverrides = function (editor) {
  28192. var originalSelection = editor.selection.getRng();
  28193. var selectionReset = function () {
  28194. global$g.setEditorTimeout(editor, function () {
  28195. editor.selection.setRng(originalSelection);
  28196. }, 10);
  28197. unbindEventListeners();
  28198. };
  28199. editor.once('touchend', selectionReset);
  28200. var preventMousedown = function (e) {
  28201. e.preventDefault();
  28202. e.stopImmediatePropagation();
  28203. };
  28204. editor.on('mousedown', preventMousedown, true);
  28205. var clearSelectionReset = function () {
  28206. return unbindEventListeners();
  28207. };
  28208. editor.once('longpresscancel', clearSelectionReset);
  28209. var unbindEventListeners = function () {
  28210. editor.off('touchend', selectionReset);
  28211. editor.off('longpresscancel', clearSelectionReset);
  28212. editor.off('mousedown', preventMousedown);
  28213. };
  28214. };
  28215. var getAnchorSpec = function (editor, e, anchorType) {
  28216. var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  28217. var bubbleYOffset = anchorType === 'point' ? bubbleSize : 0;
  28218. return __assign({
  28219. bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
  28220. layouts: layouts,
  28221. overrides: {
  28222. maxWidthFunction: expandable(),
  28223. maxHeightFunction: expandable$1()
  28224. }
  28225. }, anchorSpec);
  28226. };
  28227. var show = function (editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) {
  28228. var anchorSpec = getAnchorSpec(editor, e, anchorType);
  28229. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  28230. e.preventDefault();
  28231. InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
  28232. menu: {
  28233. markers: markers('normal'),
  28234. highlightImmediately: highlightImmediately
  28235. },
  28236. data: menuData,
  28237. type: 'horizontal'
  28238. }, function () {
  28239. return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === 'node' ? 'node' : 'selection'));
  28240. });
  28241. editor.fire(hideContextToolbarEvent);
  28242. });
  28243. };
  28244. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  28245. var detection = detect$1();
  28246. var isiOS = detection.os.isiOS();
  28247. var isOSX = detection.os.isOSX();
  28248. var isAndroid = detection.os.isAndroid();
  28249. var isTouch = detection.deviceType.isTouch();
  28250. var shouldHighlightImmediately = function () {
  28251. return !(isAndroid || isiOS || isOSX && isTouch);
  28252. };
  28253. var open = function () {
  28254. var items = buildMenu();
  28255. show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
  28256. };
  28257. if ((isOSX || isiOS) && anchorType !== 'node') {
  28258. var openiOS_1 = function () {
  28259. setupiOSOverrides(editor);
  28260. open();
  28261. };
  28262. if (isTouchWithinSelection(editor, e)) {
  28263. openiOS_1();
  28264. } else {
  28265. editor.once('selectionchange', openiOS_1);
  28266. editor.once('touchend', function () {
  28267. return editor.off('selectionchange', openiOS_1);
  28268. });
  28269. }
  28270. } else {
  28271. open();
  28272. }
  28273. };
  28274. var patchPipeConfig = function (config) {
  28275. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  28276. };
  28277. var shouldNeverUseNative = function (editor) {
  28278. return editor.getParam('contextmenu_never_use_native', false, 'boolean');
  28279. };
  28280. var getMenuItems = function (editor, name, defaultItems) {
  28281. var contextMenus = editor.ui.registry.getAll().contextMenus;
  28282. return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () {
  28283. return filter$2(patchPipeConfig(defaultItems), function (item) {
  28284. return has$2(contextMenus, item);
  28285. });
  28286. });
  28287. };
  28288. var isContextMenuDisabled = function (editor) {
  28289. return editor.getParam('contextmenu') === false;
  28290. };
  28291. var getContextMenu = function (editor) {
  28292. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  28293. };
  28294. var getAvoidOverlapSelector = function (editor) {
  28295. return editor.getParam('contextmenu_avoid_overlap', '', 'string');
  28296. };
  28297. var isSeparator = function (item) {
  28298. return isString(item) ? item === '|' : item.type === 'separator';
  28299. };
  28300. var separator = { type: 'separator' };
  28301. var makeContextItem = function (item) {
  28302. var commonMenuItem = function (item) {
  28303. return {
  28304. text: item.text,
  28305. icon: item.icon,
  28306. disabled: item.disabled,
  28307. shortcut: item.shortcut
  28308. };
  28309. };
  28310. if (isString(item)) {
  28311. return item;
  28312. } else {
  28313. switch (item.type) {
  28314. case 'separator':
  28315. return separator;
  28316. case 'submenu':
  28317. return __assign(__assign({ type: 'nestedmenuitem' }, commonMenuItem(item)), {
  28318. getSubmenuItems: function () {
  28319. var items = item.getSubmenuItems();
  28320. if (isString(items)) {
  28321. return items;
  28322. } else {
  28323. return map$2(items, makeContextItem);
  28324. }
  28325. }
  28326. });
  28327. default:
  28328. return __assign(__assign({ type: 'menuitem' }, commonMenuItem(item)), { onAction: noarg(item.onAction) });
  28329. }
  28330. }
  28331. };
  28332. var addContextMenuGroup = function (xs, groupItems) {
  28333. if (groupItems.length === 0) {
  28334. return xs;
  28335. }
  28336. var lastMenuItem = last$2(xs).filter(function (item) {
  28337. return !isSeparator(item);
  28338. });
  28339. var before = lastMenuItem.fold(function () {
  28340. return [];
  28341. }, function (_) {
  28342. return [separator];
  28343. });
  28344. return xs.concat(before).concat(groupItems).concat([separator]);
  28345. };
  28346. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  28347. var sections = foldl(menuConfig, function (acc, name) {
  28348. return get$e(contextMenus, name.toLowerCase()).map(function (menu) {
  28349. var items = menu.update(selectedElement);
  28350. if (isString(items)) {
  28351. return addContextMenuGroup(acc, items.split(' '));
  28352. } else if (items.length > 0) {
  28353. var allItems = map$2(items, makeContextItem);
  28354. return addContextMenuGroup(acc, allItems);
  28355. } else {
  28356. return acc;
  28357. }
  28358. }).getOrThunk(function () {
  28359. return acc.concat([name]);
  28360. });
  28361. }, []);
  28362. if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
  28363. sections.pop();
  28364. }
  28365. return sections;
  28366. };
  28367. var isNativeOverrideKeyEvent = function (editor, e) {
  28368. return e.ctrlKey && !shouldNeverUseNative(editor);
  28369. };
  28370. var isTriggeredByKeyboard = function (editor, e) {
  28371. return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  28372. };
  28373. var getSelectedElement = function (editor, e) {
  28374. return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
  28375. };
  28376. var getAnchorType = function (editor, e) {
  28377. var selector = getAvoidOverlapSelector(editor);
  28378. var anchorType = isTriggeredByKeyboard(editor, e) ? 'selection' : 'point';
  28379. if (isNotEmpty(selector)) {
  28380. var target = getSelectedElement(editor, e);
  28381. var selectorExists = closest(SugarElement.fromDom(target), selector);
  28382. return selectorExists ? 'node' : anchorType;
  28383. } else {
  28384. return anchorType;
  28385. }
  28386. };
  28387. var setup$5 = function (editor, lazySink, backstage) {
  28388. var detection = detect$1();
  28389. var isTouch = detection.deviceType.isTouch;
  28390. var contextmenu = build$1(InlineView.sketch({
  28391. dom: { tag: 'div' },
  28392. lazySink: lazySink,
  28393. onEscape: function () {
  28394. return editor.focus();
  28395. },
  28396. onShow: function () {
  28397. return backstage.setContextMenuState(true);
  28398. },
  28399. onHide: function () {
  28400. return backstage.setContextMenuState(false);
  28401. },
  28402. fireDismissalEventInstead: {},
  28403. inlineBehaviours: derive$1([config('dismissContextMenu', [run$1(dismissRequested(), function (comp, _se) {
  28404. Sandboxing.close(comp);
  28405. editor.focus();
  28406. })])])
  28407. }));
  28408. var hideContextMenu = function (_e) {
  28409. return InlineView.hide(contextmenu);
  28410. };
  28411. var showContextMenu = function (e) {
  28412. if (shouldNeverUseNative(editor)) {
  28413. e.preventDefault();
  28414. }
  28415. if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  28416. return;
  28417. }
  28418. var anchorType = getAnchorType(editor, e);
  28419. var buildMenu = function () {
  28420. var selectedElement = getSelectedElement(editor, e);
  28421. var registry = editor.ui.registry.getAll();
  28422. var menuConfig = getContextMenu(editor);
  28423. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  28424. };
  28425. var initAndShow$2 = isTouch() ? initAndShow : initAndShow$1;
  28426. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType);
  28427. };
  28428. editor.on('init', function () {
  28429. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  28430. editor.on(hideEvents, hideContextMenu);
  28431. editor.on('longpress contextmenu', showContextMenu);
  28432. });
  28433. };
  28434. var adt = Adt.generate([
  28435. {
  28436. offset: [
  28437. 'x',
  28438. 'y'
  28439. ]
  28440. },
  28441. {
  28442. absolute: [
  28443. 'x',
  28444. 'y'
  28445. ]
  28446. },
  28447. {
  28448. fixed: [
  28449. 'x',
  28450. 'y'
  28451. ]
  28452. }
  28453. ]);
  28454. var subtract = function (change) {
  28455. return function (point) {
  28456. return point.translate(-change.left, -change.top);
  28457. };
  28458. };
  28459. var add = function (change) {
  28460. return function (point) {
  28461. return point.translate(change.left, change.top);
  28462. };
  28463. };
  28464. var transform = function (changes) {
  28465. return function (x, y) {
  28466. return foldl(changes, function (rest, f) {
  28467. return f(rest);
  28468. }, SugarPosition(x, y));
  28469. };
  28470. };
  28471. var asFixed = function (coord, scroll, origin) {
  28472. return coord.fold(transform([
  28473. add(origin),
  28474. subtract(scroll)
  28475. ]), transform([subtract(scroll)]), transform([]));
  28476. };
  28477. var asAbsolute = function (coord, scroll, origin) {
  28478. return coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)]));
  28479. };
  28480. var asOffset = function (coord, scroll, origin) {
  28481. return coord.fold(transform([]), transform([subtract(origin)]), transform([
  28482. add(scroll),
  28483. subtract(origin)
  28484. ]));
  28485. };
  28486. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  28487. var a1 = asAbsolute(coord1, scroll, origin);
  28488. var a2 = asAbsolute(coord2, scroll, origin);
  28489. return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
  28490. };
  28491. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  28492. var a1 = asAbsolute(coord1, scroll, origin);
  28493. var a2 = asAbsolute(coord2, scroll, origin);
  28494. var left = Math.abs(a1.left - a2.left);
  28495. var top = Math.abs(a1.top - a2.top);
  28496. return SugarPosition(left, top);
  28497. };
  28498. var toStyles = function (coord, scroll, origin) {
  28499. var stylesOpt = coord.fold(function (x, y) {
  28500. return {
  28501. position: Optional.some('absolute'),
  28502. left: Optional.some(x + 'px'),
  28503. top: Optional.some(y + 'px')
  28504. };
  28505. }, function (x, y) {
  28506. return {
  28507. position: Optional.some('absolute'),
  28508. left: Optional.some(x - origin.left + 'px'),
  28509. top: Optional.some(y - origin.top + 'px')
  28510. };
  28511. }, function (x, y) {
  28512. return {
  28513. position: Optional.some('fixed'),
  28514. left: Optional.some(x + 'px'),
  28515. top: Optional.some(y + 'px')
  28516. };
  28517. });
  28518. return __assign({
  28519. right: Optional.none(),
  28520. bottom: Optional.none()
  28521. }, stylesOpt);
  28522. };
  28523. var translate = function (coord, deltaX, deltaY) {
  28524. return coord.fold(function (x, y) {
  28525. return offset(x + deltaX, y + deltaY);
  28526. }, function (x, y) {
  28527. return absolute(x + deltaX, y + deltaY);
  28528. }, function (x, y) {
  28529. return fixed(x + deltaX, y + deltaY);
  28530. });
  28531. };
  28532. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  28533. var absorbOne = function (stencil, nu) {
  28534. return function (optX, optY) {
  28535. var original = stencil(originalCoord, scroll, origin);
  28536. return nu(optX.getOr(original.left), optY.getOr(original.top));
  28537. };
  28538. };
  28539. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
  28540. };
  28541. var offset = adt.offset;
  28542. var absolute = adt.absolute;
  28543. var fixed = adt.fixed;
  28544. var parseAttrToInt = function (element, name) {
  28545. var value = get$c(element, name);
  28546. return isUndefined(value) ? NaN : parseInt(value, 10);
  28547. };
  28548. var get = function (component, snapsInfo) {
  28549. var element = component.element;
  28550. var x = parseAttrToInt(element, snapsInfo.leftAttr);
  28551. var y = parseAttrToInt(element, snapsInfo.topAttr);
  28552. return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
  28553. };
  28554. var set = function (component, snapsInfo, pt) {
  28555. var element = component.element;
  28556. set$7(element, snapsInfo.leftAttr, pt.left + 'px');
  28557. set$7(element, snapsInfo.topAttr, pt.top + 'px');
  28558. };
  28559. var clear = function (component, snapsInfo) {
  28560. var element = component.element;
  28561. remove$6(element, snapsInfo.leftAttr);
  28562. remove$6(element, snapsInfo.topAttr);
  28563. };
  28564. var getCoords = function (component, snapInfo, coord, delta) {
  28565. return get(component, snapInfo).fold(function () {
  28566. return coord;
  28567. }, function (fixed$1) {
  28568. return fixed(fixed$1.left + delta.left, fixed$1.top + delta.top);
  28569. });
  28570. };
  28571. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  28572. var newCoord = getCoords(component, snapInfo, coord, delta);
  28573. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  28574. var fixedCoord = asFixed(newCoord, scroll, origin);
  28575. set(component, snapInfo, fixedCoord);
  28576. return snap.fold(function () {
  28577. return {
  28578. coord: fixed(fixedCoord.left, fixedCoord.top),
  28579. extra: Optional.none()
  28580. };
  28581. }, function (spanned) {
  28582. return {
  28583. coord: spanned.output,
  28584. extra: spanned.extra
  28585. };
  28586. });
  28587. };
  28588. var stopDrag = function (component, snapInfo) {
  28589. clear(component, snapInfo);
  28590. };
  28591. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  28592. return findMap(snaps, function (snap) {
  28593. var sensor = snap.sensor;
  28594. var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  28595. return inRange ? Optional.some({
  28596. output: absorb(snap.output, newCoord, scroll, origin),
  28597. extra: snap.extra
  28598. }) : Optional.none();
  28599. });
  28600. };
  28601. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  28602. var snaps = snapInfo.getSnapPoints(component);
  28603. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  28604. return matchSnap.orThunk(function () {
  28605. var bestSnap = foldl(snaps, function (acc, snap) {
  28606. var sensor = snap.sensor;
  28607. var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  28608. return acc.deltas.fold(function () {
  28609. return {
  28610. deltas: Optional.some(deltas),
  28611. snap: Optional.some(snap)
  28612. };
  28613. }, function (bestDeltas) {
  28614. var currAvg = (deltas.left + deltas.top) / 2;
  28615. var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
  28616. if (currAvg <= bestAvg) {
  28617. return {
  28618. deltas: Optional.some(deltas),
  28619. snap: Optional.some(snap)
  28620. };
  28621. } else {
  28622. return acc;
  28623. }
  28624. });
  28625. }, {
  28626. deltas: Optional.none(),
  28627. snap: Optional.none()
  28628. });
  28629. return bestSnap.snap.map(function (snap) {
  28630. return {
  28631. output: absorb(snap.output, newCoord, scroll, origin),
  28632. extra: snap.extra
  28633. };
  28634. });
  28635. });
  28636. };
  28637. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  28638. var snaps = snapInfo.getSnapPoints(component);
  28639. return findMatchingSnap(snaps, newCoord, scroll, origin);
  28640. };
  28641. var snapTo$1 = function (snap, scroll, origin) {
  28642. return {
  28643. coord: absorb(snap.output, snap.output, scroll, origin),
  28644. extra: snap.extra
  28645. };
  28646. };
  28647. var snapTo = function (component, dragConfig, _state, snap) {
  28648. var target = dragConfig.getTarget(component.element);
  28649. if (dragConfig.repositionTarget) {
  28650. var doc = owner$4(component.element);
  28651. var scroll_1 = get$6(doc);
  28652. var origin_1 = getOrigin(target);
  28653. var snapPin = snapTo$1(snap, scroll_1, origin_1);
  28654. var styles = toStyles(snapPin.coord, scroll_1, origin_1);
  28655. setOptions(target, styles);
  28656. }
  28657. };
  28658. var DraggingApis = /*#__PURE__*/Object.freeze({
  28659. __proto__: null,
  28660. snapTo: snapTo
  28661. });
  28662. var initialAttribute = 'data-initial-z-index';
  28663. var resetZIndex = function (blocker) {
  28664. parent(blocker.element).filter(isElement$2).each(function (root) {
  28665. getOpt(root, initialAttribute).fold(function () {
  28666. return remove$1(root, 'z-index');
  28667. }, function (zIndex) {
  28668. return set$6(root, 'z-index', zIndex);
  28669. });
  28670. remove$6(root, initialAttribute);
  28671. });
  28672. };
  28673. var changeZIndex = function (blocker) {
  28674. parent(blocker.element).filter(isElement$2).each(function (root) {
  28675. getRaw(root, 'z-index').each(function (zindex) {
  28676. set$7(root, initialAttribute, zindex);
  28677. });
  28678. set$6(root, 'z-index', get$a(blocker.element, 'z-index'));
  28679. });
  28680. };
  28681. var instigate = function (anyComponent, blocker) {
  28682. anyComponent.getSystem().addToGui(blocker);
  28683. changeZIndex(blocker);
  28684. };
  28685. var discard = function (blocker) {
  28686. resetZIndex(blocker);
  28687. blocker.getSystem().removeFromGui(blocker);
  28688. };
  28689. var createComponent = function (component, blockerClass, blockerEvents) {
  28690. return component.getSystem().build(Container.sketch({
  28691. dom: {
  28692. styles: {
  28693. 'left': '0px',
  28694. 'top': '0px',
  28695. 'width': '100%',
  28696. 'height': '100%',
  28697. 'position': 'fixed',
  28698. 'z-index': '1000000000000000'
  28699. },
  28700. classes: [blockerClass]
  28701. },
  28702. events: blockerEvents
  28703. }));
  28704. };
  28705. var SnapSchema = optionObjOf('snaps', [
  28706. required$1('getSnapPoints'),
  28707. onHandler('onSensor'),
  28708. required$1('leftAttr'),
  28709. required$1('topAttr'),
  28710. defaulted('lazyViewport', win),
  28711. defaulted('mustSnap', false)
  28712. ]);
  28713. var schema$6 = [
  28714. defaulted('useFixed', never),
  28715. required$1('blockerClass'),
  28716. defaulted('getTarget', identity$1),
  28717. defaulted('onDrag', noop),
  28718. defaulted('repositionTarget', true),
  28719. defaulted('onDrop', noop),
  28720. defaultedFunction('getBounds', win),
  28721. SnapSchema
  28722. ];
  28723. var getCurrentCoord = function (target) {
  28724. return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  28725. var nu = position === 'fixed' ? fixed : offset;
  28726. return nu(parseInt(left, 10), parseInt(top, 10));
  28727. }).getOrThunk(function () {
  28728. var location = absolute$3(target);
  28729. return absolute(location.left, location.top);
  28730. });
  28731. };
  28732. var clampCoords = function (component, coords, scroll, origin, startData) {
  28733. var bounds = startData.bounds;
  28734. var absoluteCoord = asAbsolute(coords, scroll, origin);
  28735. var newX = clamp$1(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
  28736. var newY = clamp$1(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
  28737. var newCoords = absolute(newX, newY);
  28738. return coords.fold(function () {
  28739. var offset$1 = asOffset(newCoords, scroll, origin);
  28740. return offset(offset$1.left, offset$1.top);
  28741. }, constant$1(newCoords), function () {
  28742. var fixed$1 = asFixed(newCoords, scroll, origin);
  28743. return fixed(fixed$1.left, fixed$1.top);
  28744. });
  28745. };
  28746. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  28747. var newCoord = optSnaps.fold(function () {
  28748. var translated = translate(currentCoord, delta.left, delta.top);
  28749. var fixedCoord = asFixed(translated, scroll, origin);
  28750. return fixed(fixedCoord.left, fixedCoord.top);
  28751. }, function (snapInfo) {
  28752. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  28753. snapping.extra.each(function (extra) {
  28754. snapInfo.onSensor(component, extra);
  28755. });
  28756. return snapping.coord;
  28757. });
  28758. return clampCoords(component, newCoord, scroll, origin, startData);
  28759. };
  28760. var dragBy = function (component, dragConfig, startData, delta) {
  28761. var target = dragConfig.getTarget(component.element);
  28762. if (dragConfig.repositionTarget) {
  28763. var doc = owner$4(component.element);
  28764. var scroll_1 = get$6(doc);
  28765. var origin_1 = getOrigin(target);
  28766. var currentCoord = getCurrentCoord(target);
  28767. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
  28768. var styles = toStyles(newCoord, scroll_1, origin_1);
  28769. setOptions(target, styles);
  28770. }
  28771. dragConfig.onDrag(component, target, delta);
  28772. };
  28773. var calcStartData = function (dragConfig, comp) {
  28774. return {
  28775. bounds: dragConfig.getBounds(),
  28776. height: getOuter$1(comp.element),
  28777. width: getOuter(comp.element)
  28778. };
  28779. };
  28780. var move = function (component, dragConfig, dragState, dragMode, event) {
  28781. var delta = dragState.update(dragMode, event);
  28782. var dragStartData = dragState.getStartData().getOrThunk(function () {
  28783. return calcStartData(dragConfig, component);
  28784. });
  28785. delta.each(function (dlt) {
  28786. dragBy(component, dragConfig, dragStartData, dlt);
  28787. });
  28788. };
  28789. var stop = function (component, blocker, dragConfig, dragState) {
  28790. blocker.each(discard);
  28791. dragConfig.snaps.each(function (snapInfo) {
  28792. stopDrag(component, snapInfo);
  28793. });
  28794. var target = dragConfig.getTarget(component.element);
  28795. dragState.reset();
  28796. dragConfig.onDrop(component, target);
  28797. };
  28798. var handlers = function (events) {
  28799. return function (dragConfig, dragState) {
  28800. var updateStartState = function (comp) {
  28801. dragState.setStartData(calcStartData(dragConfig, comp));
  28802. };
  28803. return derive$2(__spreadArray([run$1(windowScroll(), function (comp) {
  28804. dragState.getStartData().each(function () {
  28805. return updateStartState(comp);
  28806. });
  28807. })], events(dragConfig, dragState, updateStartState)));
  28808. };
  28809. };
  28810. var init$2 = function (dragApi) {
  28811. return derive$2([
  28812. run$1(mousedown(), dragApi.forceDrop),
  28813. run$1(mouseup(), dragApi.drop),
  28814. run$1(mousemove(), function (comp, simulatedEvent) {
  28815. dragApi.move(simulatedEvent.event);
  28816. }),
  28817. run$1(mouseout(), dragApi.delayDrop)
  28818. ]);
  28819. };
  28820. var getData$1 = function (event) {
  28821. return Optional.from(SugarPosition(event.x, event.y));
  28822. };
  28823. var getDelta$1 = function (old, nu) {
  28824. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28825. };
  28826. var MouseData = /*#__PURE__*/Object.freeze({
  28827. __proto__: null,
  28828. getData: getData$1,
  28829. getDelta: getDelta$1
  28830. });
  28831. var events$2 = function (dragConfig, dragState, updateStartState) {
  28832. return [run$1(mousedown(), function (component, simulatedEvent) {
  28833. var raw = simulatedEvent.event.raw;
  28834. if (raw.button !== 0) {
  28835. return;
  28836. }
  28837. simulatedEvent.stop();
  28838. var stop$1 = function () {
  28839. return stop(component, Optional.some(blocker), dragConfig, dragState);
  28840. };
  28841. var delayDrop = DelayedFunction(stop$1, 200);
  28842. var dragApi = {
  28843. drop: stop$1,
  28844. delayDrop: delayDrop.schedule,
  28845. forceDrop: stop$1,
  28846. move: function (event) {
  28847. delayDrop.cancel();
  28848. move(component, dragConfig, dragState, MouseData, event);
  28849. }
  28850. };
  28851. var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
  28852. var start = function () {
  28853. updateStartState(component);
  28854. instigate(component, blocker);
  28855. };
  28856. start();
  28857. })];
  28858. };
  28859. var schema$5 = __spreadArray(__spreadArray([], schema$6), [output$1('dragger', { handlers: handlers(events$2) })]);
  28860. var init$1 = function (dragApi) {
  28861. return derive$2([
  28862. run$1(touchstart(), dragApi.forceDrop),
  28863. run$1(touchend(), dragApi.drop),
  28864. run$1(touchcancel(), dragApi.drop),
  28865. run$1(touchmove(), function (comp, simulatedEvent) {
  28866. dragApi.move(simulatedEvent.event);
  28867. })
  28868. ]);
  28869. };
  28870. var getDataFrom = function (touches) {
  28871. var touch = touches[0];
  28872. return Optional.some(SugarPosition(touch.clientX, touch.clientY));
  28873. };
  28874. var getData = function (event) {
  28875. var raw = event.raw;
  28876. var touches = raw.touches;
  28877. return touches.length === 1 ? getDataFrom(touches) : Optional.none();
  28878. };
  28879. var getDelta = function (old, nu) {
  28880. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28881. };
  28882. var TouchData = /*#__PURE__*/Object.freeze({
  28883. __proto__: null,
  28884. getData: getData,
  28885. getDelta: getDelta
  28886. });
  28887. var events$1 = function (dragConfig, dragState, updateStartState) {
  28888. var blockerSingleton = value$1();
  28889. var stopBlocking = function (component) {
  28890. stop(component, blockerSingleton.get(), dragConfig, dragState);
  28891. blockerSingleton.clear();
  28892. };
  28893. return [
  28894. run$1(touchstart(), function (component, simulatedEvent) {
  28895. simulatedEvent.stop();
  28896. var stop = function () {
  28897. return stopBlocking(component);
  28898. };
  28899. var dragApi = {
  28900. drop: stop,
  28901. delayDrop: noop,
  28902. forceDrop: stop,
  28903. move: function (event) {
  28904. move(component, dragConfig, dragState, TouchData, event);
  28905. }
  28906. };
  28907. var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
  28908. blockerSingleton.set(blocker);
  28909. var start = function () {
  28910. updateStartState(component);
  28911. instigate(component, blocker);
  28912. };
  28913. start();
  28914. }),
  28915. run$1(touchmove(), function (component, simulatedEvent) {
  28916. simulatedEvent.stop();
  28917. move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
  28918. }),
  28919. run$1(touchend(), function (component, simulatedEvent) {
  28920. simulatedEvent.stop();
  28921. stopBlocking(component);
  28922. }),
  28923. run$1(touchcancel(), stopBlocking)
  28924. ];
  28925. };
  28926. var schema$4 = __spreadArray(__spreadArray([], schema$6), [output$1('dragger', { handlers: handlers(events$1) })]);
  28927. var events = function (dragConfig, dragState, updateStartState) {
  28928. return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState)), events$1(dragConfig, dragState, updateStartState));
  28929. };
  28930. var schema$3 = __spreadArray(__spreadArray([], schema$6), [output$1('dragger', { handlers: handlers(events) })]);
  28931. var mouse = schema$5;
  28932. var touch = schema$4;
  28933. var mouseOrTouch = schema$3;
  28934. var DraggingBranches = /*#__PURE__*/Object.freeze({
  28935. __proto__: null,
  28936. mouse: mouse,
  28937. touch: touch,
  28938. mouseOrTouch: mouseOrTouch
  28939. });
  28940. var init = function () {
  28941. var previous = Optional.none();
  28942. var startData = Optional.none();
  28943. var reset = function () {
  28944. previous = Optional.none();
  28945. startData = Optional.none();
  28946. };
  28947. var calculateDelta = function (mode, nu) {
  28948. var result = previous.map(function (old) {
  28949. return mode.getDelta(old, nu);
  28950. });
  28951. previous = Optional.some(nu);
  28952. return result;
  28953. };
  28954. var update = function (mode, dragEvent) {
  28955. return mode.getData(dragEvent).bind(function (nuData) {
  28956. return calculateDelta(mode, nuData);
  28957. });
  28958. };
  28959. var setStartData = function (data) {
  28960. startData = Optional.some(data);
  28961. };
  28962. var getStartData = function () {
  28963. return startData;
  28964. };
  28965. var readState = constant$1({});
  28966. return nu$8({
  28967. readState: readState,
  28968. reset: reset,
  28969. update: update,
  28970. getStartData: getStartData,
  28971. setStartData: setStartData
  28972. });
  28973. };
  28974. var DragState = /*#__PURE__*/Object.freeze({
  28975. __proto__: null,
  28976. init: init
  28977. });
  28978. var Dragging = createModes({
  28979. branchKey: 'mode',
  28980. branches: DraggingBranches,
  28981. name: 'dragging',
  28982. active: {
  28983. events: function (dragConfig, dragState) {
  28984. var dragger = dragConfig.dragger;
  28985. return dragger.handlers(dragConfig, dragState);
  28986. }
  28987. },
  28988. extra: {
  28989. snap: function (sConfig) {
  28990. return {
  28991. sensor: sConfig.sensor,
  28992. range: sConfig.range,
  28993. output: sConfig.output,
  28994. extra: Optional.from(sConfig.extra)
  28995. };
  28996. }
  28997. },
  28998. state: DragState,
  28999. apis: DraggingApis
  29000. });
  29001. var snapWidth = 40;
  29002. var snapOffset = snapWidth / 2;
  29003. var calcSnap = function (selectorOpt, td, x, y, width, height) {
  29004. return selectorOpt.fold(function () {
  29005. return Dragging.snap({
  29006. sensor: absolute(x - snapOffset, y - snapOffset),
  29007. range: SugarPosition(width, height),
  29008. output: absolute(Optional.some(x), Optional.some(y)),
  29009. extra: { td: td }
  29010. });
  29011. }, function (selectorHandle) {
  29012. var sensorLeft = x - snapOffset;
  29013. var sensorTop = y - snapOffset;
  29014. var sensorWidth = snapWidth;
  29015. var sensorHeight = snapWidth;
  29016. var rect = selectorHandle.element.dom.getBoundingClientRect();
  29017. return Dragging.snap({
  29018. sensor: absolute(sensorLeft, sensorTop),
  29019. range: SugarPosition(sensorWidth, sensorHeight),
  29020. output: absolute(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
  29021. extra: { td: td }
  29022. });
  29023. });
  29024. };
  29025. var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  29026. var isSameCell = function (cellOpt, td) {
  29027. return cellOpt.exists(function (currentTd) {
  29028. return eq(currentTd, td);
  29029. });
  29030. };
  29031. return {
  29032. getSnapPoints: getSnapPoints,
  29033. leftAttr: 'data-drag-left',
  29034. topAttr: 'data-drag-top',
  29035. onSensor: function (component, extra) {
  29036. var td = extra.td;
  29037. if (!isSameCell(cell.get(), td)) {
  29038. cell.set(td);
  29039. onChange(td);
  29040. }
  29041. },
  29042. mustSnap: true
  29043. };
  29044. };
  29045. var createSelector = function (snaps) {
  29046. return record(Button.sketch({
  29047. dom: {
  29048. tag: 'div',
  29049. classes: ['tox-selector']
  29050. },
  29051. buttonBehaviours: derive$1([
  29052. Dragging.config({
  29053. mode: 'mouseOrTouch',
  29054. blockerClass: 'blocker',
  29055. snaps: snaps
  29056. }),
  29057. Unselecting.config({})
  29058. ]),
  29059. eventOrder: {
  29060. mousedown: [
  29061. 'dragging',
  29062. 'alloy.base.behaviour'
  29063. ],
  29064. touchstart: [
  29065. 'dragging',
  29066. 'alloy.base.behaviour'
  29067. ]
  29068. }
  29069. }));
  29070. };
  29071. var setup$4 = function (editor, sink) {
  29072. var tlTds = Cell([]);
  29073. var brTds = Cell([]);
  29074. var isVisible = Cell(false);
  29075. var startCell = value$1();
  29076. var finishCell = value$1();
  29077. var getTopLeftSnap = function (td) {
  29078. var box = absolute$2(td);
  29079. return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  29080. };
  29081. var getTopLeftSnaps = function () {
  29082. return map$2(tlTds.get(), function (td) {
  29083. return getTopLeftSnap(td);
  29084. });
  29085. };
  29086. var getBottomRightSnap = function (td) {
  29087. var box = absolute$2(td);
  29088. return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  29089. };
  29090. var getBottomRightSnaps = function () {
  29091. return map$2(brTds.get(), function (td) {
  29092. return getBottomRightSnap(td);
  29093. });
  29094. };
  29095. var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  29096. finishCell.get().each(function (finish) {
  29097. editor.fire('TableSelectorChange', {
  29098. start: start,
  29099. finish: finish
  29100. });
  29101. });
  29102. });
  29103. var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  29104. startCell.get().each(function (start) {
  29105. editor.fire('TableSelectorChange', {
  29106. start: start,
  29107. finish: finish
  29108. });
  29109. });
  29110. });
  29111. var memTopLeft = createSelector(topLeftSnaps);
  29112. var memBottomRight = createSelector(bottomRightSnaps);
  29113. var topLeft = build$1(memTopLeft.asSpec());
  29114. var bottomRight = build$1(memBottomRight.asSpec());
  29115. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  29116. var cellRect = cell.dom.getBoundingClientRect();
  29117. remove$1(selector.element, 'display');
  29118. var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
  29119. var aboveViewport = isAbove(cellRect);
  29120. var belowViewport = isBelow(cellRect, viewportHeight);
  29121. if (aboveViewport || belowViewport) {
  29122. set$6(selector.element, 'display', 'none');
  29123. }
  29124. };
  29125. var snapTo = function (selector, cell, getSnapConfig, pos) {
  29126. var snap = getSnapConfig(cell);
  29127. Dragging.snapTo(selector, snap);
  29128. var isAbove = function (rect) {
  29129. return rect[pos] < 0;
  29130. };
  29131. var isBelow = function (rect, viewportHeight) {
  29132. return rect[pos] > viewportHeight;
  29133. };
  29134. showOrHideHandle(selector, cell, isAbove, isBelow);
  29135. };
  29136. var snapTopLeft = function (cell) {
  29137. return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  29138. };
  29139. var snapLastTopLeft = function () {
  29140. return startCell.get().each(snapTopLeft);
  29141. };
  29142. var snapBottomRight = function (cell) {
  29143. return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  29144. };
  29145. var snapLastBottomRight = function () {
  29146. return finishCell.get().each(snapBottomRight);
  29147. };
  29148. if (detect$1().deviceType.isTouch()) {
  29149. editor.on('TableSelectionChange', function (e) {
  29150. if (!isVisible.get()) {
  29151. attach(sink, topLeft);
  29152. attach(sink, bottomRight);
  29153. isVisible.set(true);
  29154. }
  29155. startCell.set(e.start);
  29156. finishCell.set(e.finish);
  29157. e.otherCells.each(function (otherCells) {
  29158. tlTds.set(otherCells.upOrLeftCells);
  29159. brTds.set(otherCells.downOrRightCells);
  29160. snapTopLeft(e.start);
  29161. snapBottomRight(e.finish);
  29162. });
  29163. });
  29164. editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  29165. snapLastTopLeft();
  29166. snapLastBottomRight();
  29167. });
  29168. editor.on('TableSelectionClear', function () {
  29169. if (isVisible.get()) {
  29170. detach(topLeft);
  29171. detach(bottomRight);
  29172. isVisible.set(false);
  29173. }
  29174. startCell.clear();
  29175. finishCell.clear();
  29176. });
  29177. }
  29178. };
  29179. var isHidden = function (elm) {
  29180. if (elm.nodeType === 1) {
  29181. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  29182. return true;
  29183. }
  29184. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  29185. return true;
  29186. }
  29187. }
  29188. return false;
  29189. };
  29190. var renderElementPath = function (editor, settings, providersBackstage) {
  29191. if (!settings.delimiter) {
  29192. settings.delimiter = '\xBB';
  29193. }
  29194. var getDataPath = function (data) {
  29195. var parts = data || [];
  29196. var newPathElements = map$2(parts, function (part, index) {
  29197. return Button.sketch({
  29198. dom: {
  29199. tag: 'div',
  29200. classes: ['tox-statusbar__path-item'],
  29201. attributes: {
  29202. 'role': 'button',
  29203. 'data-index': index,
  29204. 'tab-index': -1,
  29205. 'aria-level': index + 1
  29206. },
  29207. innerHtml: part.name
  29208. },
  29209. action: function (_btn) {
  29210. editor.focus();
  29211. editor.selection.select(part.element);
  29212. editor.nodeChanged();
  29213. },
  29214. buttonBehaviours: derive$1([
  29215. DisablingConfigs.button(providersBackstage.isDisabled),
  29216. receivingConfig()
  29217. ])
  29218. });
  29219. });
  29220. var divider = {
  29221. dom: {
  29222. tag: 'div',
  29223. classes: ['tox-statusbar__path-divider'],
  29224. attributes: { 'aria-hidden': true },
  29225. innerHtml: ' ' + settings.delimiter + ' '
  29226. }
  29227. };
  29228. return foldl(newPathElements.slice(1), function (acc, element) {
  29229. var newAcc = acc;
  29230. newAcc.push(divider);
  29231. newAcc.push(element);
  29232. return newAcc;
  29233. }, [newPathElements[0]]);
  29234. };
  29235. var updatePath = function (parents) {
  29236. var newPath = [];
  29237. var i = parents.length;
  29238. while (i-- > 0) {
  29239. var parent_1 = parents[i];
  29240. if (parent_1.nodeType === 1 && !isHidden(parent_1)) {
  29241. var args = editor.fire('ResolveName', {
  29242. name: parent_1.nodeName.toLowerCase(),
  29243. target: parent_1
  29244. });
  29245. if (!args.isDefaultPrevented()) {
  29246. newPath.push({
  29247. name: args.name,
  29248. element: parent_1
  29249. });
  29250. }
  29251. if (args.isPropagationStopped()) {
  29252. break;
  29253. }
  29254. }
  29255. }
  29256. return newPath;
  29257. };
  29258. return {
  29259. dom: {
  29260. tag: 'div',
  29261. classes: ['tox-statusbar__path'],
  29262. attributes: { role: 'navigation' }
  29263. },
  29264. behaviours: derive$1([
  29265. Keying.config({
  29266. mode: 'flow',
  29267. selector: 'div[role=button]'
  29268. }),
  29269. Disabling.config({ disabled: providersBackstage.isDisabled }),
  29270. receivingConfig(),
  29271. Tabstopping.config({}),
  29272. Replacing.config({}),
  29273. config('elementPathEvents', [runOnAttached(function (comp, _e) {
  29274. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  29275. return Keying.focusIn(comp);
  29276. });
  29277. editor.on('NodeChange', function (e) {
  29278. var newPath = updatePath(e.parents);
  29279. if (newPath.length > 0) {
  29280. Replacing.set(comp, getDataPath(newPath));
  29281. } else {
  29282. Replacing.set(comp, []);
  29283. }
  29284. });
  29285. })])
  29286. ]),
  29287. components: []
  29288. };
  29289. };
  29290. var ResizeTypes;
  29291. (function (ResizeTypes) {
  29292. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  29293. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  29294. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  29295. }(ResizeTypes || (ResizeTypes = {})));
  29296. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  29297. var dimensions = {};
  29298. dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
  29299. if (resizeType === ResizeTypes.Both) {
  29300. dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
  29301. }
  29302. return dimensions;
  29303. };
  29304. var resize = function (editor, deltas, resizeType) {
  29305. var container = SugarElement.fromDom(editor.getContainer());
  29306. var dimensions = getDimensions(editor, deltas, resizeType, get$8(container), get$7(container));
  29307. each(dimensions, function (val, dim) {
  29308. return set$6(container, dim, numToPx(val));
  29309. });
  29310. fireResizeEditor(editor);
  29311. };
  29312. var getResizeType = function (editor) {
  29313. var fallback = !editor.hasPlugin('autoresize');
  29314. var resize = editor.getParam('resize', fallback);
  29315. if (resize === false) {
  29316. return ResizeTypes.None;
  29317. } else if (resize === 'both') {
  29318. return ResizeTypes.Both;
  29319. } else {
  29320. return ResizeTypes.Vertical;
  29321. }
  29322. };
  29323. var keyboardHandler = function (editor, resizeType, x, y) {
  29324. var scale = 20;
  29325. var delta = SugarPosition(x * scale, y * scale);
  29326. resize(editor, delta, resizeType);
  29327. return Optional.some(true);
  29328. };
  29329. var renderResizeHandler = function (editor, providersBackstage) {
  29330. var resizeType = getResizeType(editor);
  29331. if (resizeType === ResizeTypes.None) {
  29332. return Optional.none();
  29333. }
  29334. return Optional.some(render$3('resize-handle', {
  29335. tag: 'div',
  29336. classes: ['tox-statusbar__resize-handle'],
  29337. attributes: { title: providersBackstage.translate('Resize') },
  29338. behaviours: [
  29339. Dragging.config({
  29340. mode: 'mouse',
  29341. repositionTarget: false,
  29342. onDrag: function (_comp, _target, delta) {
  29343. return resize(editor, delta, resizeType);
  29344. },
  29345. blockerClass: 'tox-blocker'
  29346. }),
  29347. Keying.config({
  29348. mode: 'special',
  29349. onLeft: function () {
  29350. return keyboardHandler(editor, resizeType, -1, 0);
  29351. },
  29352. onRight: function () {
  29353. return keyboardHandler(editor, resizeType, 1, 0);
  29354. },
  29355. onUp: function () {
  29356. return keyboardHandler(editor, resizeType, 0, -1);
  29357. },
  29358. onDown: function () {
  29359. return keyboardHandler(editor, resizeType, 0, 1);
  29360. }
  29361. }),
  29362. Tabstopping.config({}),
  29363. Focusing.config({})
  29364. ]
  29365. }, providersBackstage.icons));
  29366. };
  29367. var renderWordCount = function (editor, providersBackstage) {
  29368. var _a;
  29369. var replaceCountText = function (comp, count, mode) {
  29370. return Replacing.set(comp, [text(providersBackstage.translate([
  29371. '{0} ' + mode,
  29372. count[mode]
  29373. ]))]);
  29374. };
  29375. return Button.sketch({
  29376. dom: {
  29377. tag: 'button',
  29378. classes: ['tox-statusbar__wordcount']
  29379. },
  29380. components: [],
  29381. buttonBehaviours: derive$1([
  29382. DisablingConfigs.button(providersBackstage.isDisabled),
  29383. receivingConfig(),
  29384. Tabstopping.config({}),
  29385. Replacing.config({}),
  29386. Representing.config({
  29387. store: {
  29388. mode: 'memory',
  29389. initialValue: {
  29390. mode: 'words',
  29391. count: {
  29392. words: 0,
  29393. characters: 0
  29394. }
  29395. }
  29396. }
  29397. }),
  29398. config('wordcount-events', [
  29399. runOnExecute$1(function (comp) {
  29400. var currentVal = Representing.getValue(comp);
  29401. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  29402. Representing.setValue(comp, {
  29403. mode: newMode,
  29404. count: currentVal.count
  29405. });
  29406. replaceCountText(comp, currentVal.count, newMode);
  29407. }),
  29408. runOnAttached(function (comp) {
  29409. editor.on('wordCountUpdate', function (e) {
  29410. var mode = Representing.getValue(comp).mode;
  29411. Representing.setValue(comp, {
  29412. mode: mode,
  29413. count: e.wordCount
  29414. });
  29415. replaceCountText(comp, e.wordCount, mode);
  29416. });
  29417. })
  29418. ])
  29419. ]),
  29420. eventOrder: (_a = {}, _a[execute$5()] = [
  29421. 'disabling',
  29422. 'alloy.base.behaviour',
  29423. 'wordcount-events'
  29424. ], _a)
  29425. });
  29426. };
  29427. var renderStatusbar = function (editor, providersBackstage) {
  29428. var renderBranding = function () {
  29429. var label = global$f.translate([
  29430. 'Powered by {0}',
  29431. 'Tiny'
  29432. ]);
  29433. var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&amp;utm_medium=poweredby&amp;utm_source=tinymce&amp;utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + '</a>';
  29434. return {
  29435. dom: {
  29436. tag: 'span',
  29437. classes: ['tox-statusbar__branding'],
  29438. innerHtml: linkHtml
  29439. }
  29440. };
  29441. };
  29442. var getTextComponents = function () {
  29443. var components = [];
  29444. if (editor.getParam('elementpath', true, 'boolean')) {
  29445. components.push(renderElementPath(editor, {}, providersBackstage));
  29446. }
  29447. if (editor.hasPlugin('wordcount')) {
  29448. components.push(renderWordCount(editor, providersBackstage));
  29449. }
  29450. if (editor.getParam('branding', true, 'boolean')) {
  29451. components.push(renderBranding());
  29452. }
  29453. if (components.length > 0) {
  29454. return [{
  29455. dom: {
  29456. tag: 'div',
  29457. classes: ['tox-statusbar__text-container']
  29458. },
  29459. components: components
  29460. }];
  29461. }
  29462. return [];
  29463. };
  29464. var getComponents = function () {
  29465. var components = getTextComponents();
  29466. var resizeHandler = renderResizeHandler(editor, providersBackstage);
  29467. return components.concat(resizeHandler.toArray());
  29468. };
  29469. return {
  29470. dom: {
  29471. tag: 'div',
  29472. classes: ['tox-statusbar']
  29473. },
  29474. components: getComponents()
  29475. };
  29476. };
  29477. var setup$3 = function (editor) {
  29478. var _a;
  29479. var isInline = editor.inline;
  29480. var mode = isInline ? Inline : Iframe;
  29481. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  29482. var lazyOuterContainer = Optional.none();
  29483. var platform = detect$1();
  29484. var isIE = platform.browser.isIE();
  29485. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  29486. var isTouch = platform.deviceType.isTouch();
  29487. var touchPlatformClass = 'tox-platform-touch';
  29488. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  29489. var isToolbarBottom = isToolbarLocationBottom(editor);
  29490. var uiContainer = getUiContainer(editor);
  29491. var dirAttributes = global$f.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  29492. var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
  29493. var lazyHeader = function () {
  29494. return lazyOuterContainer.bind(OuterContainer.getHeader);
  29495. };
  29496. var isHeaderDocked = function () {
  29497. return header.isDocked(lazyHeader);
  29498. };
  29499. var resizeUiMothership = function () {
  29500. set$6(uiMothership.element, 'width', document.body.clientWidth + 'px');
  29501. };
  29502. var makeSinkDefinition = function () {
  29503. var isGridUiContainer = eq(body(), uiContainer) && get$a(uiContainer, 'display') === 'grid';
  29504. var sinkSpec = {
  29505. dom: __assign({
  29506. tag: 'div',
  29507. classes: [
  29508. 'tox',
  29509. 'tox-silver-sink',
  29510. 'tox-tinymce-aux'
  29511. ].concat(platformClasses).concat(deviceClasses)
  29512. }, dirAttributes),
  29513. behaviours: derive$1([Positioning.config({
  29514. useFixed: function () {
  29515. return isHeaderDocked();
  29516. }
  29517. })])
  29518. };
  29519. var reactiveWidthSpec = {
  29520. dom: { styles: { width: document.body.clientWidth + 'px' } },
  29521. events: derive$2([run$1(windowResize(), resizeUiMothership)])
  29522. };
  29523. return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
  29524. };
  29525. var sink = build$1(makeSinkDefinition());
  29526. var lazySink = function () {
  29527. return Result.value(sink);
  29528. };
  29529. var memAnchorBar = record({
  29530. dom: {
  29531. tag: 'div',
  29532. classes: ['tox-anchorbar']
  29533. }
  29534. });
  29535. var lazyAnchorBar = function () {
  29536. return lazyOuterContainer.bind(function (container) {
  29537. return memAnchorBar.getOpt(container);
  29538. }).getOrDie('Could not find a anchor bar element');
  29539. };
  29540. var lazyToolbar = function () {
  29541. return lazyOuterContainer.bind(function (container) {
  29542. return OuterContainer.getToolbar(container);
  29543. }).getOrDie('Could not find more toolbar element');
  29544. };
  29545. var lazyThrobber = function () {
  29546. return lazyOuterContainer.bind(function (container) {
  29547. return OuterContainer.getThrobber(container);
  29548. }).getOrDie('Could not find throbber element');
  29549. };
  29550. var backstage = init$7(sink, editor, lazyAnchorBar);
  29551. var partMenubar = OuterContainer.parts.menubar({
  29552. dom: {
  29553. tag: 'div',
  29554. classes: ['tox-menubar']
  29555. },
  29556. backstage: backstage,
  29557. onEscape: function () {
  29558. editor.focus();
  29559. }
  29560. });
  29561. var toolbarMode = getToolbarMode(editor);
  29562. var partToolbar = OuterContainer.parts.toolbar(__assign({
  29563. dom: {
  29564. tag: 'div',
  29565. classes: ['tox-toolbar']
  29566. },
  29567. getSink: lazySink,
  29568. providers: backstage.shared.providers,
  29569. onEscape: function () {
  29570. editor.focus();
  29571. },
  29572. type: toolbarMode,
  29573. lazyToolbar: lazyToolbar,
  29574. lazyHeader: function () {
  29575. return lazyHeader().getOrDie('Could not find header element');
  29576. }
  29577. }, verticalDirAttributes));
  29578. var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
  29579. dom: {
  29580. tag: 'div',
  29581. classes: ['tox-toolbar-overlord']
  29582. },
  29583. providers: backstage.shared.providers,
  29584. onEscape: function () {
  29585. editor.focus();
  29586. },
  29587. type: toolbarMode
  29588. });
  29589. var partSocket = OuterContainer.parts.socket({
  29590. dom: {
  29591. tag: 'div',
  29592. classes: ['tox-edit-area']
  29593. }
  29594. });
  29595. var partSidebar = OuterContainer.parts.sidebar({
  29596. dom: {
  29597. tag: 'div',
  29598. classes: ['tox-sidebar']
  29599. }
  29600. });
  29601. var partThrobber = OuterContainer.parts.throbber({
  29602. dom: {
  29603. tag: 'div',
  29604. classes: ['tox-throbber']
  29605. },
  29606. backstage: backstage
  29607. });
  29608. var sb = editor.getParam('statusbar', true, 'boolean');
  29609. var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
  29610. var socketSidebarContainer = {
  29611. dom: {
  29612. tag: 'div',
  29613. classes: ['tox-sidebar-wrap']
  29614. },
  29615. components: [
  29616. partSocket,
  29617. partSidebar
  29618. ]
  29619. };
  29620. var hasMultipleToolbar = isMultipleToolbars(editor);
  29621. var hasToolbar = isToolbarEnabled(editor);
  29622. var hasMenubar = isMenubarEnabled(editor);
  29623. var getPartToolbar = function () {
  29624. if (hasMultipleToolbar) {
  29625. return [partMultipleToolbar];
  29626. } else if (hasToolbar) {
  29627. return [partToolbar];
  29628. } else {
  29629. return [];
  29630. }
  29631. };
  29632. var partHeader = OuterContainer.parts.header({
  29633. dom: __assign({
  29634. tag: 'div',
  29635. classes: ['tox-editor-header']
  29636. }, verticalDirAttributes),
  29637. components: flatten([
  29638. hasMenubar ? [partMenubar] : [],
  29639. getPartToolbar(),
  29640. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  29641. ]),
  29642. sticky: isStickyToolbar(editor),
  29643. editor: editor,
  29644. sharedBackstage: backstage.shared
  29645. });
  29646. var editorComponents = flatten([
  29647. isToolbarBottom ? [] : [partHeader],
  29648. isInline ? [] : [socketSidebarContainer],
  29649. isToolbarBottom ? [partHeader] : []
  29650. ]);
  29651. var editorContainer = {
  29652. dom: {
  29653. tag: 'div',
  29654. classes: ['tox-editor-container']
  29655. },
  29656. components: editorComponents
  29657. };
  29658. var containerComponents = flatten([
  29659. [editorContainer],
  29660. isInline ? [] : statusbar.toArray(),
  29661. [partThrobber]
  29662. ]);
  29663. var isHidden = isDistractionFree(editor);
  29664. var attributes = __assign(__assign({ role: 'application' }, global$f.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  29665. var outerContainer = build$1(OuterContainer.sketch({
  29666. dom: {
  29667. tag: 'div',
  29668. classes: [
  29669. 'tox',
  29670. 'tox-tinymce'
  29671. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
  29672. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  29673. opacity: '0',
  29674. border: '0'
  29675. } : {}),
  29676. attributes: attributes
  29677. },
  29678. components: containerComponents,
  29679. behaviours: derive$1([
  29680. receivingConfig(),
  29681. Disabling.config({ disableClass: 'tox-tinymce--disabled' }),
  29682. Keying.config({
  29683. mode: 'cyclic',
  29684. 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'
  29685. })
  29686. ])
  29687. }));
  29688. lazyOuterContainer = Optional.some(outerContainer);
  29689. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  29690. OuterContainer.focusMenubar(outerContainer);
  29691. });
  29692. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  29693. OuterContainer.focusToolbar(outerContainer);
  29694. });
  29695. editor.addCommand('ToggleToolbarDrawer', function () {
  29696. OuterContainer.toggleToolbarDrawer(outerContainer);
  29697. });
  29698. editor.addQueryStateHandler('ToggleToolbarDrawer', function () {
  29699. return OuterContainer.isToolbarDrawerToggled(outerContainer);
  29700. });
  29701. var mothership = takeover(outerContainer);
  29702. var uiMothership = takeover(sink);
  29703. setup$b(editor, mothership, uiMothership);
  29704. var getUi = function () {
  29705. var channels = {
  29706. broadcastAll: uiMothership.broadcast,
  29707. broadcastOn: uiMothership.broadcastOn,
  29708. register: noop
  29709. };
  29710. return { channels: channels };
  29711. };
  29712. var setEditorSize = function () {
  29713. var parsedHeight = numToPx(getHeightWithFallback(editor));
  29714. var parsedWidth = numToPx(getWidthWithFallback(editor));
  29715. if (!editor.inline) {
  29716. if (isValidValue('div', 'width', parsedWidth)) {
  29717. set$6(outerContainer.element, 'width', parsedWidth);
  29718. }
  29719. if (isValidValue('div', 'height', parsedHeight)) {
  29720. set$6(outerContainer.element, 'height', parsedHeight);
  29721. } else {
  29722. set$6(outerContainer.element, 'height', '200px');
  29723. }
  29724. }
  29725. return parsedHeight;
  29726. };
  29727. var renderUI = function () {
  29728. header.setup(editor, backstage.shared, lazyHeader);
  29729. setup$6(editor, backstage);
  29730. setup$5(editor, lazySink, backstage);
  29731. setup$8(editor);
  29732. setup$7(editor, lazyThrobber, backstage.shared);
  29733. map(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  29734. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  29735. });
  29736. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  29737. var toolbarOpt = getMultipleToolbarsSetting(editor);
  29738. var rawUiConfig = {
  29739. menuItems: menuItems,
  29740. menus: getMenus(editor),
  29741. menubar: getMenubar(editor),
  29742. toolbar: toolbarOpt.getOrThunk(function () {
  29743. return getToolbar(editor);
  29744. }),
  29745. allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  29746. buttons: buttons,
  29747. sidebar: sidebars
  29748. };
  29749. register$7(editor, contextToolbars, sink, { backstage: backstage });
  29750. setup$4(editor, sink);
  29751. var elm = editor.getElement();
  29752. var height = setEditorSize();
  29753. var uiComponents = {
  29754. mothership: mothership,
  29755. uiMothership: uiMothership,
  29756. outerContainer: outerContainer
  29757. };
  29758. var args = {
  29759. targetNode: elm,
  29760. height: height
  29761. };
  29762. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  29763. };
  29764. return {
  29765. mothership: mothership,
  29766. uiMothership: uiMothership,
  29767. backstage: backstage,
  29768. renderUI: renderUI,
  29769. getUi: getUi
  29770. };
  29771. };
  29772. var describedBy = function (describedElement, describeElement) {
  29773. var describeId = Optional.from(get$c(describedElement, 'id')).fold(function () {
  29774. var id = generate$6('dialog-describe');
  29775. set$7(describeElement, 'id', id);
  29776. return id;
  29777. }, identity$1);
  29778. set$7(describedElement, 'aria-describedby', describeId);
  29779. };
  29780. var labelledBy = function (labelledElement, labelElement) {
  29781. var labelId = getOpt(labelledElement, 'id').fold(function () {
  29782. var id = generate$6('dialog-label');
  29783. set$7(labelElement, 'id', id);
  29784. return id;
  29785. }, identity$1);
  29786. set$7(labelledElement, 'aria-labelledby', labelId);
  29787. };
  29788. var schema$2 = constant$1([
  29789. required$1('lazySink'),
  29790. option('dragBlockClass'),
  29791. defaultedFunction('getBounds', win),
  29792. defaulted('useTabstopAt', always),
  29793. defaulted('eventOrder', {}),
  29794. field('modalBehaviours', [Keying]),
  29795. onKeyboardHandler('onExecute'),
  29796. onStrictKeyboardHandler('onEscape')
  29797. ]);
  29798. var basic = { sketch: identity$1 };
  29799. var parts$2 = constant$1([
  29800. optional({
  29801. name: 'draghandle',
  29802. overrides: function (detail, spec) {
  29803. return {
  29804. behaviours: derive$1([Dragging.config({
  29805. mode: 'mouse',
  29806. getTarget: function (handle) {
  29807. return ancestor(handle, '[role="dialog"]').getOr(handle);
  29808. },
  29809. 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),
  29810. getBounds: detail.getDragBounds
  29811. })])
  29812. };
  29813. }
  29814. }),
  29815. required({
  29816. schema: [required$1('dom')],
  29817. name: 'title'
  29818. }),
  29819. required({
  29820. factory: basic,
  29821. schema: [required$1('dom')],
  29822. name: 'close'
  29823. }),
  29824. required({
  29825. factory: basic,
  29826. schema: [required$1('dom')],
  29827. name: 'body'
  29828. }),
  29829. optional({
  29830. factory: basic,
  29831. schema: [required$1('dom')],
  29832. name: 'footer'
  29833. }),
  29834. external$1({
  29835. factory: {
  29836. sketch: function (spec, detail) {
  29837. return __assign(__assign({}, spec), {
  29838. dom: detail.dom,
  29839. components: detail.components
  29840. });
  29841. }
  29842. },
  29843. schema: [
  29844. defaulted('dom', {
  29845. tag: 'div',
  29846. styles: {
  29847. position: 'fixed',
  29848. left: '0px',
  29849. top: '0px',
  29850. right: '0px',
  29851. bottom: '0px'
  29852. }
  29853. }),
  29854. defaulted('components', [])
  29855. ],
  29856. name: 'blocker'
  29857. })
  29858. ]);
  29859. var factory$4 = function (detail, components, spec, externals) {
  29860. var _a;
  29861. var dialogComp = value$1();
  29862. var showDialog = function (dialog) {
  29863. dialogComp.set(dialog);
  29864. var sink = detail.lazySink(dialog).getOrDie();
  29865. var externalBlocker = externals.blocker();
  29866. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  29867. components: externalBlocker.components.concat([premade(dialog)]),
  29868. behaviours: derive$1([
  29869. Focusing.config({}),
  29870. config('dialog-blocker-events', [runOnSource(focusin(), function () {
  29871. Keying.focusIn(dialog);
  29872. })])
  29873. ])
  29874. }));
  29875. attach(sink, blocker);
  29876. Keying.focusIn(dialog);
  29877. };
  29878. var hideDialog = function (dialog) {
  29879. dialogComp.clear();
  29880. parent(dialog.element).each(function (blockerDom) {
  29881. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  29882. detach(blocker);
  29883. });
  29884. });
  29885. };
  29886. var getDialogBody = function (dialog) {
  29887. return getPartOrDie(dialog, detail, 'body');
  29888. };
  29889. var getDialogFooter = function (dialog) {
  29890. return getPartOrDie(dialog, detail, 'footer');
  29891. };
  29892. var setBusy = function (dialog, getBusySpec) {
  29893. Blocking.block(dialog, getBusySpec);
  29894. };
  29895. var setIdle = function (dialog) {
  29896. Blocking.unblock(dialog);
  29897. };
  29898. var modalEventsId = generate$6('modal-events');
  29899. var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a));
  29900. return {
  29901. uid: detail.uid,
  29902. dom: detail.dom,
  29903. components: components,
  29904. apis: {
  29905. show: showDialog,
  29906. hide: hideDialog,
  29907. getBody: getDialogBody,
  29908. getFooter: getDialogFooter,
  29909. setIdle: setIdle,
  29910. setBusy: setBusy
  29911. },
  29912. eventOrder: eventOrder,
  29913. domModification: {
  29914. attributes: {
  29915. 'role': 'dialog',
  29916. 'aria-modal': 'true'
  29917. }
  29918. },
  29919. behaviours: augment(detail.modalBehaviours, [
  29920. Replacing.config({}),
  29921. Keying.config({
  29922. mode: 'cyclic',
  29923. onEnter: detail.onExecute,
  29924. onEscape: detail.onEscape,
  29925. useTabstopAt: detail.useTabstopAt
  29926. }),
  29927. Blocking.config({ getRoot: dialogComp.get }),
  29928. config(modalEventsId, [runOnAttached(function (c) {
  29929. labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
  29930. describedBy(c.element, getPartOrDie(c, detail, 'body').element);
  29931. })])
  29932. ])
  29933. };
  29934. };
  29935. var ModalDialog = composite({
  29936. name: 'ModalDialog',
  29937. configFields: schema$2(),
  29938. partFields: parts$2(),
  29939. factory: factory$4,
  29940. apis: {
  29941. show: function (apis, dialog) {
  29942. apis.show(dialog);
  29943. },
  29944. hide: function (apis, dialog) {
  29945. apis.hide(dialog);
  29946. },
  29947. getBody: function (apis, dialog) {
  29948. return apis.getBody(dialog);
  29949. },
  29950. getFooter: function (apis, dialog) {
  29951. return apis.getFooter(dialog);
  29952. },
  29953. setBusy: function (apis, dialog, getBusySpec) {
  29954. apis.setBusy(dialog, getBusySpec);
  29955. },
  29956. setIdle: function (apis, dialog) {
  29957. apis.setIdle(dialog);
  29958. }
  29959. }
  29960. });
  29961. var dialogToggleMenuItemSchema = objOf([
  29962. requiredString('type'),
  29963. requiredString('name')
  29964. ].concat(commonMenuItemFields));
  29965. var dialogToggleMenuItemDataProcessor = boolean;
  29966. var baseFooterButtonFields = [
  29967. field$1('name', 'name', defaultedThunk(function () {
  29968. return generate$6('button-name');
  29969. }), string),
  29970. optionString('icon'),
  29971. defaultedStringEnum('align', 'end', [
  29972. 'start',
  29973. 'end'
  29974. ]),
  29975. defaultedBoolean('primary', false),
  29976. defaultedBoolean('disabled', false)
  29977. ];
  29978. var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields), [requiredString('text')]);
  29979. var normalFooterButtonFields = __spreadArray([requiredStringEnum('type', [
  29980. 'submit',
  29981. 'cancel',
  29982. 'custom'
  29983. ])], dialogFooterButtonFields);
  29984. var menuFooterButtonFields = __spreadArray([
  29985. requiredStringEnum('type', ['menu']),
  29986. optionString('text'),
  29987. optionString('tooltip'),
  29988. optionString('icon'),
  29989. requiredArrayOf('items', dialogToggleMenuItemSchema)
  29990. ], baseFooterButtonFields);
  29991. var dialogFooterButtonSchema = choose$1('type', {
  29992. submit: normalFooterButtonFields,
  29993. cancel: normalFooterButtonFields,
  29994. custom: normalFooterButtonFields,
  29995. menu: menuFooterButtonFields
  29996. });
  29997. var alertBannerFields = [
  29998. requiredString('type'),
  29999. requiredString('text'),
  30000. requiredStringEnum('level', [
  30001. 'info',
  30002. 'warn',
  30003. 'error',
  30004. 'success'
  30005. ]),
  30006. requiredString('icon'),
  30007. defaulted('url', '')
  30008. ];
  30009. var alertBannerSchema = objOf(alertBannerFields);
  30010. var createBarFields = function (itemsField) {
  30011. return [
  30012. requiredString('type'),
  30013. itemsField
  30014. ];
  30015. };
  30016. var buttonFields = [
  30017. requiredString('type'),
  30018. requiredString('text'),
  30019. defaultedBoolean('disabled', false),
  30020. defaultedBoolean('primary', false),
  30021. field$1('name', 'name', defaultedThunk(function () {
  30022. return generate$6('button-name');
  30023. }), string),
  30024. optionString('icon'),
  30025. defaultedBoolean('borderless', false)
  30026. ];
  30027. var buttonSchema = objOf(buttonFields);
  30028. var checkboxFields = [
  30029. requiredString('type'),
  30030. requiredString('name'),
  30031. requiredString('label'),
  30032. defaultedBoolean('disabled', false)
  30033. ];
  30034. var checkboxSchema = objOf(checkboxFields);
  30035. var checkboxDataProcessor = boolean;
  30036. var formComponentFields = [
  30037. requiredString('type'),
  30038. requiredString('name')
  30039. ];
  30040. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  30041. var collectionFields = formComponentWithLabelFields.concat([defaulted('columns', 'auto')]);
  30042. var collectionSchema = objOf(collectionFields);
  30043. var collectionDataProcessor = arrOfObj([
  30044. requiredString('value'),
  30045. requiredString('text'),
  30046. requiredString('icon')
  30047. ]);
  30048. var colorInputFields = formComponentWithLabelFields;
  30049. var colorInputSchema = objOf(colorInputFields);
  30050. var colorInputDataProcessor = string;
  30051. var colorPickerFields = formComponentWithLabelFields;
  30052. var colorPickerSchema = objOf(colorPickerFields);
  30053. var colorPickerDataProcessor = string;
  30054. var customEditorFields = formComponentFields.concat([
  30055. defaultedString('tag', 'textarea'),
  30056. requiredString('scriptId'),
  30057. requiredString('scriptUrl'),
  30058. defaultedPostMsg('settings', undefined)
  30059. ]);
  30060. var customEditorFieldsOld = formComponentFields.concat([
  30061. defaultedString('tag', 'textarea'),
  30062. requiredFunction('init')
  30063. ]);
  30064. var customEditorSchema = valueOf(function (v) {
  30065. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  30066. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  30067. });
  30068. });
  30069. var customEditorDataProcessor = string;
  30070. var dropZoneFields = formComponentWithLabelFields;
  30071. var dropZoneSchema = objOf(dropZoneFields);
  30072. var dropZoneDataProcessor = arrOfVal();
  30073. var createGridFields = function (itemsField) {
  30074. return [
  30075. requiredString('type'),
  30076. requiredNumber('columns'),
  30077. itemsField
  30078. ];
  30079. };
  30080. var htmlPanelFields = [
  30081. requiredString('type'),
  30082. requiredString('html'),
  30083. defaultedStringEnum('presets', 'presentation', [
  30084. 'presentation',
  30085. 'document'
  30086. ])
  30087. ];
  30088. var htmlPanelSchema = objOf(htmlPanelFields);
  30089. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  30090. var iframeSchema = objOf(iframeFields);
  30091. var iframeDataProcessor = string;
  30092. var imageToolsFields = formComponentWithLabelFields.concat([requiredOf('currentState', objOf([
  30093. required$1('blob'),
  30094. requiredString('url')
  30095. ]))]);
  30096. var imageToolsSchema = objOf(imageToolsFields);
  30097. var inputFields = formComponentWithLabelFields.concat([
  30098. optionString('inputMode'),
  30099. optionString('placeholder'),
  30100. defaultedBoolean('maximized', false),
  30101. defaultedBoolean('disabled', false)
  30102. ]);
  30103. var inputSchema = objOf(inputFields);
  30104. var inputDataProcessor = string;
  30105. var createLabelFields = function (itemsField) {
  30106. return [
  30107. requiredString('type'),
  30108. requiredString('label'),
  30109. itemsField
  30110. ];
  30111. };
  30112. var listBoxSingleItemFields = [
  30113. requiredString('text'),
  30114. requiredString('value')
  30115. ];
  30116. var listBoxNestedItemFields = [
  30117. requiredString('text'),
  30118. requiredArrayOf('items', thunkOf('items', function () {
  30119. return listBoxItemSchema;
  30120. }))
  30121. ];
  30122. var listBoxItemSchema = oneOf([
  30123. objOf(listBoxSingleItemFields),
  30124. objOf(listBoxNestedItemFields)
  30125. ]);
  30126. var listBoxFields = formComponentWithLabelFields.concat([
  30127. requiredArrayOf('items', listBoxItemSchema),
  30128. defaultedBoolean('disabled', false)
  30129. ]);
  30130. var listBoxSchema = objOf(listBoxFields);
  30131. var listBoxDataProcessor = string;
  30132. var selectBoxFields = formComponentWithLabelFields.concat([
  30133. requiredArrayOfObj('items', [
  30134. requiredString('text'),
  30135. requiredString('value')
  30136. ]),
  30137. defaultedNumber('size', 1),
  30138. defaultedBoolean('disabled', false)
  30139. ]);
  30140. var selectBoxSchema = objOf(selectBoxFields);
  30141. var selectBoxDataProcessor = string;
  30142. var sizeInputFields = formComponentWithLabelFields.concat([
  30143. defaultedBoolean('constrain', true),
  30144. defaultedBoolean('disabled', false)
  30145. ]);
  30146. var sizeInputSchema = objOf(sizeInputFields);
  30147. var sizeInputDataProcessor = objOf([
  30148. requiredString('width'),
  30149. requiredString('height')
  30150. ]);
  30151. var tableFields = [
  30152. requiredString('type'),
  30153. requiredArrayOf('header', string),
  30154. requiredArrayOf('cells', arrOf(string))
  30155. ];
  30156. var tableSchema = objOf(tableFields);
  30157. var textAreaFields = formComponentWithLabelFields.concat([
  30158. optionString('placeholder'),
  30159. defaultedBoolean('maximized', false),
  30160. defaultedBoolean('disabled', false)
  30161. ]);
  30162. var textAreaSchema = objOf(textAreaFields);
  30163. var textAreaDataProcessor = string;
  30164. var urlInputFields = formComponentWithLabelFields.concat([
  30165. defaultedStringEnum('filetype', 'file', [
  30166. 'image',
  30167. 'media',
  30168. 'file'
  30169. ]),
  30170. defaulted('disabled', false)
  30171. ]);
  30172. var urlInputSchema = objOf(urlInputFields);
  30173. var urlInputDataProcessor = objOf([
  30174. requiredString('value'),
  30175. defaulted('meta', {})
  30176. ]);
  30177. var createItemsField = function (name) {
  30178. return field$1('items', 'items', required$2(), arrOf(valueOf(function (v) {
  30179. return asRaw('Checking item of ' + name, itemSchema, v).fold(function (sErr) {
  30180. return Result.error(formatError(sErr));
  30181. }, function (passValue) {
  30182. return Result.value(passValue);
  30183. });
  30184. })));
  30185. };
  30186. var itemSchema = valueThunk(function () {
  30187. return choose$2('type', {
  30188. alertbanner: alertBannerSchema,
  30189. bar: objOf(createBarFields(createItemsField('bar'))),
  30190. button: buttonSchema,
  30191. checkbox: checkboxSchema,
  30192. colorinput: colorInputSchema,
  30193. colorpicker: colorPickerSchema,
  30194. dropzone: dropZoneSchema,
  30195. grid: objOf(createGridFields(createItemsField('grid'))),
  30196. iframe: iframeSchema,
  30197. input: inputSchema,
  30198. listbox: listBoxSchema,
  30199. selectbox: selectBoxSchema,
  30200. sizeinput: sizeInputSchema,
  30201. textarea: textAreaSchema,
  30202. urlinput: urlInputSchema,
  30203. customeditor: customEditorSchema,
  30204. htmlpanel: htmlPanelSchema,
  30205. imagetools: imageToolsSchema,
  30206. collection: collectionSchema,
  30207. label: objOf(createLabelFields(createItemsField('label'))),
  30208. table: tableSchema,
  30209. panel: panelSchema
  30210. });
  30211. });
  30212. var panelFields = [
  30213. requiredString('type'),
  30214. defaulted('classes', []),
  30215. requiredArrayOf('items', itemSchema)
  30216. ];
  30217. var panelSchema = objOf(panelFields);
  30218. var tabFields = [
  30219. field$1('name', 'name', defaultedThunk(function () {
  30220. return generate$6('tab-name');
  30221. }), string),
  30222. requiredString('title'),
  30223. requiredArrayOf('items', itemSchema)
  30224. ];
  30225. var tabPanelFields = [
  30226. requiredString('type'),
  30227. requiredArrayOfObj('tabs', tabFields)
  30228. ];
  30229. var tabPanelSchema = objOf(tabPanelFields);
  30230. var dialogButtonFields = dialogFooterButtonFields;
  30231. var dialogButtonSchema = dialogFooterButtonSchema;
  30232. var dialogSchema = objOf([
  30233. requiredString('title'),
  30234. requiredOf('body', choose$2('type', {
  30235. panel: panelSchema,
  30236. tabpanel: tabPanelSchema
  30237. })),
  30238. defaultedString('size', 'normal'),
  30239. requiredArrayOf('buttons', dialogButtonSchema),
  30240. defaulted('initialData', {}),
  30241. defaultedFunction('onAction', noop),
  30242. defaultedFunction('onChange', noop),
  30243. defaultedFunction('onSubmit', noop),
  30244. defaultedFunction('onClose', noop),
  30245. defaultedFunction('onCancel', noop),
  30246. defaulted('onTabChange', noop)
  30247. ]);
  30248. var createDialog = function (spec) {
  30249. return asRaw('dialog', dialogSchema, spec);
  30250. };
  30251. var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum('type', [
  30252. 'cancel',
  30253. 'custom'
  30254. ])], dialogButtonFields));
  30255. var urlDialogSchema = objOf([
  30256. requiredString('title'),
  30257. requiredString('url'),
  30258. optionNumber('height'),
  30259. optionNumber('width'),
  30260. optionArrayOf('buttons', urlDialogButtonSchema),
  30261. defaultedFunction('onAction', noop),
  30262. defaultedFunction('onCancel', noop),
  30263. defaultedFunction('onClose', noop),
  30264. defaultedFunction('onMessage', noop)
  30265. ]);
  30266. var createUrlDialog = function (spec) {
  30267. return asRaw('dialog', urlDialogSchema, spec);
  30268. };
  30269. var getAllObjects = function (obj) {
  30270. if (isObject(obj)) {
  30271. return [obj].concat(bind$3(values(obj), getAllObjects));
  30272. } else if (isArray(obj)) {
  30273. return bind$3(obj, getAllObjects);
  30274. } else {
  30275. return [];
  30276. }
  30277. };
  30278. var isNamedItem = function (obj) {
  30279. return isString(obj.type) && isString(obj.name);
  30280. };
  30281. var dataProcessors = {
  30282. checkbox: checkboxDataProcessor,
  30283. colorinput: colorInputDataProcessor,
  30284. colorpicker: colorPickerDataProcessor,
  30285. dropzone: dropZoneDataProcessor,
  30286. input: inputDataProcessor,
  30287. iframe: iframeDataProcessor,
  30288. sizeinput: sizeInputDataProcessor,
  30289. selectbox: selectBoxDataProcessor,
  30290. listbox: listBoxDataProcessor,
  30291. size: sizeInputDataProcessor,
  30292. textarea: textAreaDataProcessor,
  30293. urlinput: urlInputDataProcessor,
  30294. customeditor: customEditorDataProcessor,
  30295. collection: collectionDataProcessor,
  30296. togglemenuitem: dialogToggleMenuItemDataProcessor
  30297. };
  30298. var getDataProcessor = function (item) {
  30299. return Optional.from(dataProcessors[item.type]);
  30300. };
  30301. var getNamedItems = function (structure) {
  30302. return filter$2(getAllObjects(structure), isNamedItem);
  30303. };
  30304. var createDataValidator = function (structure) {
  30305. var namedItems = getNamedItems(structure);
  30306. var fields = bind$3(namedItems, function (item) {
  30307. return getDataProcessor(item).fold(function () {
  30308. return [];
  30309. }, function (schema) {
  30310. return [requiredOf(item.name, schema)];
  30311. });
  30312. });
  30313. return objOf(fields);
  30314. };
  30315. var extract = function (structure) {
  30316. var internalDialog = getOrDie(createDialog(structure));
  30317. var dataValidator = createDataValidator(structure);
  30318. var initialData = structure.initialData;
  30319. return {
  30320. internalDialog: internalDialog,
  30321. dataValidator: dataValidator,
  30322. initialData: initialData
  30323. };
  30324. };
  30325. var DialogManager = {
  30326. open: function (factory, structure) {
  30327. var extraction = extract(structure);
  30328. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  30329. },
  30330. openUrl: function (factory, structure) {
  30331. var internalDialog = getOrDie(createUrlDialog(structure));
  30332. return factory(internalDialog);
  30333. },
  30334. redial: function (structure) {
  30335. return extract(structure);
  30336. }
  30337. };
  30338. var toValidValues = function (values) {
  30339. var errors = [];
  30340. var result = {};
  30341. each(values, function (value, name) {
  30342. value.fold(function () {
  30343. errors.push(name);
  30344. }, function (v) {
  30345. result[name] = v;
  30346. });
  30347. });
  30348. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  30349. };
  30350. var renderBodyPanel = function (spec, backstage) {
  30351. var memForm = record(Form.sketch(function (parts) {
  30352. return {
  30353. dom: {
  30354. tag: 'div',
  30355. classes: ['tox-form'].concat(spec.classes)
  30356. },
  30357. components: map$2(spec.items, function (item) {
  30358. return interpretInForm(parts, item, backstage);
  30359. })
  30360. };
  30361. }));
  30362. return {
  30363. dom: {
  30364. tag: 'div',
  30365. classes: ['tox-dialog__body']
  30366. },
  30367. components: [{
  30368. dom: {
  30369. tag: 'div',
  30370. classes: ['tox-dialog__body-content']
  30371. },
  30372. components: [memForm.asSpec()]
  30373. }],
  30374. behaviours: derive$1([
  30375. Keying.config({
  30376. mode: 'acyclic',
  30377. useTabstopAt: not(isPseudoStop)
  30378. }),
  30379. ComposingConfigs.memento(memForm),
  30380. RepresentingConfigs.memento(memForm, {
  30381. postprocess: function (formValue) {
  30382. return toValidValues(formValue).fold(function (err) {
  30383. console.error(err);
  30384. return {};
  30385. }, identity$1);
  30386. }
  30387. })
  30388. ])
  30389. };
  30390. };
  30391. var factory$3 = function (detail, _spec) {
  30392. return {
  30393. uid: detail.uid,
  30394. dom: detail.dom,
  30395. components: detail.components,
  30396. events: events$a(detail.action),
  30397. behaviours: augment(detail.tabButtonBehaviours, [
  30398. Focusing.config({}),
  30399. Keying.config({
  30400. mode: 'execution',
  30401. useSpace: true,
  30402. useEnter: true
  30403. }),
  30404. Representing.config({
  30405. store: {
  30406. mode: 'memory',
  30407. initialValue: detail.value
  30408. }
  30409. })
  30410. ]),
  30411. domModification: detail.domModification
  30412. };
  30413. };
  30414. var TabButton = single({
  30415. name: 'TabButton',
  30416. configFields: [
  30417. defaulted('uid', undefined),
  30418. required$1('value'),
  30419. field$1('dom', 'dom', mergeWithThunk(function () {
  30420. return {
  30421. attributes: {
  30422. 'role': 'tab',
  30423. 'id': generate$6('aria'),
  30424. 'aria-selected': 'false'
  30425. }
  30426. };
  30427. }), anyValue()),
  30428. option('action'),
  30429. defaulted('domModification', {}),
  30430. field('tabButtonBehaviours', [
  30431. Focusing,
  30432. Keying,
  30433. Representing
  30434. ]),
  30435. required$1('view')
  30436. ],
  30437. factory: factory$3
  30438. });
  30439. var schema$1 = constant$1([
  30440. required$1('tabs'),
  30441. required$1('dom'),
  30442. defaulted('clickToDismiss', false),
  30443. field('tabbarBehaviours', [
  30444. Highlighting,
  30445. Keying
  30446. ]),
  30447. markers$1([
  30448. 'tabClass',
  30449. 'selectedClass'
  30450. ])
  30451. ]);
  30452. var tabsPart = group({
  30453. factory: TabButton,
  30454. name: 'tabs',
  30455. unit: 'tab',
  30456. overrides: function (barDetail) {
  30457. var dismissTab$1 = function (tabbar, button) {
  30458. Highlighting.dehighlight(tabbar, button);
  30459. emitWith(tabbar, dismissTab(), {
  30460. tabbar: tabbar,
  30461. button: button
  30462. });
  30463. };
  30464. var changeTab$1 = function (tabbar, button) {
  30465. Highlighting.highlight(tabbar, button);
  30466. emitWith(tabbar, changeTab(), {
  30467. tabbar: tabbar,
  30468. button: button
  30469. });
  30470. };
  30471. return {
  30472. action: function (button) {
  30473. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  30474. var activeButton = Highlighting.isHighlighted(tabbar, button);
  30475. var response = function () {
  30476. if (activeButton && barDetail.clickToDismiss) {
  30477. return dismissTab$1;
  30478. } else if (!activeButton) {
  30479. return changeTab$1;
  30480. } else {
  30481. return noop;
  30482. }
  30483. }();
  30484. response(tabbar, button);
  30485. },
  30486. domModification: { classes: [barDetail.markers.tabClass] }
  30487. };
  30488. }
  30489. });
  30490. var parts$1 = constant$1([tabsPart]);
  30491. var factory$2 = function (detail, components, _spec, _externals) {
  30492. return {
  30493. 'uid': detail.uid,
  30494. 'dom': detail.dom,
  30495. components: components,
  30496. 'debug.sketcher': 'Tabbar',
  30497. 'domModification': { attributes: { role: 'tablist' } },
  30498. 'behaviours': augment(detail.tabbarBehaviours, [
  30499. Highlighting.config({
  30500. highlightClass: detail.markers.selectedClass,
  30501. itemClass: detail.markers.tabClass,
  30502. onHighlight: function (tabbar, tab) {
  30503. set$7(tab.element, 'aria-selected', 'true');
  30504. },
  30505. onDehighlight: function (tabbar, tab) {
  30506. set$7(tab.element, 'aria-selected', 'false');
  30507. }
  30508. }),
  30509. Keying.config({
  30510. mode: 'flow',
  30511. getInitial: function (tabbar) {
  30512. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  30513. return tab.element;
  30514. });
  30515. },
  30516. selector: '.' + detail.markers.tabClass,
  30517. executeOnMove: true
  30518. })
  30519. ])
  30520. };
  30521. };
  30522. var Tabbar = composite({
  30523. name: 'Tabbar',
  30524. configFields: schema$1(),
  30525. partFields: parts$1(),
  30526. factory: factory$2
  30527. });
  30528. var factory$1 = function (detail, _spec) {
  30529. return {
  30530. uid: detail.uid,
  30531. dom: detail.dom,
  30532. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  30533. domModification: { attributes: { role: 'tabpanel' } }
  30534. };
  30535. };
  30536. var Tabview = single({
  30537. name: 'Tabview',
  30538. configFields: [field('tabviewBehaviours', [Replacing])],
  30539. factory: factory$1
  30540. });
  30541. var schema = constant$1([
  30542. defaulted('selectFirst', true),
  30543. onHandler('onChangeTab'),
  30544. onHandler('onDismissTab'),
  30545. defaulted('tabs', []),
  30546. field('tabSectionBehaviours', [])
  30547. ]);
  30548. var barPart = required({
  30549. factory: Tabbar,
  30550. schema: [
  30551. required$1('dom'),
  30552. requiredObjOf('markers', [
  30553. required$1('tabClass'),
  30554. required$1('selectedClass')
  30555. ])
  30556. ],
  30557. name: 'tabbar',
  30558. defaults: function (detail) {
  30559. return { tabs: detail.tabs };
  30560. }
  30561. });
  30562. var viewPart = required({
  30563. factory: Tabview,
  30564. name: 'tabview'
  30565. });
  30566. var parts = constant$1([
  30567. barPart,
  30568. viewPart
  30569. ]);
  30570. var factory = function (detail, components, _spec, _externals) {
  30571. var changeTab$1 = function (button) {
  30572. var tabValue = Representing.getValue(button);
  30573. getPart(button, detail, 'tabview').each(function (tabview) {
  30574. var tabWithValue = find$5(detail.tabs, function (t) {
  30575. return t.value === tabValue;
  30576. });
  30577. tabWithValue.each(function (tabData) {
  30578. var panel = tabData.view();
  30579. getOpt(button.element, 'id').each(function (id) {
  30580. set$7(tabview.element, 'aria-labelledby', id);
  30581. });
  30582. Replacing.set(tabview, panel);
  30583. detail.onChangeTab(tabview, button, panel);
  30584. });
  30585. });
  30586. };
  30587. var changeTabBy = function (section, byPred) {
  30588. getPart(section, detail, 'tabbar').each(function (tabbar) {
  30589. byPred(tabbar).each(emitExecute);
  30590. });
  30591. };
  30592. return {
  30593. uid: detail.uid,
  30594. dom: detail.dom,
  30595. components: components,
  30596. behaviours: get$2(detail.tabSectionBehaviours),
  30597. events: derive$2(flatten([
  30598. detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
  30599. changeTabBy(section, Highlighting.getFirst);
  30600. })] : [],
  30601. [
  30602. run$1(changeTab(), function (section, simulatedEvent) {
  30603. var button = simulatedEvent.event.button;
  30604. changeTab$1(button);
  30605. }),
  30606. run$1(dismissTab(), function (section, simulatedEvent) {
  30607. var button = simulatedEvent.event.button;
  30608. detail.onDismissTab(section, button);
  30609. })
  30610. ]
  30611. ])),
  30612. apis: {
  30613. getViewItems: function (section) {
  30614. return getPart(section, detail, 'tabview').map(function (tabview) {
  30615. return Replacing.contents(tabview);
  30616. }).getOr([]);
  30617. },
  30618. showTab: function (section, tabKey) {
  30619. var getTabIfNotActive = function (tabbar) {
  30620. var candidates = Highlighting.getCandidates(tabbar);
  30621. var optTab = find$5(candidates, function (c) {
  30622. return Representing.getValue(c) === tabKey;
  30623. });
  30624. return optTab.filter(function (tab) {
  30625. return !Highlighting.isHighlighted(tabbar, tab);
  30626. });
  30627. };
  30628. changeTabBy(section, getTabIfNotActive);
  30629. }
  30630. }
  30631. };
  30632. };
  30633. var TabSection = composite({
  30634. name: 'TabSection',
  30635. configFields: schema(),
  30636. partFields: parts(),
  30637. factory: factory,
  30638. apis: {
  30639. getViewItems: function (apis, component) {
  30640. return apis.getViewItems(component);
  30641. },
  30642. showTab: function (apis, component, tabKey) {
  30643. apis.showTab(component, tabKey);
  30644. }
  30645. }
  30646. });
  30647. var measureHeights = function (allTabs, tabview, tabviewComp) {
  30648. return map$2(allTabs, function (_tab, i) {
  30649. Replacing.set(tabviewComp, allTabs[i].view());
  30650. var rect = tabview.dom.getBoundingClientRect();
  30651. Replacing.set(tabviewComp, []);
  30652. return rect.height;
  30653. });
  30654. };
  30655. var getMaxHeight = function (heights) {
  30656. return head(sort(heights, function (a, b) {
  30657. if (a > b) {
  30658. return -1;
  30659. } else if (a < b) {
  30660. return +1;
  30661. } else {
  30662. return 0;
  30663. }
  30664. }));
  30665. };
  30666. var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  30667. var documentElement$1 = documentElement(dialog).dom;
  30668. var rootElm = ancestor(dialog, '.tox-dialog-wrap').getOr(dialog);
  30669. var isFixed = get$a(rootElm, 'position') === 'fixed';
  30670. var maxHeight;
  30671. if (isFixed) {
  30672. maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
  30673. } else {
  30674. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  30675. }
  30676. var tabviewHeight = get$8(tabview);
  30677. var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$7(tablist);
  30678. var currentTabHeight = isTabListBeside ? Math.max(get$8(tablist), tabviewHeight) : tabviewHeight;
  30679. var dialogTopMargin = parseInt(get$a(dialog, 'margin-top'), 10) || 0;
  30680. var dialogBottomMargin = parseInt(get$a(dialog, 'margin-bottom'), 10) || 0;
  30681. var dialogHeight = get$8(dialog) + dialogTopMargin + dialogBottomMargin;
  30682. var chromeHeight = dialogHeight - currentTabHeight;
  30683. return maxHeight - chromeHeight;
  30684. };
  30685. var showTab = function (allTabs, comp) {
  30686. head(allTabs).each(function (tab) {
  30687. return TabSection.showTab(comp, tab.value);
  30688. });
  30689. };
  30690. var setTabviewHeight = function (tabview, height) {
  30691. set$6(tabview, 'height', height + 'px');
  30692. if (!detect$1().browser.isIE()) {
  30693. set$6(tabview, 'flex-basis', height + 'px');
  30694. } else {
  30695. remove$1(tabview, 'flex-basis');
  30696. }
  30697. };
  30698. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  30699. ancestor(dialogBody, '[role="dialog"]').each(function (dialog) {
  30700. descendant(dialog, '[role="tablist"]').each(function (tablist) {
  30701. maxTabHeight.get().map(function (height) {
  30702. set$6(tabview, 'height', '0');
  30703. set$6(tabview, 'flex-basis', '0');
  30704. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  30705. }).each(function (height) {
  30706. setTabviewHeight(tabview, height);
  30707. });
  30708. });
  30709. });
  30710. };
  30711. var getTabview = function (dialog) {
  30712. return descendant(dialog, '[role="tabpanel"]');
  30713. };
  30714. var setMode = function (allTabs) {
  30715. var smartTabHeight = function () {
  30716. var maxTabHeight = value$1();
  30717. var extraEvents = [
  30718. runOnAttached(function (comp) {
  30719. var dialog = comp.element;
  30720. getTabview(dialog).each(function (tabview) {
  30721. set$6(tabview, 'visibility', 'hidden');
  30722. comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) {
  30723. var heights = measureHeights(allTabs, tabview, tabviewComp);
  30724. var maxTabHeightOpt = getMaxHeight(heights);
  30725. maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
  30726. });
  30727. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30728. remove$1(tabview, 'visibility');
  30729. showTab(allTabs, comp);
  30730. global$g.requestAnimationFrame(function () {
  30731. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30732. });
  30733. });
  30734. }),
  30735. run$1(windowResize(), function (comp) {
  30736. var dialog = comp.element;
  30737. getTabview(dialog).each(function (tabview) {
  30738. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30739. });
  30740. }),
  30741. run$1(formResizeEvent, function (comp, _se) {
  30742. var dialog = comp.element;
  30743. getTabview(dialog).each(function (tabview) {
  30744. var oldFocus = active(getRootNode(tabview));
  30745. set$6(tabview, 'visibility', 'hidden');
  30746. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  30747. return parseInt(h, 10);
  30748. });
  30749. remove$1(tabview, 'height');
  30750. remove$1(tabview, 'flex-basis');
  30751. var newHeight = tabview.dom.getBoundingClientRect().height;
  30752. var hasGrown = oldHeight.forall(function (h) {
  30753. return newHeight > h;
  30754. });
  30755. if (hasGrown) {
  30756. maxTabHeight.set(newHeight);
  30757. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30758. } else {
  30759. oldHeight.each(function (h) {
  30760. setTabviewHeight(tabview, h);
  30761. });
  30762. }
  30763. remove$1(tabview, 'visibility');
  30764. oldFocus.each(focus$3);
  30765. });
  30766. })
  30767. ];
  30768. var selectFirst = false;
  30769. return {
  30770. extraEvents: extraEvents,
  30771. selectFirst: selectFirst
  30772. };
  30773. }();
  30774. var naiveTabHeight = function () {
  30775. var extraEvents = [];
  30776. var selectFirst = true;
  30777. return {
  30778. extraEvents: extraEvents,
  30779. selectFirst: selectFirst
  30780. };
  30781. }();
  30782. return {
  30783. smartTabHeight: smartTabHeight,
  30784. naiveTabHeight: naiveTabHeight
  30785. };
  30786. };
  30787. var SendDataToSectionChannel = 'send-data-to-section';
  30788. var SendDataToViewChannel = 'send-data-to-view';
  30789. var renderTabPanel = function (spec, backstage) {
  30790. var storedValue = Cell({});
  30791. var updateDataWithForm = function (form) {
  30792. var formData = Representing.getValue(form);
  30793. var validData = toValidValues(formData).getOr({});
  30794. var currentData = storedValue.get();
  30795. var newData = deepMerge(currentData, validData);
  30796. storedValue.set(newData);
  30797. };
  30798. var setDataOnForm = function (form) {
  30799. var tabData = storedValue.get();
  30800. Representing.setValue(form, tabData);
  30801. };
  30802. var oldTab = Cell(null);
  30803. var allTabs = map$2(spec.tabs, function (tab) {
  30804. return {
  30805. value: tab.name,
  30806. dom: {
  30807. tag: 'div',
  30808. classes: ['tox-dialog__body-nav-item'],
  30809. innerHtml: backstage.shared.providers.translate(tab.title)
  30810. },
  30811. view: function () {
  30812. return [Form.sketch(function (parts) {
  30813. return {
  30814. dom: {
  30815. tag: 'div',
  30816. classes: ['tox-form']
  30817. },
  30818. components: map$2(tab.items, function (item) {
  30819. return interpretInForm(parts, item, backstage);
  30820. }),
  30821. formBehaviours: derive$1([
  30822. Keying.config({
  30823. mode: 'acyclic',
  30824. useTabstopAt: not(isPseudoStop)
  30825. }),
  30826. config('TabView.form.events', [
  30827. runOnAttached(setDataOnForm),
  30828. runOnDetached(updateDataWithForm)
  30829. ]),
  30830. Receiving.config({
  30831. channels: wrapAll([
  30832. {
  30833. key: SendDataToSectionChannel,
  30834. value: { onReceive: updateDataWithForm }
  30835. },
  30836. {
  30837. key: SendDataToViewChannel,
  30838. value: { onReceive: setDataOnForm }
  30839. }
  30840. ])
  30841. })
  30842. ])
  30843. };
  30844. })];
  30845. }
  30846. };
  30847. });
  30848. var tabMode = setMode(allTabs).smartTabHeight;
  30849. return TabSection.sketch({
  30850. dom: {
  30851. tag: 'div',
  30852. classes: ['tox-dialog__body']
  30853. },
  30854. onChangeTab: function (section, button, _viewItems) {
  30855. var name = Representing.getValue(button);
  30856. emitWith(section, formTabChangeEvent, {
  30857. name: name,
  30858. oldName: oldTab.get()
  30859. });
  30860. oldTab.set(name);
  30861. },
  30862. tabs: allTabs,
  30863. components: [
  30864. TabSection.parts.tabbar({
  30865. dom: {
  30866. tag: 'div',
  30867. classes: ['tox-dialog__body-nav']
  30868. },
  30869. components: [Tabbar.parts.tabs({})],
  30870. markers: {
  30871. tabClass: 'tox-tab',
  30872. selectedClass: 'tox-dialog__body-nav-item--active'
  30873. },
  30874. tabbarBehaviours: derive$1([Tabstopping.config({})])
  30875. }),
  30876. TabSection.parts.tabview({
  30877. dom: {
  30878. tag: 'div',
  30879. classes: ['tox-dialog__body-content']
  30880. }
  30881. })
  30882. ],
  30883. selectFirst: tabMode.selectFirst,
  30884. tabSectionBehaviours: derive$1([
  30885. config('tabpanel', tabMode.extraEvents),
  30886. Keying.config({ mode: 'acyclic' }),
  30887. Composing.config({
  30888. find: function (comp) {
  30889. return head(TabSection.getViewItems(comp));
  30890. }
  30891. }),
  30892. Representing.config({
  30893. store: {
  30894. mode: 'manual',
  30895. getValue: function (tsection) {
  30896. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  30897. return storedValue.get();
  30898. },
  30899. setValue: function (tsection, value) {
  30900. storedValue.set(value);
  30901. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  30902. }
  30903. }
  30904. })
  30905. ])
  30906. });
  30907. };
  30908. var dialogChannel = generate$6('update-dialog');
  30909. var titleChannel = generate$6('update-title');
  30910. var bodyChannel = generate$6('update-body');
  30911. var footerChannel = generate$6('update-footer');
  30912. var bodySendMessageChannel = generate$6('body-send-message');
  30913. var renderBody = function (spec, id, backstage, ariaAttrs) {
  30914. var renderComponents = function (incoming) {
  30915. switch (incoming.body.type) {
  30916. case 'tabpanel': {
  30917. return [renderTabPanel(incoming.body, backstage)];
  30918. }
  30919. default: {
  30920. return [renderBodyPanel(incoming.body, backstage)];
  30921. }
  30922. }
  30923. };
  30924. var updateState = function (_comp, incoming) {
  30925. return Optional.some({
  30926. isTabPanel: function () {
  30927. return incoming.body.type === 'tabpanel';
  30928. }
  30929. });
  30930. };
  30931. var ariaAttributes = { 'aria-live': 'polite' };
  30932. return {
  30933. dom: {
  30934. tag: 'div',
  30935. classes: ['tox-dialog__content-js'],
  30936. attributes: __assign(__assign({}, id.map(function (x) {
  30937. return { id: x };
  30938. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  30939. },
  30940. components: [],
  30941. behaviours: derive$1([
  30942. ComposingConfigs.childAt(0),
  30943. Reflecting.config({
  30944. channel: bodyChannel,
  30945. updateState: updateState,
  30946. renderComponents: renderComponents,
  30947. initialData: spec
  30948. })
  30949. ])
  30950. };
  30951. };
  30952. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  30953. return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
  30954. };
  30955. var renderModalBody = function (spec, backstage) {
  30956. var bodySpec = renderBody(spec, Optional.none(), backstage, false);
  30957. return ModalDialog.parts.body(bodySpec);
  30958. };
  30959. var renderIframeBody = function (spec) {
  30960. var bodySpec = {
  30961. dom: {
  30962. tag: 'div',
  30963. classes: ['tox-dialog__content-js']
  30964. },
  30965. components: [{
  30966. dom: {
  30967. tag: 'div',
  30968. classes: ['tox-dialog__body-iframe']
  30969. },
  30970. components: [craft({
  30971. dom: {
  30972. tag: 'iframe',
  30973. attributes: { src: spec.url }
  30974. },
  30975. behaviours: derive$1([
  30976. Tabstopping.config({}),
  30977. Focusing.config({})
  30978. ])
  30979. })]
  30980. }],
  30981. behaviours: derive$1([Keying.config({
  30982. mode: 'acyclic',
  30983. useTabstopAt: not(isPseudoStop)
  30984. })])
  30985. };
  30986. return ModalDialog.parts.body(bodySpec);
  30987. };
  30988. var isTouch = global$a.deviceType.isTouch();
  30989. var hiddenHeader = function (title, close) {
  30990. return {
  30991. dom: {
  30992. tag: 'div',
  30993. styles: { display: 'none' },
  30994. classes: ['tox-dialog__header']
  30995. },
  30996. components: [
  30997. title,
  30998. close
  30999. ]
  31000. };
  31001. };
  31002. var pClose = function (onClose, providersBackstage) {
  31003. return ModalDialog.parts.close(Button.sketch({
  31004. dom: {
  31005. tag: 'button',
  31006. classes: [
  31007. 'tox-button',
  31008. 'tox-button--icon',
  31009. 'tox-button--naked'
  31010. ],
  31011. attributes: {
  31012. 'type': 'button',
  31013. 'aria-label': providersBackstage.translate('Close')
  31014. }
  31015. },
  31016. action: onClose,
  31017. buttonBehaviours: derive$1([Tabstopping.config({})])
  31018. }));
  31019. };
  31020. var pUntitled = function () {
  31021. return ModalDialog.parts.title({
  31022. dom: {
  31023. tag: 'div',
  31024. classes: ['tox-dialog__title'],
  31025. innerHtml: '',
  31026. styles: { display: 'none' }
  31027. }
  31028. });
  31029. };
  31030. var pBodyMessage = function (message, providersBackstage) {
  31031. return ModalDialog.parts.body({
  31032. dom: {
  31033. tag: 'div',
  31034. classes: ['tox-dialog__body']
  31035. },
  31036. components: [{
  31037. dom: {
  31038. tag: 'div',
  31039. classes: ['tox-dialog__body-content']
  31040. },
  31041. components: [{ dom: fromHtml('<p>' + providersBackstage.translate(message) + '</p>') }]
  31042. }]
  31043. });
  31044. };
  31045. var pFooter = function (buttons) {
  31046. return ModalDialog.parts.footer({
  31047. dom: {
  31048. tag: 'div',
  31049. classes: ['tox-dialog__footer']
  31050. },
  31051. components: buttons
  31052. });
  31053. };
  31054. var pFooterGroup = function (startButtons, endButtons) {
  31055. return [
  31056. Container.sketch({
  31057. dom: {
  31058. tag: 'div',
  31059. classes: ['tox-dialog__footer-start']
  31060. },
  31061. components: startButtons
  31062. }),
  31063. Container.sketch({
  31064. dom: {
  31065. tag: 'div',
  31066. classes: ['tox-dialog__footer-end']
  31067. },
  31068. components: endButtons
  31069. })
  31070. ];
  31071. };
  31072. var renderDialog$1 = function (spec) {
  31073. var _a;
  31074. var dialogClass = 'tox-dialog';
  31075. var blockerClass = dialogClass + '-wrap';
  31076. var blockerBackdropClass = blockerClass + '__backdrop';
  31077. var scrollLockClass = dialogClass + '__disable-scroll';
  31078. return ModalDialog.sketch({
  31079. lazySink: spec.lazySink,
  31080. onEscape: function (comp) {
  31081. spec.onEscape(comp);
  31082. return Optional.some(true);
  31083. },
  31084. useTabstopAt: function (elem) {
  31085. return !isPseudoStop(elem);
  31086. },
  31087. dom: {
  31088. tag: 'div',
  31089. classes: [dialogClass].concat(spec.extraClasses),
  31090. styles: __assign({ position: 'relative' }, spec.extraStyles)
  31091. },
  31092. components: __spreadArray([
  31093. spec.header,
  31094. spec.body
  31095. ], spec.footer.toArray()),
  31096. parts: {
  31097. blocker: {
  31098. dom: fromHtml('<div class="' + blockerClass + '"></div>'),
  31099. components: [{
  31100. dom: {
  31101. tag: 'div',
  31102. classes: isTouch ? [
  31103. blockerBackdropClass,
  31104. blockerBackdropClass + '--opaque'
  31105. ] : [blockerBackdropClass]
  31106. }
  31107. }]
  31108. }
  31109. },
  31110. dragBlockClass: blockerClass,
  31111. modalBehaviours: derive$1(__spreadArray([
  31112. Focusing.config({}),
  31113. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  31114. Keying.focusIn(comp);
  31115. })])),
  31116. config('scroll-lock', [
  31117. runOnAttached(function () {
  31118. add$2(body(), scrollLockClass);
  31119. }),
  31120. runOnDetached(function () {
  31121. remove$3(body(), scrollLockClass);
  31122. })
  31123. ])
  31124. ], spec.extraBehaviours)),
  31125. eventOrder: __assign((_a = {}, _a[execute$5()] = ['dialog-events'], _a[attachedToDom()] = [
  31126. 'scroll-lock',
  31127. 'dialog-events',
  31128. 'alloy.base.behaviour'
  31129. ], _a[detachedFromDom()] = [
  31130. 'alloy.base.behaviour',
  31131. 'dialog-events',
  31132. 'scroll-lock'
  31133. ], _a), spec.eventOrder)
  31134. });
  31135. };
  31136. var renderClose = function (providersBackstage) {
  31137. return Button.sketch({
  31138. dom: {
  31139. tag: 'button',
  31140. classes: [
  31141. 'tox-button',
  31142. 'tox-button--icon',
  31143. 'tox-button--naked'
  31144. ],
  31145. attributes: {
  31146. 'type': 'button',
  31147. 'aria-label': providersBackstage.translate('Close'),
  31148. 'title': providersBackstage.translate('Close')
  31149. }
  31150. },
  31151. components: [render$3('close', {
  31152. tag: 'div',
  31153. classes: ['tox-icon']
  31154. }, providersBackstage.icons)],
  31155. action: function (comp) {
  31156. emit(comp, formCancelEvent);
  31157. }
  31158. });
  31159. };
  31160. var renderTitle = function (spec, id, providersBackstage) {
  31161. var renderComponents = function (data) {
  31162. return [text(providersBackstage.translate(data.title))];
  31163. };
  31164. return {
  31165. dom: {
  31166. tag: 'div',
  31167. classes: ['tox-dialog__title'],
  31168. attributes: __assign({}, id.map(function (x) {
  31169. return { id: x };
  31170. }).getOr({}))
  31171. },
  31172. components: renderComponents(spec),
  31173. behaviours: derive$1([Reflecting.config({
  31174. channel: titleChannel,
  31175. renderComponents: renderComponents
  31176. })])
  31177. };
  31178. };
  31179. var renderDragHandle = function () {
  31180. return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') };
  31181. };
  31182. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  31183. return Container.sketch({
  31184. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  31185. components: [
  31186. renderTitle(spec, Optional.some(titleId), providersBackstage),
  31187. renderDragHandle(),
  31188. renderClose(providersBackstage)
  31189. ],
  31190. containerBehaviours: derive$1([Dragging.config({
  31191. mode: 'mouse',
  31192. blockerClass: 'blocker',
  31193. getTarget: function (handle) {
  31194. return closest$1(handle, '[role="dialog"]').getOrDie();
  31195. },
  31196. snaps: {
  31197. getSnapPoints: function () {
  31198. return [];
  31199. },
  31200. leftAttr: 'data-drag-left',
  31201. topAttr: 'data-drag-top'
  31202. }
  31203. })])
  31204. });
  31205. };
  31206. var renderModalHeader = function (spec, providersBackstage) {
  31207. var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
  31208. var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
  31209. var pClose = ModalDialog.parts.close(renderClose(providersBackstage));
  31210. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  31211. return Container.sketch({
  31212. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  31213. components: components
  31214. });
  31215. };
  31216. var getHeader = function (title, backstage) {
  31217. return renderModalHeader({
  31218. title: backstage.shared.providers.translate(title),
  31219. draggable: backstage.dialog.isDraggableModal()
  31220. }, backstage.shared.providers);
  31221. };
  31222. var getBusySpec = function (message, bs, providers) {
  31223. return {
  31224. dom: {
  31225. tag: 'div',
  31226. classes: ['tox-dialog__busy-spinner'],
  31227. attributes: { 'aria-label': providers.translate(message) },
  31228. styles: {
  31229. left: '0px',
  31230. right: '0px',
  31231. bottom: '0px',
  31232. top: '0px',
  31233. position: 'absolute'
  31234. }
  31235. },
  31236. behaviours: bs,
  31237. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  31238. };
  31239. };
  31240. var getEventExtras = function (lazyDialog, providers, extra) {
  31241. return {
  31242. onClose: function () {
  31243. return extra.closeWindow();
  31244. },
  31245. onBlock: function (blockEvent) {
  31246. ModalDialog.setBusy(lazyDialog(), function (_comp, bs) {
  31247. return getBusySpec(blockEvent.message, bs, providers);
  31248. });
  31249. },
  31250. onUnblock: function () {
  31251. ModalDialog.setIdle(lazyDialog());
  31252. }
  31253. };
  31254. };
  31255. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  31256. var _a;
  31257. var updateState = function (_comp, incoming) {
  31258. return Optional.some(incoming);
  31259. };
  31260. return build$1(renderDialog$1(__assign(__assign({}, spec), {
  31261. lazySink: backstage.shared.getSink,
  31262. extraBehaviours: __spreadArray([
  31263. Reflecting.config({
  31264. channel: dialogChannel,
  31265. updateState: updateState,
  31266. initialData: initialData
  31267. }),
  31268. RepresentingConfigs.memory({})
  31269. ], spec.extraBehaviours),
  31270. onEscape: function (comp) {
  31271. emit(comp, formCancelEvent);
  31272. },
  31273. dialogEvents: dialogEvents,
  31274. eventOrder: (_a = {}, _a[receive()] = [
  31275. Reflecting.name(),
  31276. Receiving.name()
  31277. ], _a[attachedToDom()] = [
  31278. 'scroll-lock',
  31279. Reflecting.name(),
  31280. 'messages',
  31281. 'dialog-events',
  31282. 'alloy.base.behaviour'
  31283. ], _a[detachedFromDom()] = [
  31284. 'alloy.base.behaviour',
  31285. 'dialog-events',
  31286. 'messages',
  31287. Reflecting.name(),
  31288. 'scroll-lock'
  31289. ], _a)
  31290. })));
  31291. };
  31292. var mapMenuButtons = function (buttons) {
  31293. var mapItems = function (button) {
  31294. var items = map$2(button.items, function (item) {
  31295. var cell = Cell(false);
  31296. return __assign(__assign({}, item), { storage: cell });
  31297. });
  31298. return __assign(__assign({}, button), { items: items });
  31299. };
  31300. return map$2(buttons, function (button) {
  31301. if (button.type === 'menu') {
  31302. return mapItems(button);
  31303. }
  31304. return button;
  31305. });
  31306. };
  31307. var extractCellsToObject = function (buttons) {
  31308. return foldl(buttons, function (acc, button) {
  31309. if (button.type === 'menu') {
  31310. var menuButton = button;
  31311. return foldl(menuButton.items, function (innerAcc, item) {
  31312. innerAcc[item.name] = item.storage;
  31313. return innerAcc;
  31314. }, acc);
  31315. }
  31316. return acc;
  31317. }, {});
  31318. };
  31319. var initCommonEvents = function (fireApiEvent, extras) {
  31320. return [
  31321. runWithTarget(focusin(), onFocus),
  31322. fireApiEvent(formCloseEvent, function (_api, spec) {
  31323. extras.onClose();
  31324. spec.onClose();
  31325. }),
  31326. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  31327. spec.onCancel(api);
  31328. emit(self, formCloseEvent);
  31329. }),
  31330. run$1(formUnblockEvent, function (_c, _se) {
  31331. return extras.onUnblock();
  31332. }),
  31333. run$1(formBlockEvent, function (_c, se) {
  31334. return extras.onBlock(se.event);
  31335. })
  31336. ];
  31337. };
  31338. var initUrlDialog = function (getInstanceApi, extras) {
  31339. var fireApiEvent = function (eventName, f) {
  31340. return run$1(eventName, function (c, se) {
  31341. withSpec(c, function (spec, _c) {
  31342. f(getInstanceApi(), spec, se.event, c);
  31343. });
  31344. });
  31345. };
  31346. var withSpec = function (c, f) {
  31347. Reflecting.getState(c).get().each(function (currentDialog) {
  31348. f(currentDialog, c);
  31349. });
  31350. };
  31351. return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras)), [fireApiEvent(formActionEvent, function (api, spec, event) {
  31352. spec.onAction(api, { name: event.name });
  31353. })]);
  31354. };
  31355. var initDialog = function (getInstanceApi, extras, getSink) {
  31356. var fireApiEvent = function (eventName, f) {
  31357. return run$1(eventName, function (c, se) {
  31358. withSpec(c, function (spec, _c) {
  31359. f(getInstanceApi(), spec, se.event, c);
  31360. });
  31361. });
  31362. };
  31363. var withSpec = function (c, f) {
  31364. Reflecting.getState(c).get().each(function (currentDialogInit) {
  31365. f(currentDialogInit.internalDialog, c);
  31366. });
  31367. };
  31368. return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras)), [
  31369. fireApiEvent(formSubmitEvent, function (api, spec) {
  31370. return spec.onSubmit(api);
  31371. }),
  31372. fireApiEvent(formChangeEvent, function (api, spec, event) {
  31373. spec.onChange(api, { name: event.name });
  31374. }),
  31375. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  31376. var focusIn = function () {
  31377. return Keying.focusIn(component);
  31378. };
  31379. var isDisabled = function (focused) {
  31380. return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
  31381. return val === 'true';
  31382. });
  31383. };
  31384. var rootNode = getRootNode(component.element);
  31385. var current = active(rootNode);
  31386. spec.onAction(api, {
  31387. name: event.name,
  31388. value: event.value
  31389. });
  31390. active(rootNode).fold(focusIn, function (focused) {
  31391. if (isDisabled(focused)) {
  31392. focusIn();
  31393. } else if (current.exists(function (cur) {
  31394. return contains(focused, cur) && isDisabled(cur);
  31395. })) {
  31396. focusIn();
  31397. } else {
  31398. getSink().toOptional().filter(function (sink) {
  31399. return !contains(sink.element, focused);
  31400. }).each(focusIn);
  31401. }
  31402. });
  31403. }),
  31404. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  31405. spec.onTabChange(api, {
  31406. newTabName: event.name,
  31407. oldTabName: event.oldName
  31408. });
  31409. }),
  31410. runOnDetached(function (component) {
  31411. var api = getInstanceApi();
  31412. Representing.setValue(component, api.getData());
  31413. })
  31414. ]);
  31415. };
  31416. var SilverDialogEvents = {
  31417. initUrlDialog: initUrlDialog,
  31418. initDialog: initDialog
  31419. };
  31420. var makeButton = function (button, backstage) {
  31421. return renderFooterButton(button, button.type, backstage);
  31422. };
  31423. var lookup = function (compInSystem, footerButtons, buttonName) {
  31424. return find$5(footerButtons, function (button) {
  31425. return button.name === buttonName;
  31426. }).bind(function (memButton) {
  31427. return memButton.memento.getOpt(compInSystem);
  31428. });
  31429. };
  31430. var renderComponents = function (_data, state) {
  31431. var footerButtons = state.map(function (s) {
  31432. return s.footerButtons;
  31433. }).getOr([]);
  31434. var buttonGroups = partition$3(footerButtons, function (button) {
  31435. return button.align === 'start';
  31436. });
  31437. var makeGroup = function (edge, buttons) {
  31438. return Container.sketch({
  31439. dom: {
  31440. tag: 'div',
  31441. classes: ['tox-dialog__footer-' + edge]
  31442. },
  31443. components: map$2(buttons, function (button) {
  31444. return button.memento.asSpec();
  31445. })
  31446. });
  31447. };
  31448. var startButtons = makeGroup('start', buttonGroups.pass);
  31449. var endButtons = makeGroup('end', buttonGroups.fail);
  31450. return [
  31451. startButtons,
  31452. endButtons
  31453. ];
  31454. };
  31455. var renderFooter = function (initSpec, backstage) {
  31456. var updateState = function (_comp, data) {
  31457. var footerButtons = map$2(data.buttons, function (button) {
  31458. var memButton = record(makeButton(button, backstage));
  31459. return {
  31460. name: button.name,
  31461. align: button.align,
  31462. memento: memButton
  31463. };
  31464. });
  31465. var lookupByName = function (compInSystem, buttonName) {
  31466. return lookup(compInSystem, footerButtons, buttonName);
  31467. };
  31468. return Optional.some({
  31469. lookupByName: lookupByName,
  31470. footerButtons: footerButtons
  31471. });
  31472. };
  31473. return {
  31474. dom: fromHtml('<div class="tox-dialog__footer"></div>'),
  31475. components: [],
  31476. behaviours: derive$1([Reflecting.config({
  31477. channel: footerChannel,
  31478. initialData: initSpec,
  31479. updateState: updateState,
  31480. renderComponents: renderComponents
  31481. })])
  31482. };
  31483. };
  31484. var renderInlineFooter = function (initSpec, backstage) {
  31485. return renderFooter(initSpec, backstage);
  31486. };
  31487. var renderModalFooter = function (initSpec, backstage) {
  31488. return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
  31489. };
  31490. var getCompByName = function (access, name) {
  31491. var root = access.getRoot();
  31492. if (root.getSystem().isConnected()) {
  31493. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  31494. return Form.getField(form_1, name).fold(function () {
  31495. var footer = access.getFooter();
  31496. var footerState = Reflecting.getState(footer);
  31497. return footerState.get().bind(function (f) {
  31498. return f.lookupByName(form_1, name);
  31499. });
  31500. }, function (comp) {
  31501. return Optional.some(comp);
  31502. });
  31503. } else {
  31504. return Optional.none();
  31505. }
  31506. };
  31507. var validateData$1 = function (access, data) {
  31508. var root = access.getRoot();
  31509. return Reflecting.getState(root).get().map(function (dialogState) {
  31510. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  31511. }).getOr(data);
  31512. };
  31513. var getDialogApi = function (access, doRedial, menuItemStates) {
  31514. var withRoot = function (f) {
  31515. var root = access.getRoot();
  31516. if (root.getSystem().isConnected()) {
  31517. f(root);
  31518. }
  31519. };
  31520. var getData = function () {
  31521. var root = access.getRoot();
  31522. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  31523. var representedValues = Representing.getValue(valueComp);
  31524. var menuItemCurrentState = map(menuItemStates, function (cell) {
  31525. return cell.get();
  31526. });
  31527. return __assign(__assign({}, representedValues), menuItemCurrentState);
  31528. };
  31529. var setData = function (newData) {
  31530. withRoot(function (_) {
  31531. var prevData = instanceApi.getData();
  31532. var mergedData = __assign(__assign({}, prevData), newData);
  31533. var newInternalData = validateData$1(access, mergedData);
  31534. var form = access.getFormWrapper();
  31535. Representing.setValue(form, newInternalData);
  31536. each(menuItemStates, function (v, k) {
  31537. if (has$2(mergedData, k)) {
  31538. v.set(mergedData[k]);
  31539. }
  31540. });
  31541. });
  31542. };
  31543. var disable = function (name) {
  31544. getCompByName(access, name).each(Disabling.disable);
  31545. };
  31546. var enable = function (name) {
  31547. getCompByName(access, name).each(Disabling.enable);
  31548. };
  31549. var focus = function (name) {
  31550. getCompByName(access, name).each(Focusing.focus);
  31551. };
  31552. var block = function (message) {
  31553. if (!isString(message)) {
  31554. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  31555. }
  31556. withRoot(function (root) {
  31557. emitWith(root, formBlockEvent, { message: message });
  31558. });
  31559. };
  31560. var unblock = function () {
  31561. withRoot(function (root) {
  31562. emit(root, formUnblockEvent);
  31563. });
  31564. };
  31565. var showTab = function (name) {
  31566. withRoot(function (_) {
  31567. var body = access.getBody();
  31568. var bodyState = Reflecting.getState(body);
  31569. if (bodyState.get().exists(function (b) {
  31570. return b.isTabPanel();
  31571. })) {
  31572. Composing.getCurrent(body).each(function (tabSection) {
  31573. TabSection.showTab(tabSection, name);
  31574. });
  31575. }
  31576. });
  31577. };
  31578. var redial = function (d) {
  31579. withRoot(function (root) {
  31580. var dialogInit = doRedial(d);
  31581. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  31582. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  31583. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  31584. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  31585. instanceApi.setData(dialogInit.initialData);
  31586. });
  31587. };
  31588. var close = function () {
  31589. withRoot(function (root) {
  31590. emit(root, formCloseEvent);
  31591. });
  31592. };
  31593. var instanceApi = {
  31594. getData: getData,
  31595. setData: setData,
  31596. disable: disable,
  31597. enable: enable,
  31598. focus: focus,
  31599. block: block,
  31600. unblock: unblock,
  31601. showTab: showTab,
  31602. redial: redial,
  31603. close: close
  31604. };
  31605. return instanceApi;
  31606. };
  31607. var getDialogSizeClasses = function (size) {
  31608. switch (size) {
  31609. case 'large':
  31610. return ['tox-dialog--width-lg'];
  31611. case 'medium':
  31612. return ['tox-dialog--width-md'];
  31613. default:
  31614. return [];
  31615. }
  31616. };
  31617. var renderDialog = function (dialogInit, extra, backstage) {
  31618. var header = getHeader(dialogInit.internalDialog.title, backstage);
  31619. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  31620. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  31621. var objOfCells = extractCellsToObject(storagedMenuButtons);
  31622. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  31623. var dialogEvents = SilverDialogEvents.initDialog(function () {
  31624. return instanceApi;
  31625. }, getEventExtras(function () {
  31626. return dialog;
  31627. }, backstage.shared.providers, extra), backstage.shared.getSink);
  31628. var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
  31629. var spec = {
  31630. header: header,
  31631. body: body,
  31632. footer: Optional.some(footer),
  31633. extraClasses: dialogSize,
  31634. extraBehaviours: [],
  31635. extraStyles: {}
  31636. };
  31637. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  31638. var modalAccess = function () {
  31639. var getForm = function () {
  31640. var outerForm = ModalDialog.getBody(dialog);
  31641. return Composing.getCurrent(outerForm).getOr(outerForm);
  31642. };
  31643. return {
  31644. getRoot: constant$1(dialog),
  31645. getBody: function () {
  31646. return ModalDialog.getBody(dialog);
  31647. },
  31648. getFooter: function () {
  31649. return ModalDialog.getFooter(dialog);
  31650. },
  31651. getFormWrapper: getForm
  31652. };
  31653. }();
  31654. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  31655. return {
  31656. dialog: dialog,
  31657. instanceApi: instanceApi
  31658. };
  31659. };
  31660. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  31661. var _a, _b;
  31662. var dialogLabelId = generate$6('dialog-label');
  31663. var dialogContentId = generate$6('dialog-content');
  31664. var updateState = function (_comp, incoming) {
  31665. return Optional.some(incoming);
  31666. };
  31667. var memHeader = record(renderInlineHeader({
  31668. title: dialogInit.internalDialog.title,
  31669. draggable: true
  31670. }, dialogLabelId, backstage.shared.providers));
  31671. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  31672. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  31673. var objOfCells = extractCellsToObject(storagedMenuButtons);
  31674. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  31675. var dialogEvents = SilverDialogEvents.initDialog(function () {
  31676. return instanceApi;
  31677. }, {
  31678. onBlock: function (event) {
  31679. Blocking.block(dialog, function (_comp, bs) {
  31680. return getBusySpec(event.message, bs, backstage.shared.providers);
  31681. });
  31682. },
  31683. onUnblock: function () {
  31684. Blocking.unblock(dialog);
  31685. },
  31686. onClose: function () {
  31687. return extra.closeWindow();
  31688. }
  31689. }, backstage.shared.getSink);
  31690. var dialog = build$1({
  31691. dom: {
  31692. tag: 'div',
  31693. classes: [
  31694. 'tox-dialog',
  31695. 'tox-dialog-inline'
  31696. ],
  31697. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = dialogContentId, _a)
  31698. },
  31699. eventOrder: (_b = {}, _b[receive()] = [
  31700. Reflecting.name(),
  31701. Receiving.name()
  31702. ], _b[execute$5()] = ['execute-on-form'], _b[attachedToDom()] = [
  31703. 'reflecting',
  31704. 'execute-on-form'
  31705. ], _b),
  31706. behaviours: derive$1([
  31707. Keying.config({
  31708. mode: 'cyclic',
  31709. onEscape: function (c) {
  31710. emit(c, formCloseEvent);
  31711. return Optional.some(true);
  31712. },
  31713. useTabstopAt: function (elem) {
  31714. return !isPseudoStop(elem) && (name$2(elem) !== 'button' || get$c(elem, 'disabled') !== 'disabled');
  31715. }
  31716. }),
  31717. Reflecting.config({
  31718. channel: dialogChannel,
  31719. updateState: updateState,
  31720. initialData: dialogInit
  31721. }),
  31722. Focusing.config({}),
  31723. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  31724. Keying.focusIn(comp);
  31725. })])),
  31726. Blocking.config({
  31727. getRoot: function () {
  31728. return Optional.some(dialog);
  31729. }
  31730. }),
  31731. Replacing.config({}),
  31732. RepresentingConfigs.memory({})
  31733. ]),
  31734. components: [
  31735. memHeader.asSpec(),
  31736. memBody.asSpec(),
  31737. memFooter.asSpec()
  31738. ]
  31739. });
  31740. var instanceApi = getDialogApi({
  31741. getRoot: constant$1(dialog),
  31742. getFooter: function () {
  31743. return memFooter.get(dialog);
  31744. },
  31745. getBody: function () {
  31746. return memBody.get(dialog);
  31747. },
  31748. getFormWrapper: function () {
  31749. var body = memBody.get(dialog);
  31750. return Composing.getCurrent(body).getOr(body);
  31751. }
  31752. }, extra.redial, objOfCells);
  31753. return {
  31754. dialog: dialog,
  31755. instanceApi: instanceApi
  31756. };
  31757. };
  31758. var global$1 = tinymce.util.Tools.resolve('tinymce.util.URI');
  31759. var getUrlDialogApi = function (root) {
  31760. var withRoot = function (f) {
  31761. if (root.getSystem().isConnected()) {
  31762. f(root);
  31763. }
  31764. };
  31765. var block = function (message) {
  31766. if (!isString(message)) {
  31767. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  31768. }
  31769. withRoot(function (root) {
  31770. emitWith(root, formBlockEvent, { message: message });
  31771. });
  31772. };
  31773. var unblock = function () {
  31774. withRoot(function (root) {
  31775. emit(root, formUnblockEvent);
  31776. });
  31777. };
  31778. var close = function () {
  31779. withRoot(function (root) {
  31780. emit(root, formCloseEvent);
  31781. });
  31782. };
  31783. var sendMessage = function (data) {
  31784. withRoot(function (root) {
  31785. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  31786. });
  31787. };
  31788. return {
  31789. block: block,
  31790. unblock: unblock,
  31791. close: close,
  31792. sendMessage: sendMessage
  31793. };
  31794. };
  31795. var SUPPORTED_MESSAGE_ACTIONS = [
  31796. 'insertContent',
  31797. 'setContent',
  31798. 'execCommand',
  31799. 'close',
  31800. 'block',
  31801. 'unblock'
  31802. ];
  31803. var isSupportedMessage = function (data) {
  31804. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  31805. };
  31806. var isCustomMessage = function (data) {
  31807. return !isSupportedMessage(data) && isObject(data) && has$2(data, 'mceAction');
  31808. };
  31809. var handleMessage = function (editor, api, data) {
  31810. switch (data.mceAction) {
  31811. case 'insertContent':
  31812. editor.insertContent(data.content);
  31813. break;
  31814. case 'setContent':
  31815. editor.setContent(data.content);
  31816. break;
  31817. case 'execCommand':
  31818. var ui = isBoolean(data.ui) ? data.ui : false;
  31819. editor.execCommand(data.cmd, ui, data.value);
  31820. break;
  31821. case 'close':
  31822. api.close();
  31823. break;
  31824. case 'block':
  31825. api.block(data.message);
  31826. break;
  31827. case 'unblock':
  31828. api.unblock();
  31829. break;
  31830. }
  31831. };
  31832. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  31833. var _a;
  31834. var header = getHeader(internalDialog.title, backstage);
  31835. var body = renderIframeBody(internalDialog);
  31836. var footer = internalDialog.buttons.bind(function (buttons) {
  31837. if (buttons.length === 0) {
  31838. return Optional.none();
  31839. } else {
  31840. return Optional.some(renderModalFooter({ buttons: buttons }, backstage));
  31841. }
  31842. });
  31843. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  31844. return instanceApi;
  31845. }, getEventExtras(function () {
  31846. return dialog;
  31847. }, backstage.shared.providers, extra));
  31848. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  31849. return {};
  31850. }, function (height) {
  31851. return {
  31852. 'height': height + 'px',
  31853. 'max-height': height + 'px'
  31854. };
  31855. })), internalDialog.width.fold(function () {
  31856. return {};
  31857. }, function (width) {
  31858. return {
  31859. 'width': width + 'px',
  31860. 'max-width': width + 'px'
  31861. };
  31862. }));
  31863. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  31864. var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) });
  31865. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  31866. var messageHandlerUnbinder = unbindable();
  31867. var extraBehaviours = [
  31868. config('messages', [
  31869. runOnAttached(function () {
  31870. var unbind = bind(SugarElement.fromDom(window), 'message', function (e) {
  31871. if (iframeUri.isSameOrigin(new global$1(e.raw.origin))) {
  31872. var data = e.raw.data;
  31873. if (isSupportedMessage(data)) {
  31874. handleMessage(editor, instanceApi, data);
  31875. } else if (isCustomMessage(data)) {
  31876. internalDialog.onMessage(instanceApi, data);
  31877. }
  31878. }
  31879. });
  31880. messageHandlerUnbinder.set(unbind);
  31881. }),
  31882. runOnDetached(messageHandlerUnbinder.clear)
  31883. ]),
  31884. Receiving.config({
  31885. channels: (_a = {}, _a[bodySendMessageChannel] = {
  31886. onReceive: function (comp, data) {
  31887. descendant(comp.element, 'iframe').each(function (iframeEle) {
  31888. var iframeWin = iframeEle.dom.contentWindow;
  31889. iframeWin.postMessage(data, iframeDomain);
  31890. });
  31891. }
  31892. }, _a)
  31893. })
  31894. ];
  31895. var spec = {
  31896. header: header,
  31897. body: body,
  31898. footer: footer,
  31899. extraClasses: classes,
  31900. extraBehaviours: extraBehaviours,
  31901. extraStyles: styles
  31902. };
  31903. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  31904. var instanceApi = getUrlDialogApi(dialog);
  31905. return {
  31906. dialog: dialog,
  31907. instanceApi: instanceApi
  31908. };
  31909. };
  31910. var setup$2 = function (extras) {
  31911. var sharedBackstage = extras.backstage.shared;
  31912. var open = function (message, callback) {
  31913. var closeDialog = function () {
  31914. ModalDialog.hide(alertDialog);
  31915. callback();
  31916. };
  31917. var memFooterClose = record(renderFooterButton({
  31918. name: 'close-alert',
  31919. text: 'OK',
  31920. primary: true,
  31921. align: 'end',
  31922. disabled: false,
  31923. icon: Optional.none()
  31924. }, 'cancel', extras.backstage));
  31925. var titleSpec = pUntitled();
  31926. var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  31927. var alertDialog = build$1(renderDialog$1({
  31928. lazySink: function () {
  31929. return sharedBackstage.getSink();
  31930. },
  31931. header: hiddenHeader(titleSpec, closeSpec),
  31932. body: pBodyMessage(message, sharedBackstage.providers),
  31933. footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  31934. onEscape: closeDialog,
  31935. extraClasses: ['tox-alert-dialog'],
  31936. extraBehaviours: [],
  31937. extraStyles: {},
  31938. dialogEvents: [run$1(formCancelEvent, closeDialog)],
  31939. eventOrder: {}
  31940. }));
  31941. ModalDialog.show(alertDialog);
  31942. var footerCloseButton = memFooterClose.get(alertDialog);
  31943. Focusing.focus(footerCloseButton);
  31944. };
  31945. return { open: open };
  31946. };
  31947. var setup$1 = function (extras) {
  31948. var sharedBackstage = extras.backstage.shared;
  31949. var open = function (message, callback) {
  31950. var closeDialog = function (state) {
  31951. ModalDialog.hide(confirmDialog);
  31952. callback(state);
  31953. };
  31954. var memFooterYes = record(renderFooterButton({
  31955. name: 'yes',
  31956. text: 'Yes',
  31957. primary: true,
  31958. align: 'end',
  31959. disabled: false,
  31960. icon: Optional.none()
  31961. }, 'submit', extras.backstage));
  31962. var footerNo = renderFooterButton({
  31963. name: 'no',
  31964. text: 'No',
  31965. primary: false,
  31966. align: 'end',
  31967. disabled: false,
  31968. icon: Optional.none()
  31969. }, 'cancel', extras.backstage);
  31970. var titleSpec = pUntitled();
  31971. var closeSpec = pClose(function () {
  31972. return closeDialog(false);
  31973. }, sharedBackstage.providers);
  31974. var confirmDialog = build$1(renderDialog$1({
  31975. lazySink: function () {
  31976. return sharedBackstage.getSink();
  31977. },
  31978. header: hiddenHeader(titleSpec, closeSpec),
  31979. body: pBodyMessage(message, sharedBackstage.providers),
  31980. footer: Optional.some(pFooter(pFooterGroup([], [
  31981. footerNo,
  31982. memFooterYes.asSpec()
  31983. ]))),
  31984. onEscape: function () {
  31985. return closeDialog(false);
  31986. },
  31987. extraClasses: ['tox-confirm-dialog'],
  31988. extraBehaviours: [],
  31989. extraStyles: {},
  31990. dialogEvents: [
  31991. run$1(formCancelEvent, function () {
  31992. return closeDialog(false);
  31993. }),
  31994. run$1(formSubmitEvent, function () {
  31995. return closeDialog(true);
  31996. })
  31997. ],
  31998. eventOrder: {}
  31999. }));
  32000. ModalDialog.show(confirmDialog);
  32001. var footerYesButton = memFooterYes.get(confirmDialog);
  32002. Focusing.focus(footerYesButton);
  32003. };
  32004. return { open: open };
  32005. };
  32006. var validateData = function (data, validator) {
  32007. return getOrDie(asRaw('data', validator, data));
  32008. };
  32009. var isAlertOrConfirmDialog = function (target) {
  32010. return closest(target, '.tox-alert-dialog') || closest(target, '.tox-confirm-dialog');
  32011. };
  32012. var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  32013. if (isStickyToolbar && isToolbarLocationTop) {
  32014. return [];
  32015. } else {
  32016. return [Docking.config({
  32017. contextual: {
  32018. lazyContext: function () {
  32019. return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer())));
  32020. },
  32021. fadeInClass: 'tox-dialog-dock-fadein',
  32022. fadeOutClass: 'tox-dialog-dock-fadeout',
  32023. transitionClass: 'tox-dialog-dock-transition'
  32024. },
  32025. modes: ['top']
  32026. })];
  32027. }
  32028. };
  32029. var setup = function (extras) {
  32030. var backstage = extras.backstage;
  32031. var editor = extras.editor;
  32032. var isStickyToolbar$1 = isStickyToolbar(editor);
  32033. var alertDialog = setup$2(extras);
  32034. var confirmDialog = setup$1(extras);
  32035. var open = function (config, params, closeWindow) {
  32036. if (params !== undefined && params.inline === 'toolbar') {
  32037. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  32038. } else if (params !== undefined && params.inline === 'cursor') {
  32039. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  32040. } else {
  32041. return openModalDialog(config, closeWindow);
  32042. }
  32043. };
  32044. var openUrl = function (config, closeWindow) {
  32045. return openModalUrlDialog(config, closeWindow);
  32046. };
  32047. var openModalUrlDialog = function (config, closeWindow) {
  32048. var factory = function (contents) {
  32049. var dialog = renderUrlDialog(contents, {
  32050. closeWindow: function () {
  32051. ModalDialog.hide(dialog.dialog);
  32052. closeWindow(dialog.instanceApi);
  32053. }
  32054. }, editor, backstage);
  32055. ModalDialog.show(dialog.dialog);
  32056. return dialog.instanceApi;
  32057. };
  32058. return DialogManager.openUrl(factory, config);
  32059. };
  32060. var openModalDialog = function (config, closeWindow) {
  32061. var factory = function (contents, internalInitialData, dataValidator) {
  32062. var initialData = internalInitialData;
  32063. var dialogInit = {
  32064. dataValidator: dataValidator,
  32065. initialData: initialData,
  32066. internalDialog: contents
  32067. };
  32068. var dialog = renderDialog(dialogInit, {
  32069. redial: DialogManager.redial,
  32070. closeWindow: function () {
  32071. ModalDialog.hide(dialog.dialog);
  32072. closeWindow(dialog.instanceApi);
  32073. }
  32074. }, backstage);
  32075. ModalDialog.show(dialog.dialog);
  32076. dialog.instanceApi.setData(initialData);
  32077. return dialog.instanceApi;
  32078. };
  32079. return DialogManager.open(factory, config);
  32080. };
  32081. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  32082. var factory = function (contents, internalInitialData, dataValidator) {
  32083. var initialData = validateData(internalInitialData, dataValidator);
  32084. var inlineDialog = value$1();
  32085. var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  32086. var dialogInit = {
  32087. dataValidator: dataValidator,
  32088. initialData: initialData,
  32089. internalDialog: contents
  32090. };
  32091. var refreshDocking = function () {
  32092. return inlineDialog.on(function (dialog) {
  32093. InlineView.reposition(dialog);
  32094. Docking.refresh(dialog);
  32095. });
  32096. };
  32097. var dialogUi = renderInlineDialog(dialogInit, {
  32098. redial: DialogManager.redial,
  32099. closeWindow: function () {
  32100. inlineDialog.on(InlineView.hide);
  32101. editor.off('ResizeEditor', refreshDocking);
  32102. inlineDialog.clear();
  32103. closeWindow(dialogUi.instanceApi);
  32104. }
  32105. }, backstage, ariaAttrs);
  32106. var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  32107. lazySink: backstage.shared.getSink,
  32108. dom: {
  32109. tag: 'div',
  32110. classes: []
  32111. },
  32112. fireDismissalEventInstead: {}
  32113. }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
  32114. inlineBehaviours: derive$1(__spreadArray([config('window-manager-inline-events', [run$1(dismissRequested(), function (_comp, _se) {
  32115. emit(dialogUi.dialog, formCancelEvent);
  32116. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop))),
  32117. isExtraPart: function (_comp, target) {
  32118. return isAlertOrConfirmDialog(target);
  32119. }
  32120. })));
  32121. inlineDialog.set(inlineDialogComp);
  32122. InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor }, Optional.some(body()));
  32123. if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  32124. Docking.refresh(inlineDialogComp);
  32125. editor.on('ResizeEditor', refreshDocking);
  32126. }
  32127. dialogUi.instanceApi.setData(initialData);
  32128. Keying.focusIn(dialogUi.dialog);
  32129. return dialogUi.instanceApi;
  32130. };
  32131. return DialogManager.open(factory, config$1);
  32132. };
  32133. var confirm = function (message, callback) {
  32134. confirmDialog.open(message, function (state) {
  32135. callback(state);
  32136. });
  32137. };
  32138. var alert = function (message, callback) {
  32139. alertDialog.open(message, function () {
  32140. callback();
  32141. });
  32142. };
  32143. var close = function (instanceApi) {
  32144. instanceApi.close();
  32145. };
  32146. return {
  32147. open: open,
  32148. openUrl: openUrl,
  32149. alert: alert,
  32150. close: close,
  32151. confirm: confirm
  32152. };
  32153. };
  32154. function Theme () {
  32155. global$h.add('silver', function (editor) {
  32156. var _a = setup$3(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  32157. Autocompleter.register(editor, backstage.shared);
  32158. var windowMgr = setup({
  32159. editor: editor,
  32160. backstage: backstage
  32161. });
  32162. return {
  32163. renderUI: renderUI,
  32164. getWindowManagerImpl: constant$1(windowMgr),
  32165. getNotificationManagerImpl: function () {
  32166. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  32167. },
  32168. ui: getUi()
  32169. };
  32170. });
  32171. }
  32172. Theme();
  32173. }());