theme.js 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.10.2 (2021-11-17)
  8. */
  9. (function () {
  10. 'use strict';
  11. var 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$g = 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 keys = Object.keys;
  431. var hasOwnProperty = Object.hasOwnProperty;
  432. var each = function (obj, f) {
  433. var props = keys(obj);
  434. for (var k = 0, len = props.length; k < len; k++) {
  435. var i = props[k];
  436. var x = obj[i];
  437. f(x, i);
  438. }
  439. };
  440. var map$1 = function (obj, f) {
  441. return tupleMap(obj, function (x, i) {
  442. return {
  443. k: i,
  444. v: f(x, i)
  445. };
  446. });
  447. };
  448. var tupleMap = function (obj, f) {
  449. var r = {};
  450. each(obj, function (x, i) {
  451. var tuple = f(x, i);
  452. r[tuple.k] = tuple.v;
  453. });
  454. return r;
  455. };
  456. var objAcc = function (r) {
  457. return function (x, i) {
  458. r[i] = x;
  459. };
  460. };
  461. var internalFilter = function (obj, pred, onTrue, onFalse) {
  462. var r = {};
  463. each(obj, function (x, i) {
  464. (pred(x, i) ? onTrue : onFalse)(x, i);
  465. });
  466. return r;
  467. };
  468. var filter$1 = function (obj, pred) {
  469. var t = {};
  470. internalFilter(obj, pred, objAcc(t), noop);
  471. return t;
  472. };
  473. var mapToArray = function (obj, f) {
  474. var r = [];
  475. each(obj, function (value, name) {
  476. r.push(f(value, name));
  477. });
  478. return r;
  479. };
  480. var find$4 = function (obj, pred) {
  481. var props = keys(obj);
  482. for (var k = 0, len = props.length; k < len; k++) {
  483. var i = props[k];
  484. var x = obj[i];
  485. if (pred(x, i, obj)) {
  486. return Optional.some(x);
  487. }
  488. }
  489. return Optional.none();
  490. };
  491. var values = function (obj) {
  492. return mapToArray(obj, identity$1);
  493. };
  494. var get$e = function (obj, key) {
  495. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  496. };
  497. var has$2 = function (obj, key) {
  498. return hasOwnProperty.call(obj, key);
  499. };
  500. var hasNonNullableKey = function (obj, key) {
  501. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  502. };
  503. var is$1 = function (lhs, rhs, comparator) {
  504. if (comparator === void 0) {
  505. comparator = tripleEquals;
  506. }
  507. return lhs.exists(function (left) {
  508. return comparator(left, rhs);
  509. });
  510. };
  511. var equals = function (lhs, rhs, comparator) {
  512. if (comparator === void 0) {
  513. comparator = tripleEquals;
  514. }
  515. return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone());
  516. };
  517. var cat = function (arr) {
  518. var r = [];
  519. var push = function (x) {
  520. r.push(x);
  521. };
  522. for (var i = 0; i < arr.length; i++) {
  523. arr[i].each(push);
  524. }
  525. return r;
  526. };
  527. var sequence = function (arr) {
  528. var r = [];
  529. for (var i = 0; i < arr.length; i++) {
  530. var x = arr[i];
  531. if (x.isSome()) {
  532. r.push(x.getOrDie());
  533. } else {
  534. return Optional.none();
  535. }
  536. }
  537. return Optional.some(r);
  538. };
  539. var lift2 = function (oa, ob, f) {
  540. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  541. };
  542. var lift3 = function (oa, ob, oc, f) {
  543. return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none();
  544. };
  545. var mapFrom = function (a, f) {
  546. return a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none();
  547. };
  548. var someIf = function (b, a) {
  549. return b ? Optional.some(a) : Optional.none();
  550. };
  551. var addToEnd = function (str, suffix) {
  552. return str + suffix;
  553. };
  554. var removeFromStart = function (str, numChars) {
  555. return str.substring(numChars);
  556. };
  557. var checkRange = function (str, substr, start) {
  558. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  559. };
  560. var removeLeading = function (str, prefix) {
  561. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  562. };
  563. var ensureTrailing = function (str, suffix) {
  564. return endsWith(str, suffix) ? str : addToEnd(str, suffix);
  565. };
  566. var contains$1 = function (str, substr) {
  567. return str.indexOf(substr) !== -1;
  568. };
  569. var startsWith = function (str, prefix) {
  570. return checkRange(str, prefix, 0);
  571. };
  572. var endsWith = function (str, suffix) {
  573. return checkRange(str, suffix, str.length - suffix.length);
  574. };
  575. var blank = function (r) {
  576. return function (s) {
  577. return s.replace(r, '');
  578. };
  579. };
  580. var trim$1 = blank(/^\s+|\s+$/g);
  581. var isNotEmpty = function (s) {
  582. return s.length > 0;
  583. };
  584. var isEmpty = function (s) {
  585. return !isNotEmpty(s);
  586. };
  587. var isSupported$1 = function (dom) {
  588. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  589. };
  590. var fromHtml$2 = function (html, scope) {
  591. var doc = scope || document;
  592. var div = doc.createElement('div');
  593. div.innerHTML = html;
  594. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  595. console.error('HTML does not have a single root node', html);
  596. throw new Error('HTML must have a single root node');
  597. }
  598. return fromDom(div.childNodes[0]);
  599. };
  600. var fromTag = function (tag, scope) {
  601. var doc = scope || document;
  602. var node = doc.createElement(tag);
  603. return fromDom(node);
  604. };
  605. var fromText = function (text, scope) {
  606. var doc = scope || document;
  607. var node = doc.createTextNode(text);
  608. return fromDom(node);
  609. };
  610. var fromDom = function (node) {
  611. if (node === null || node === undefined) {
  612. throw new Error('Node cannot be null or undefined');
  613. }
  614. return { dom: node };
  615. };
  616. var fromPoint = function (docElm, x, y) {
  617. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  618. };
  619. var SugarElement = {
  620. fromHtml: fromHtml$2,
  621. fromTag: fromTag,
  622. fromText: fromText,
  623. fromDom: fromDom,
  624. fromPoint: fromPoint
  625. };
  626. typeof window !== 'undefined' ? window : Function('return this;')();
  627. var DOCUMENT = 9;
  628. var DOCUMENT_FRAGMENT = 11;
  629. var ELEMENT = 1;
  630. var TEXT = 3;
  631. var name$2 = function (element) {
  632. var r = element.dom.nodeName;
  633. return r.toLowerCase();
  634. };
  635. var type = function (element) {
  636. return element.dom.nodeType;
  637. };
  638. var isType = function (t) {
  639. return function (element) {
  640. return type(element) === t;
  641. };
  642. };
  643. var isElement$2 = isType(ELEMENT);
  644. var isText$1 = isType(TEXT);
  645. var isDocument = isType(DOCUMENT);
  646. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  647. var cached = function (f) {
  648. var called = false;
  649. var r;
  650. return function () {
  651. var args = [];
  652. for (var _i = 0; _i < arguments.length; _i++) {
  653. args[_i] = arguments[_i];
  654. }
  655. if (!called) {
  656. called = true;
  657. r = f.apply(null, args);
  658. }
  659. return r;
  660. };
  661. };
  662. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  663. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  664. var isiPhone = os.isiOS() && !isiPad;
  665. var isMobile = os.isiOS() || os.isAndroid();
  666. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  667. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  668. var isPhone = isiPhone || isMobile && !isTablet;
  669. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  670. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  671. return {
  672. isiPad: constant$1(isiPad),
  673. isiPhone: constant$1(isiPhone),
  674. isTablet: constant$1(isTablet),
  675. isPhone: constant$1(isPhone),
  676. isTouch: constant$1(isTouch),
  677. isAndroid: os.isAndroid,
  678. isiOS: os.isiOS,
  679. isWebView: constant$1(iOSwebview),
  680. isDesktop: constant$1(isDesktop)
  681. };
  682. };
  683. var firstMatch = function (regexes, s) {
  684. for (var i = 0; i < regexes.length; i++) {
  685. var x = regexes[i];
  686. if (x.test(s)) {
  687. return x;
  688. }
  689. }
  690. return undefined;
  691. };
  692. var find$3 = function (regexes, agent) {
  693. var r = firstMatch(regexes, agent);
  694. if (!r) {
  695. return {
  696. major: 0,
  697. minor: 0
  698. };
  699. }
  700. var group = function (i) {
  701. return Number(agent.replace(r, '$' + i));
  702. };
  703. return nu$d(group(1), group(2));
  704. };
  705. var detect$4 = function (versionRegexes, agent) {
  706. var cleanedAgent = String(agent).toLowerCase();
  707. if (versionRegexes.length === 0) {
  708. return unknown$3();
  709. }
  710. return find$3(versionRegexes, cleanedAgent);
  711. };
  712. var unknown$3 = function () {
  713. return nu$d(0, 0);
  714. };
  715. var nu$d = function (major, minor) {
  716. return {
  717. major: major,
  718. minor: minor
  719. };
  720. };
  721. var Version = {
  722. nu: nu$d,
  723. detect: detect$4,
  724. unknown: unknown$3
  725. };
  726. var detectBrowser$1 = function (browsers, userAgentData) {
  727. return findMap(userAgentData.brands, function (uaBrand) {
  728. var lcBrand = uaBrand.brand.toLowerCase();
  729. return find$5(browsers, function (browser) {
  730. var _a;
  731. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  732. }).map(function (info) {
  733. return {
  734. current: info.name,
  735. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  736. };
  737. });
  738. });
  739. };
  740. var detect$3 = function (candidates, userAgent) {
  741. var agent = String(userAgent).toLowerCase();
  742. return find$5(candidates, function (candidate) {
  743. return candidate.search(agent);
  744. });
  745. };
  746. var detectBrowser = function (browsers, userAgent) {
  747. return detect$3(browsers, userAgent).map(function (browser) {
  748. var version = Version.detect(browser.versionRegexes, userAgent);
  749. return {
  750. current: browser.name,
  751. version: version
  752. };
  753. });
  754. };
  755. var detectOs = function (oses, userAgent) {
  756. return detect$3(oses, userAgent).map(function (os) {
  757. var version = Version.detect(os.versionRegexes, userAgent);
  758. return {
  759. current: os.name,
  760. version: version
  761. };
  762. });
  763. };
  764. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  765. var checkContains = function (target) {
  766. return function (uastring) {
  767. return contains$1(uastring, target);
  768. };
  769. };
  770. var browsers = [
  771. {
  772. name: 'Edge',
  773. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  774. search: function (uastring) {
  775. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  776. }
  777. },
  778. {
  779. name: 'Chrome',
  780. brand: 'Chromium',
  781. versionRegexes: [
  782. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  783. normalVersionRegex
  784. ],
  785. search: function (uastring) {
  786. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  787. }
  788. },
  789. {
  790. name: 'IE',
  791. versionRegexes: [
  792. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  793. /.*?rv:([0-9]+)\.([0-9]+).*/
  794. ],
  795. search: function (uastring) {
  796. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  797. }
  798. },
  799. {
  800. name: 'Opera',
  801. versionRegexes: [
  802. normalVersionRegex,
  803. /.*?opera\/([0-9]+)\.([0-9]+).*/
  804. ],
  805. search: checkContains('opera')
  806. },
  807. {
  808. name: 'Firefox',
  809. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  810. search: checkContains('firefox')
  811. },
  812. {
  813. name: 'Safari',
  814. versionRegexes: [
  815. normalVersionRegex,
  816. /.*?cpu os ([0-9]+)_([0-9]+).*/
  817. ],
  818. search: function (uastring) {
  819. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  820. }
  821. }
  822. ];
  823. var oses = [
  824. {
  825. name: 'Windows',
  826. search: checkContains('win'),
  827. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  828. },
  829. {
  830. name: 'iOS',
  831. search: function (uastring) {
  832. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  833. },
  834. versionRegexes: [
  835. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  836. /.*cpu os ([0-9]+)_([0-9]+).*/,
  837. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  838. ]
  839. },
  840. {
  841. name: 'Android',
  842. search: checkContains('android'),
  843. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  844. },
  845. {
  846. name: 'OSX',
  847. search: checkContains('mac os x'),
  848. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  849. },
  850. {
  851. name: 'Linux',
  852. search: checkContains('linux'),
  853. versionRegexes: []
  854. },
  855. {
  856. name: 'Solaris',
  857. search: checkContains('sunos'),
  858. versionRegexes: []
  859. },
  860. {
  861. name: 'FreeBSD',
  862. search: checkContains('freebsd'),
  863. versionRegexes: []
  864. },
  865. {
  866. name: 'ChromeOS',
  867. search: checkContains('cros'),
  868. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  869. }
  870. ];
  871. var PlatformInfo = {
  872. browsers: constant$1(browsers),
  873. oses: constant$1(oses)
  874. };
  875. var edge = 'Edge';
  876. var chrome = 'Chrome';
  877. var ie = 'IE';
  878. var opera = 'Opera';
  879. var firefox = 'Firefox';
  880. var safari = 'Safari';
  881. var unknown$2 = function () {
  882. return nu$c({
  883. current: undefined,
  884. version: Version.unknown()
  885. });
  886. };
  887. var nu$c = function (info) {
  888. var current = info.current;
  889. var version = info.version;
  890. var isBrowser = function (name) {
  891. return function () {
  892. return current === name;
  893. };
  894. };
  895. return {
  896. current: current,
  897. version: version,
  898. isEdge: isBrowser(edge),
  899. isChrome: isBrowser(chrome),
  900. isIE: isBrowser(ie),
  901. isOpera: isBrowser(opera),
  902. isFirefox: isBrowser(firefox),
  903. isSafari: isBrowser(safari)
  904. };
  905. };
  906. var Browser = {
  907. unknown: unknown$2,
  908. nu: nu$c,
  909. edge: constant$1(edge),
  910. chrome: constant$1(chrome),
  911. ie: constant$1(ie),
  912. opera: constant$1(opera),
  913. firefox: constant$1(firefox),
  914. safari: constant$1(safari)
  915. };
  916. var windows = 'Windows';
  917. var ios = 'iOS';
  918. var android = 'Android';
  919. var linux = 'Linux';
  920. var osx = 'OSX';
  921. var solaris = 'Solaris';
  922. var freebsd = 'FreeBSD';
  923. var chromeos = 'ChromeOS';
  924. var unknown$1 = function () {
  925. return nu$b({
  926. current: undefined,
  927. version: Version.unknown()
  928. });
  929. };
  930. var nu$b = function (info) {
  931. var current = info.current;
  932. var version = info.version;
  933. var isOS = function (name) {
  934. return function () {
  935. return current === name;
  936. };
  937. };
  938. return {
  939. current: current,
  940. version: version,
  941. isWindows: isOS(windows),
  942. isiOS: isOS(ios),
  943. isAndroid: isOS(android),
  944. isOSX: isOS(osx),
  945. isLinux: isOS(linux),
  946. isSolaris: isOS(solaris),
  947. isFreeBSD: isOS(freebsd),
  948. isChromeOS: isOS(chromeos)
  949. };
  950. };
  951. var OperatingSystem = {
  952. unknown: unknown$1,
  953. nu: nu$b,
  954. windows: constant$1(windows),
  955. ios: constant$1(ios),
  956. android: constant$1(android),
  957. linux: constant$1(linux),
  958. osx: constant$1(osx),
  959. solaris: constant$1(solaris),
  960. freebsd: constant$1(freebsd),
  961. chromeos: constant$1(chromeos)
  962. };
  963. var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  964. var browsers = PlatformInfo.browsers();
  965. var oses = PlatformInfo.oses();
  966. var browser = userAgentDataOpt.bind(function (userAgentData) {
  967. return detectBrowser$1(browsers, userAgentData);
  968. }).orThunk(function () {
  969. return detectBrowser(browsers, userAgent);
  970. }).fold(Browser.unknown, Browser.nu);
  971. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  972. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  973. return {
  974. browser: browser,
  975. os: os,
  976. deviceType: deviceType
  977. };
  978. };
  979. var PlatformDetection = { detect: detect$2 };
  980. var mediaMatch = function (query) {
  981. return window.matchMedia(query).matches;
  982. };
  983. var platform = cached(function () {
  984. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  985. });
  986. var detect$1 = function () {
  987. return platform();
  988. };
  989. var compareDocumentPosition = function (a, b, match) {
  990. return (a.compareDocumentPosition(b) & match) !== 0;
  991. };
  992. var documentPositionContainedBy = function (a, b) {
  993. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY);
  994. };
  995. var is = function (element, selector) {
  996. var dom = element.dom;
  997. if (dom.nodeType !== ELEMENT) {
  998. return false;
  999. } else {
  1000. var elem = dom;
  1001. if (elem.matches !== undefined) {
  1002. return elem.matches(selector);
  1003. } else if (elem.msMatchesSelector !== undefined) {
  1004. return elem.msMatchesSelector(selector);
  1005. } else if (elem.webkitMatchesSelector !== undefined) {
  1006. return elem.webkitMatchesSelector(selector);
  1007. } else if (elem.mozMatchesSelector !== undefined) {
  1008. return elem.mozMatchesSelector(selector);
  1009. } else {
  1010. throw new Error('Browser lacks native selectors');
  1011. }
  1012. }
  1013. };
  1014. var bypassSelector = function (dom) {
  1015. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  1016. };
  1017. var all$3 = function (selector, scope) {
  1018. var base = scope === undefined ? document : scope.dom;
  1019. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  1020. };
  1021. var one = function (selector, scope) {
  1022. var base = scope === undefined ? document : scope.dom;
  1023. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  1024. };
  1025. var eq = function (e1, e2) {
  1026. return e1.dom === e2.dom;
  1027. };
  1028. var regularContains = function (e1, e2) {
  1029. var d1 = e1.dom;
  1030. var d2 = e2.dom;
  1031. return d1 === d2 ? false : d1.contains(d2);
  1032. };
  1033. var ieContains = function (e1, e2) {
  1034. return documentPositionContainedBy(e1.dom, e2.dom);
  1035. };
  1036. var contains = function (e1, e2) {
  1037. return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1038. };
  1039. var owner$4 = function (element) {
  1040. return SugarElement.fromDom(element.dom.ownerDocument);
  1041. };
  1042. var documentOrOwner = function (dos) {
  1043. return isDocument(dos) ? dos : owner$4(dos);
  1044. };
  1045. var documentElement = function (element) {
  1046. return SugarElement.fromDom(documentOrOwner(element).dom.documentElement);
  1047. };
  1048. var defaultView = function (element) {
  1049. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  1050. };
  1051. var parent = function (element) {
  1052. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  1053. };
  1054. var parentNode = function (element) {
  1055. return parent(element);
  1056. };
  1057. var offsetParent = function (element) {
  1058. return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom);
  1059. };
  1060. var nextSibling = function (element) {
  1061. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  1062. };
  1063. var children = function (element) {
  1064. return map$2(element.dom.childNodes, SugarElement.fromDom);
  1065. };
  1066. var child$2 = function (element, index) {
  1067. var cs = element.dom.childNodes;
  1068. return Optional.from(cs[index]).map(SugarElement.fromDom);
  1069. };
  1070. var firstChild = function (element) {
  1071. return child$2(element, 0);
  1072. };
  1073. var spot = function (element, offset) {
  1074. return {
  1075. element: element,
  1076. offset: offset
  1077. };
  1078. };
  1079. var leaf = function (element, offset) {
  1080. var cs = children(element);
  1081. return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  1082. };
  1083. var isShadowRoot = function (dos) {
  1084. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  1085. };
  1086. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  1087. var isSupported = constant$1(supported);
  1088. var getRootNode = supported ? function (e) {
  1089. return SugarElement.fromDom(e.dom.getRootNode());
  1090. } : documentOrOwner;
  1091. var getContentContainer = function (dos) {
  1092. return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body);
  1093. };
  1094. var isInShadowRoot = function (e) {
  1095. return getShadowRoot(e).isSome();
  1096. };
  1097. var getShadowRoot = function (e) {
  1098. var r = getRootNode(e);
  1099. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  1100. };
  1101. var getShadowHost = function (e) {
  1102. return SugarElement.fromDom(e.dom.host);
  1103. };
  1104. var getOriginalEventTarget = function (event) {
  1105. if (isSupported() && isNonNullable(event.target)) {
  1106. var el = SugarElement.fromDom(event.target);
  1107. if (isElement$2(el) && isOpenShadowHost(el)) {
  1108. if (event.composed && event.composedPath) {
  1109. var composedPath = event.composedPath();
  1110. if (composedPath) {
  1111. return head(composedPath);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. return Optional.from(event.target);
  1117. };
  1118. var isOpenShadowHost = function (element) {
  1119. return isNonNullable(element.dom.shadowRoot);
  1120. };
  1121. var inBody = function (element) {
  1122. var dom = isText$1(element) ? element.dom.parentNode : element.dom;
  1123. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1124. return false;
  1125. }
  1126. var doc = dom.ownerDocument;
  1127. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1128. return doc.body.contains(dom);
  1129. }, compose1(inBody, getShadowHost));
  1130. };
  1131. var body = function () {
  1132. return getBody(SugarElement.fromDom(document));
  1133. };
  1134. var getBody = function (doc) {
  1135. var b = doc.dom.body;
  1136. if (b === null || b === undefined) {
  1137. throw new Error('Body is not available yet');
  1138. }
  1139. return SugarElement.fromDom(b);
  1140. };
  1141. var rawSet = function (dom, key, value) {
  1142. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1143. dom.setAttribute(key, value + '');
  1144. } else {
  1145. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1146. throw new Error('Attribute value was not simple');
  1147. }
  1148. };
  1149. var set$8 = function (element, key, value) {
  1150. rawSet(element.dom, key, value);
  1151. };
  1152. var setAll$1 = function (element, attrs) {
  1153. var dom = element.dom;
  1154. each(attrs, function (v, k) {
  1155. rawSet(dom, k, v);
  1156. });
  1157. };
  1158. var get$d = function (element, key) {
  1159. var v = element.dom.getAttribute(key);
  1160. return v === null ? undefined : v;
  1161. };
  1162. var getOpt = function (element, key) {
  1163. return Optional.from(get$d(element, key));
  1164. };
  1165. var has$1 = function (element, key) {
  1166. var dom = element.dom;
  1167. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1168. };
  1169. var remove$7 = function (element, key) {
  1170. element.dom.removeAttribute(key);
  1171. };
  1172. var internalSet = function (dom, property, value) {
  1173. if (!isString(value)) {
  1174. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  1175. throw new Error('CSS value must be a string: ' + value);
  1176. }
  1177. if (isSupported$1(dom)) {
  1178. dom.style.setProperty(property, value);
  1179. }
  1180. };
  1181. var internalRemove = function (dom, property) {
  1182. if (isSupported$1(dom)) {
  1183. dom.style.removeProperty(property);
  1184. }
  1185. };
  1186. var set$7 = function (element, property, value) {
  1187. var dom = element.dom;
  1188. internalSet(dom, property, value);
  1189. };
  1190. var setAll = function (element, css) {
  1191. var dom = element.dom;
  1192. each(css, function (v, k) {
  1193. internalSet(dom, k, v);
  1194. });
  1195. };
  1196. var setOptions = function (element, css) {
  1197. var dom = element.dom;
  1198. each(css, function (v, k) {
  1199. v.fold(function () {
  1200. internalRemove(dom, k);
  1201. }, function (value) {
  1202. internalSet(dom, k, value);
  1203. });
  1204. });
  1205. };
  1206. var get$c = function (element, property) {
  1207. var dom = element.dom;
  1208. var styles = window.getComputedStyle(dom);
  1209. var r = styles.getPropertyValue(property);
  1210. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  1211. };
  1212. var getUnsafeProperty = function (dom, property) {
  1213. return isSupported$1(dom) ? dom.style.getPropertyValue(property) : '';
  1214. };
  1215. var getRaw = function (element, property) {
  1216. var dom = element.dom;
  1217. var raw = getUnsafeProperty(dom, property);
  1218. return Optional.from(raw).filter(function (r) {
  1219. return r.length > 0;
  1220. });
  1221. };
  1222. var getAllRaw = function (element) {
  1223. var css = {};
  1224. var dom = element.dom;
  1225. if (isSupported$1(dom)) {
  1226. for (var i = 0; i < dom.style.length; i++) {
  1227. var ruleName = dom.style.item(i);
  1228. css[ruleName] = dom.style[ruleName];
  1229. }
  1230. }
  1231. return css;
  1232. };
  1233. var isValidValue = function (tag, property, value) {
  1234. var element = SugarElement.fromTag(tag);
  1235. set$7(element, property, value);
  1236. var style = getRaw(element, property);
  1237. return style.isSome();
  1238. };
  1239. var remove$6 = function (element, property) {
  1240. var dom = element.dom;
  1241. internalRemove(dom, property);
  1242. if (is$1(getOpt(element, 'style').map(trim$1), '')) {
  1243. remove$7(element, 'style');
  1244. }
  1245. };
  1246. var reflow = function (e) {
  1247. return e.dom.offsetWidth;
  1248. };
  1249. var Dimension = function (name, getOffset) {
  1250. var set = function (element, h) {
  1251. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  1252. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  1253. }
  1254. var dom = element.dom;
  1255. if (isSupported$1(dom)) {
  1256. dom.style[name] = h + 'px';
  1257. }
  1258. };
  1259. var get = function (element) {
  1260. var r = getOffset(element);
  1261. if (r <= 0 || r === null) {
  1262. var css = get$c(element, name);
  1263. return parseFloat(css) || 0;
  1264. }
  1265. return r;
  1266. };
  1267. var getOuter = get;
  1268. var aggregate = function (element, properties) {
  1269. return foldl(properties, function (acc, property) {
  1270. var val = get$c(element, property);
  1271. var value = val === undefined ? 0 : parseInt(val, 10);
  1272. return isNaN(value) ? acc : acc + value;
  1273. }, 0);
  1274. };
  1275. var max = function (element, value, properties) {
  1276. var cumulativeInclusions = aggregate(element, properties);
  1277. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  1278. return absoluteMax;
  1279. };
  1280. return {
  1281. set: set,
  1282. get: get,
  1283. getOuter: getOuter,
  1284. aggregate: aggregate,
  1285. max: max
  1286. };
  1287. };
  1288. var api$3 = Dimension('height', function (element) {
  1289. var dom = element.dom;
  1290. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  1291. });
  1292. var get$b = function (element) {
  1293. return api$3.get(element);
  1294. };
  1295. var getOuter$2 = function (element) {
  1296. return api$3.getOuter(element);
  1297. };
  1298. var setMax$1 = function (element, value) {
  1299. var inclusions = [
  1300. 'margin-top',
  1301. 'border-top-width',
  1302. 'padding-top',
  1303. 'padding-bottom',
  1304. 'border-bottom-width',
  1305. 'margin-bottom'
  1306. ];
  1307. var absMax = api$3.max(element, value, inclusions);
  1308. set$7(element, 'max-height', absMax + 'px');
  1309. };
  1310. var r$1 = function (left, top) {
  1311. var translate = function (x, y) {
  1312. return r$1(left + x, top + y);
  1313. };
  1314. return {
  1315. left: left,
  1316. top: top,
  1317. translate: translate
  1318. };
  1319. };
  1320. var SugarPosition = r$1;
  1321. var boxPosition = function (dom) {
  1322. var box = dom.getBoundingClientRect();
  1323. return SugarPosition(box.left, box.top);
  1324. };
  1325. var firstDefinedOrZero = function (a, b) {
  1326. if (a !== undefined) {
  1327. return a;
  1328. } else {
  1329. return b !== undefined ? b : 0;
  1330. }
  1331. };
  1332. var absolute$3 = function (element) {
  1333. var doc = element.dom.ownerDocument;
  1334. var body = doc.body;
  1335. var win = doc.defaultView;
  1336. var html = doc.documentElement;
  1337. if (body === element.dom) {
  1338. return SugarPosition(body.offsetLeft, body.offsetTop);
  1339. }
  1340. var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop);
  1341. var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft);
  1342. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  1343. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  1344. return viewport$1(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  1345. };
  1346. var viewport$1 = function (element) {
  1347. var dom = element.dom;
  1348. var doc = dom.ownerDocument;
  1349. var body = doc.body;
  1350. if (body === dom) {
  1351. return SugarPosition(body.offsetLeft, body.offsetTop);
  1352. }
  1353. if (!inBody(element)) {
  1354. return SugarPosition(0, 0);
  1355. }
  1356. return boxPosition(dom);
  1357. };
  1358. var api$2 = Dimension('width', function (element) {
  1359. return element.dom.offsetWidth;
  1360. });
  1361. var set$6 = function (element, h) {
  1362. return api$2.set(element, h);
  1363. };
  1364. var get$a = function (element) {
  1365. return api$2.get(element);
  1366. };
  1367. var getOuter$1 = function (element) {
  1368. return api$2.getOuter(element);
  1369. };
  1370. var setMax = function (element, value) {
  1371. var inclusions = [
  1372. 'margin-left',
  1373. 'border-left-width',
  1374. 'padding-left',
  1375. 'padding-right',
  1376. 'border-right-width',
  1377. 'margin-right'
  1378. ];
  1379. var absMax = api$2.max(element, value, inclusions);
  1380. set$7(element, 'max-width', absMax + 'px');
  1381. };
  1382. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  1383. return {
  1384. target: target,
  1385. x: x,
  1386. y: y,
  1387. stop: stop,
  1388. prevent: prevent,
  1389. kill: kill,
  1390. raw: raw
  1391. };
  1392. };
  1393. var fromRawEvent$1 = function (rawEvent) {
  1394. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  1395. var stop = function () {
  1396. return rawEvent.stopPropagation();
  1397. };
  1398. var prevent = function () {
  1399. return rawEvent.preventDefault();
  1400. };
  1401. var kill = compose(prevent, stop);
  1402. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  1403. };
  1404. var handle = function (filter, handler) {
  1405. return function (rawEvent) {
  1406. if (filter(rawEvent)) {
  1407. handler(fromRawEvent$1(rawEvent));
  1408. }
  1409. };
  1410. };
  1411. var binder = function (element, event, filter, handler, useCapture) {
  1412. var wrapped = handle(filter, handler);
  1413. element.dom.addEventListener(event, wrapped, useCapture);
  1414. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  1415. };
  1416. var bind$2 = function (element, event, filter, handler) {
  1417. return binder(element, event, filter, handler, false);
  1418. };
  1419. var capture$1 = function (element, event, filter, handler) {
  1420. return binder(element, event, filter, handler, true);
  1421. };
  1422. var unbind = function (element, event, handler, useCapture) {
  1423. element.dom.removeEventListener(event, handler, useCapture);
  1424. };
  1425. var before$2 = function (marker, element) {
  1426. var parent$1 = parent(marker);
  1427. parent$1.each(function (v) {
  1428. v.dom.insertBefore(element.dom, marker.dom);
  1429. });
  1430. };
  1431. var after$2 = function (marker, element) {
  1432. var sibling = nextSibling(marker);
  1433. sibling.fold(function () {
  1434. var parent$1 = parent(marker);
  1435. parent$1.each(function (v) {
  1436. append$2(v, element);
  1437. });
  1438. }, function (v) {
  1439. before$2(v, element);
  1440. });
  1441. };
  1442. var prepend$1 = function (parent, element) {
  1443. var firstChild$1 = firstChild(parent);
  1444. firstChild$1.fold(function () {
  1445. append$2(parent, element);
  1446. }, function (v) {
  1447. parent.dom.insertBefore(element.dom, v.dom);
  1448. });
  1449. };
  1450. var append$2 = function (parent, element) {
  1451. parent.dom.appendChild(element.dom);
  1452. };
  1453. var appendAt = function (parent, element, index) {
  1454. child$2(parent, index).fold(function () {
  1455. append$2(parent, element);
  1456. }, function (v) {
  1457. before$2(v, element);
  1458. });
  1459. };
  1460. var before$1 = function (marker, elements) {
  1461. each$1(elements, function (x) {
  1462. before$2(marker, x);
  1463. });
  1464. };
  1465. var append$1 = function (parent, elements) {
  1466. each$1(elements, function (x) {
  1467. append$2(parent, x);
  1468. });
  1469. };
  1470. var empty = function (element) {
  1471. element.dom.textContent = '';
  1472. each$1(children(element), function (rogue) {
  1473. remove$5(rogue);
  1474. });
  1475. };
  1476. var remove$5 = function (element) {
  1477. var dom = element.dom;
  1478. if (dom.parentNode !== null) {
  1479. dom.parentNode.removeChild(dom);
  1480. }
  1481. };
  1482. var unwrap = function (wrapper) {
  1483. var children$1 = children(wrapper);
  1484. if (children$1.length > 0) {
  1485. before$1(wrapper, children$1);
  1486. }
  1487. remove$5(wrapper);
  1488. };
  1489. var get$9 = function (_DOC) {
  1490. var doc = _DOC !== undefined ? _DOC.dom : document;
  1491. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  1492. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  1493. return SugarPosition(x, y);
  1494. };
  1495. var to = function (x, y, _DOC) {
  1496. var doc = _DOC !== undefined ? _DOC.dom : document;
  1497. var win = doc.defaultView;
  1498. if (win) {
  1499. win.scrollTo(x, y);
  1500. }
  1501. };
  1502. var get$8 = function (_win) {
  1503. var win = _win === undefined ? window : _win;
  1504. if (detect$1().browser.isFirefox()) {
  1505. return Optional.none();
  1506. } else {
  1507. return Optional.from(win['visualViewport']);
  1508. }
  1509. };
  1510. var bounds$1 = function (x, y, width, height) {
  1511. return {
  1512. x: x,
  1513. y: y,
  1514. width: width,
  1515. height: height,
  1516. right: x + width,
  1517. bottom: y + height
  1518. };
  1519. };
  1520. var getBounds$3 = function (_win) {
  1521. var win = _win === undefined ? window : _win;
  1522. var doc = win.document;
  1523. var scroll = get$9(SugarElement.fromDom(doc));
  1524. return get$8(win).fold(function () {
  1525. var html = win.document.documentElement;
  1526. var width = html.clientWidth;
  1527. var height = html.clientHeight;
  1528. return bounds$1(scroll.left, scroll.top, width, height);
  1529. }, function (visualViewport) {
  1530. return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height);
  1531. });
  1532. };
  1533. var walkUp = function (navigation, doc) {
  1534. var frame = navigation.view(doc);
  1535. return frame.fold(constant$1([]), function (f) {
  1536. var parent = navigation.owner(f);
  1537. var rest = walkUp(navigation, parent);
  1538. return [f].concat(rest);
  1539. });
  1540. };
  1541. var pathTo = function (element, navigation) {
  1542. var d = navigation.owner(element);
  1543. var paths = walkUp(navigation, d);
  1544. return Optional.some(paths);
  1545. };
  1546. var view = function (doc) {
  1547. var _a;
  1548. var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement);
  1549. return element.map(SugarElement.fromDom);
  1550. };
  1551. var owner$3 = function (element) {
  1552. return owner$4(element);
  1553. };
  1554. var Navigation = /*#__PURE__*/Object.freeze({
  1555. __proto__: null,
  1556. view: view,
  1557. owner: owner$3
  1558. });
  1559. var find$2 = function (element) {
  1560. var doc = SugarElement.fromDom(document);
  1561. var scroll = get$9(doc);
  1562. var path = pathTo(element, Navigation);
  1563. return path.fold(curry(absolute$3, element), function (frames) {
  1564. var offset = viewport$1(element);
  1565. var r = foldr(frames, function (b, a) {
  1566. var loc = viewport$1(a);
  1567. return {
  1568. left: b.left + loc.left,
  1569. top: b.top + loc.top
  1570. };
  1571. }, {
  1572. left: 0,
  1573. top: 0
  1574. });
  1575. return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top);
  1576. });
  1577. };
  1578. var pointed = function (point, width, height) {
  1579. return {
  1580. point: point,
  1581. width: width,
  1582. height: height
  1583. };
  1584. };
  1585. var rect = function (x, y, width, height) {
  1586. return {
  1587. x: x,
  1588. y: y,
  1589. width: width,
  1590. height: height
  1591. };
  1592. };
  1593. var bounds = function (x, y, width, height) {
  1594. return {
  1595. x: x,
  1596. y: y,
  1597. width: width,
  1598. height: height,
  1599. right: x + width,
  1600. bottom: y + height
  1601. };
  1602. };
  1603. var box$1 = function (element) {
  1604. var xy = absolute$3(element);
  1605. var w = getOuter$1(element);
  1606. var h = getOuter$2(element);
  1607. return bounds(xy.left, xy.top, w, h);
  1608. };
  1609. var absolute$2 = function (element) {
  1610. var position = find$2(element);
  1611. var width = getOuter$1(element);
  1612. var height = getOuter$2(element);
  1613. return bounds(position.left, position.top, width, height);
  1614. };
  1615. var win = function () {
  1616. return getBounds$3(window);
  1617. };
  1618. var value$3 = function (o) {
  1619. var or = function (_opt) {
  1620. return value$3(o);
  1621. };
  1622. var orThunk = function (_f) {
  1623. return value$3(o);
  1624. };
  1625. var map = function (f) {
  1626. return value$3(f(o));
  1627. };
  1628. var mapError = function (_f) {
  1629. return value$3(o);
  1630. };
  1631. var each = function (f) {
  1632. f(o);
  1633. };
  1634. var bind = function (f) {
  1635. return f(o);
  1636. };
  1637. var fold = function (_, onValue) {
  1638. return onValue(o);
  1639. };
  1640. var exists = function (f) {
  1641. return f(o);
  1642. };
  1643. var forall = function (f) {
  1644. return f(o);
  1645. };
  1646. var toOptional = function () {
  1647. return Optional.some(o);
  1648. };
  1649. return {
  1650. isValue: always,
  1651. isError: never,
  1652. getOr: constant$1(o),
  1653. getOrThunk: constant$1(o),
  1654. getOrDie: constant$1(o),
  1655. or: or,
  1656. orThunk: orThunk,
  1657. fold: fold,
  1658. map: map,
  1659. mapError: mapError,
  1660. each: each,
  1661. bind: bind,
  1662. exists: exists,
  1663. forall: forall,
  1664. toOptional: toOptional
  1665. };
  1666. };
  1667. var error$1 = function (message) {
  1668. var getOrThunk = function (f) {
  1669. return f();
  1670. };
  1671. var getOrDie = function () {
  1672. return die(String(message))();
  1673. };
  1674. var or = identity$1;
  1675. var orThunk = function (f) {
  1676. return f();
  1677. };
  1678. var map = function (_f) {
  1679. return error$1(message);
  1680. };
  1681. var mapError = function (f) {
  1682. return error$1(f(message));
  1683. };
  1684. var bind = function (_f) {
  1685. return error$1(message);
  1686. };
  1687. var fold = function (onError, _) {
  1688. return onError(message);
  1689. };
  1690. return {
  1691. isValue: never,
  1692. isError: always,
  1693. getOr: identity$1,
  1694. getOrThunk: getOrThunk,
  1695. getOrDie: getOrDie,
  1696. or: or,
  1697. orThunk: orThunk,
  1698. fold: fold,
  1699. map: map,
  1700. mapError: mapError,
  1701. each: noop,
  1702. bind: bind,
  1703. exists: never,
  1704. forall: always,
  1705. toOptional: Optional.none
  1706. };
  1707. };
  1708. var fromOption = function (opt, err) {
  1709. return opt.fold(function () {
  1710. return error$1(err);
  1711. }, value$3);
  1712. };
  1713. var Result = {
  1714. value: value$3,
  1715. error: error$1,
  1716. fromOption: fromOption
  1717. };
  1718. var SimpleResultType;
  1719. (function (SimpleResultType) {
  1720. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1721. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1722. }(SimpleResultType || (SimpleResultType = {})));
  1723. var fold$1 = function (res, onError, onValue) {
  1724. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1725. };
  1726. var partition$2 = function (results) {
  1727. var values = [];
  1728. var errors = [];
  1729. each$1(results, function (obj) {
  1730. fold$1(obj, function (err) {
  1731. return errors.push(err);
  1732. }, function (val) {
  1733. return values.push(val);
  1734. });
  1735. });
  1736. return {
  1737. values: values,
  1738. errors: errors
  1739. };
  1740. };
  1741. var mapError = function (res, f) {
  1742. if (res.stype === SimpleResultType.Error) {
  1743. return {
  1744. stype: SimpleResultType.Error,
  1745. serror: f(res.serror)
  1746. };
  1747. } else {
  1748. return res;
  1749. }
  1750. };
  1751. var map = function (res, f) {
  1752. if (res.stype === SimpleResultType.Value) {
  1753. return {
  1754. stype: SimpleResultType.Value,
  1755. svalue: f(res.svalue)
  1756. };
  1757. } else {
  1758. return res;
  1759. }
  1760. };
  1761. var bind$1 = function (res, f) {
  1762. if (res.stype === SimpleResultType.Value) {
  1763. return f(res.svalue);
  1764. } else {
  1765. return res;
  1766. }
  1767. };
  1768. var bindError = function (res, f) {
  1769. if (res.stype === SimpleResultType.Error) {
  1770. return f(res.serror);
  1771. } else {
  1772. return res;
  1773. }
  1774. };
  1775. var svalue = function (v) {
  1776. return {
  1777. stype: SimpleResultType.Value,
  1778. svalue: v
  1779. };
  1780. };
  1781. var serror = function (e) {
  1782. return {
  1783. stype: SimpleResultType.Error,
  1784. serror: e
  1785. };
  1786. };
  1787. var toResult$1 = function (res) {
  1788. return fold$1(res, Result.error, Result.value);
  1789. };
  1790. var fromResult$1 = function (res) {
  1791. return res.fold(serror, svalue);
  1792. };
  1793. var SimpleResult = {
  1794. fromResult: fromResult$1,
  1795. toResult: toResult$1,
  1796. svalue: svalue,
  1797. partition: partition$2,
  1798. serror: serror,
  1799. bind: bind$1,
  1800. bindError: bindError,
  1801. map: map,
  1802. mapError: mapError,
  1803. fold: fold$1
  1804. };
  1805. var field$2 = function (key, newKey, presence, prop) {
  1806. return {
  1807. tag: 'field',
  1808. key: key,
  1809. newKey: newKey,
  1810. presence: presence,
  1811. prop: prop
  1812. };
  1813. };
  1814. var customField$1 = function (newKey, instantiator) {
  1815. return {
  1816. tag: 'custom',
  1817. newKey: newKey,
  1818. instantiator: instantiator
  1819. };
  1820. };
  1821. var fold = function (value, ifField, ifCustom) {
  1822. switch (value.tag) {
  1823. case 'field':
  1824. return ifField(value.key, value.newKey, value.presence, value.prop);
  1825. case 'custom':
  1826. return ifCustom(value.newKey, value.instantiator);
  1827. }
  1828. };
  1829. var shallow$1 = function (old, nu) {
  1830. return nu;
  1831. };
  1832. var deep = function (old, nu) {
  1833. var bothObjects = isObject(old) && isObject(nu);
  1834. return bothObjects ? deepMerge(old, nu) : nu;
  1835. };
  1836. var baseMerge = function (merger) {
  1837. return function () {
  1838. var objects = [];
  1839. for (var _i = 0; _i < arguments.length; _i++) {
  1840. objects[_i] = arguments[_i];
  1841. }
  1842. if (objects.length === 0) {
  1843. throw new Error('Can\'t merge zero objects');
  1844. }
  1845. var ret = {};
  1846. for (var j = 0; j < objects.length; j++) {
  1847. var curObject = objects[j];
  1848. for (var key in curObject) {
  1849. if (has$2(curObject, key)) {
  1850. ret[key] = merger(ret[key], curObject[key]);
  1851. }
  1852. }
  1853. }
  1854. return ret;
  1855. };
  1856. };
  1857. var deepMerge = baseMerge(deep);
  1858. var merge$1 = baseMerge(shallow$1);
  1859. var required$2 = function () {
  1860. return {
  1861. tag: 'required',
  1862. process: {}
  1863. };
  1864. };
  1865. var defaultedThunk = function (fallbackThunk) {
  1866. return {
  1867. tag: 'defaultedThunk',
  1868. process: fallbackThunk
  1869. };
  1870. };
  1871. var defaulted$1 = function (fallback) {
  1872. return defaultedThunk(constant$1(fallback));
  1873. };
  1874. var asOption = function () {
  1875. return {
  1876. tag: 'option',
  1877. process: {}
  1878. };
  1879. };
  1880. var mergeWithThunk = function (baseThunk) {
  1881. return {
  1882. tag: 'mergeWithThunk',
  1883. process: baseThunk
  1884. };
  1885. };
  1886. var mergeWith = function (base) {
  1887. return mergeWithThunk(constant$1(base));
  1888. };
  1889. var mergeValues$1 = function (values, base) {
  1890. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1891. };
  1892. var mergeErrors$1 = function (errors) {
  1893. return compose(SimpleResult.serror, flatten)(errors);
  1894. };
  1895. var consolidateObj = function (objects, base) {
  1896. var partition = SimpleResult.partition(objects);
  1897. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1898. };
  1899. var consolidateArr = function (objects) {
  1900. var partitions = SimpleResult.partition(objects);
  1901. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1902. };
  1903. var ResultCombine = {
  1904. consolidateObj: consolidateObj,
  1905. consolidateArr: consolidateArr
  1906. };
  1907. var formatObj = function (input) {
  1908. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1909. };
  1910. var formatErrors = function (errors) {
  1911. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1912. path: [],
  1913. getErrorInfo: constant$1('... (only showing first ten failures)')
  1914. }]) : errors;
  1915. return map$2(es, function (e) {
  1916. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1917. });
  1918. };
  1919. var nu$a = function (path, getErrorInfo) {
  1920. return SimpleResult.serror([{
  1921. path: path,
  1922. getErrorInfo: getErrorInfo
  1923. }]);
  1924. };
  1925. var missingRequired = function (path, key, obj) {
  1926. return nu$a(path, function () {
  1927. return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  1928. });
  1929. };
  1930. var missingKey = function (path, key) {
  1931. return nu$a(path, function () {
  1932. return 'Choice schema did not contain choice key: "' + key + '"';
  1933. });
  1934. };
  1935. var missingBranch = function (path, branches, branch) {
  1936. return nu$a(path, function () {
  1937. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1938. });
  1939. };
  1940. var unsupportedFields = function (path, unsupported) {
  1941. return nu$a(path, function () {
  1942. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1943. });
  1944. };
  1945. var custom = function (path, err) {
  1946. return nu$a(path, constant$1(err));
  1947. };
  1948. var value$2 = function (validator) {
  1949. var extract = function (path, val) {
  1950. return SimpleResult.bindError(validator(val), function (err) {
  1951. return custom(path, err);
  1952. });
  1953. };
  1954. var toString = constant$1('val');
  1955. return {
  1956. extract: extract,
  1957. toString: toString
  1958. };
  1959. };
  1960. var anyValue$1 = value$2(SimpleResult.svalue);
  1961. var requiredAccess = function (path, obj, key, bundle) {
  1962. return get$e(obj, key).fold(function () {
  1963. return missingRequired(path, key, obj);
  1964. }, bundle);
  1965. };
  1966. var fallbackAccess = function (obj, key, fallback, bundle) {
  1967. var v = get$e(obj, key).getOrThunk(function () {
  1968. return fallback(obj);
  1969. });
  1970. return bundle(v);
  1971. };
  1972. var optionAccess = function (obj, key, bundle) {
  1973. return bundle(get$e(obj, key));
  1974. };
  1975. var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  1976. var opt = get$e(obj, key).map(function (val) {
  1977. return val === true ? fallback(obj) : val;
  1978. });
  1979. return bundle(opt);
  1980. };
  1981. var extractField = function (field, path, obj, key, prop) {
  1982. var bundle = function (av) {
  1983. return prop.extract(path.concat([key]), av);
  1984. };
  1985. var bundleAsOption = function (optValue) {
  1986. return optValue.fold(function () {
  1987. return SimpleResult.svalue(Optional.none());
  1988. }, function (ov) {
  1989. var result = prop.extract(path.concat([key]), ov);
  1990. return SimpleResult.map(result, Optional.some);
  1991. });
  1992. };
  1993. switch (field.tag) {
  1994. case 'required':
  1995. return requiredAccess(path, obj, key, bundle);
  1996. case 'defaultedThunk':
  1997. return fallbackAccess(obj, key, field.process, bundle);
  1998. case 'option':
  1999. return optionAccess(obj, key, bundleAsOption);
  2000. case 'defaultedOptionThunk':
  2001. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  2002. case 'mergeWithThunk': {
  2003. return fallbackAccess(obj, key, constant$1({}), function (v) {
  2004. var result = deepMerge(field.process(obj), v);
  2005. return bundle(result);
  2006. });
  2007. }
  2008. }
  2009. };
  2010. var extractFields = function (path, obj, fields) {
  2011. var success = {};
  2012. var errors = [];
  2013. for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  2014. var field = fields_1[_i];
  2015. fold(field, function (key, newKey, presence, prop) {
  2016. var result = extractField(presence, path, obj, key, prop);
  2017. SimpleResult.fold(result, function (err) {
  2018. errors.push.apply(errors, err);
  2019. }, function (res) {
  2020. success[newKey] = res;
  2021. });
  2022. }, function (newKey, instantiator) {
  2023. success[newKey] = instantiator(obj);
  2024. });
  2025. }
  2026. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  2027. };
  2028. var valueThunk = function (getDelegate) {
  2029. var extract = function (path, val) {
  2030. return getDelegate().extract(path, val);
  2031. };
  2032. var toString = function () {
  2033. return getDelegate().toString();
  2034. };
  2035. return {
  2036. extract: extract,
  2037. toString: toString
  2038. };
  2039. };
  2040. var getSetKeys = function (obj) {
  2041. return keys(filter$1(obj, isNonNullable));
  2042. };
  2043. var objOfOnly = function (fields) {
  2044. var delegate = objOf(fields);
  2045. var fieldNames = foldr(fields, function (acc, value) {
  2046. return fold(value, function (key) {
  2047. var _a;
  2048. return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  2049. }, constant$1(acc));
  2050. }, {});
  2051. var extract = function (path, o) {
  2052. var keys = isBoolean(o) ? [] : getSetKeys(o);
  2053. var extra = filter$2(keys, function (k) {
  2054. return !hasNonNullableKey(fieldNames, k);
  2055. });
  2056. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  2057. };
  2058. return {
  2059. extract: extract,
  2060. toString: delegate.toString
  2061. };
  2062. };
  2063. var objOf = function (values) {
  2064. var extract = function (path, o) {
  2065. return extractFields(path, o, values);
  2066. };
  2067. var toString = function () {
  2068. var fieldStrings = map$2(values, function (value) {
  2069. return fold(value, function (key, _okey, _presence, prop) {
  2070. return key + ' -> ' + prop.toString();
  2071. }, function (newKey, _instantiator) {
  2072. return 'state(' + newKey + ')';
  2073. });
  2074. });
  2075. return 'obj{\n' + fieldStrings.join('\n') + '}';
  2076. };
  2077. return {
  2078. extract: extract,
  2079. toString: toString
  2080. };
  2081. };
  2082. var arrOf = function (prop) {
  2083. var extract = function (path, array) {
  2084. var results = map$2(array, function (a, i) {
  2085. return prop.extract(path.concat(['[' + i + ']']), a);
  2086. });
  2087. return ResultCombine.consolidateArr(results);
  2088. };
  2089. var toString = function () {
  2090. return 'array(' + prop.toString() + ')';
  2091. };
  2092. return {
  2093. extract: extract,
  2094. toString: toString
  2095. };
  2096. };
  2097. var oneOf = function (props) {
  2098. var extract = function (path, val) {
  2099. var errors = [];
  2100. for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  2101. var prop = props_1[_i];
  2102. var res = prop.extract(path, val);
  2103. if (res.stype === SimpleResultType.Value) {
  2104. return res;
  2105. }
  2106. errors.push(res);
  2107. }
  2108. return ResultCombine.consolidateArr(errors);
  2109. };
  2110. var toString = function () {
  2111. return 'oneOf(' + map$2(props, function (prop) {
  2112. return prop.toString();
  2113. }).join(', ') + ')';
  2114. };
  2115. return {
  2116. extract: extract,
  2117. toString: toString
  2118. };
  2119. };
  2120. var setOf$1 = function (validator, prop) {
  2121. var validateKeys = function (path, keys) {
  2122. return arrOf(value$2(validator)).extract(path, keys);
  2123. };
  2124. var extract = function (path, o) {
  2125. var keys$1 = keys(o);
  2126. var validatedKeys = validateKeys(path, keys$1);
  2127. return SimpleResult.bind(validatedKeys, function (validKeys) {
  2128. var schema = map$2(validKeys, function (vk) {
  2129. return field$2(vk, vk, required$2(), prop);
  2130. });
  2131. return objOf(schema).extract(path, o);
  2132. });
  2133. };
  2134. var toString = function () {
  2135. return 'setOf(' + prop.toString() + ')';
  2136. };
  2137. return {
  2138. extract: extract,
  2139. toString: toString
  2140. };
  2141. };
  2142. var thunk = function (_desc, processor) {
  2143. var getP = cached(processor);
  2144. var extract = function (path, val) {
  2145. return getP().extract(path, val);
  2146. };
  2147. var toString = function () {
  2148. return getP().toString();
  2149. };
  2150. return {
  2151. extract: extract,
  2152. toString: toString
  2153. };
  2154. };
  2155. var arrOfObj = compose(arrOf, objOf);
  2156. var anyValue = constant$1(anyValue$1);
  2157. var typedValue = function (validator, expectedType) {
  2158. return value$2(function (a) {
  2159. var actualType = typeof a;
  2160. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  2161. });
  2162. };
  2163. var number = typedValue(isNumber, 'number');
  2164. var string = typedValue(isString, 'string');
  2165. var boolean = typedValue(isBoolean, 'boolean');
  2166. var functionProcessor = typedValue(isFunction, 'function');
  2167. var isPostMessageable = function (val) {
  2168. if (Object(val) !== val) {
  2169. return true;
  2170. }
  2171. switch ({}.toString.call(val).slice(8, -1)) {
  2172. case 'Boolean':
  2173. case 'Number':
  2174. case 'String':
  2175. case 'Date':
  2176. case 'RegExp':
  2177. case 'Blob':
  2178. case 'FileList':
  2179. case 'ImageData':
  2180. case 'ImageBitmap':
  2181. case 'ArrayBuffer':
  2182. return true;
  2183. case 'Array':
  2184. case 'Object':
  2185. return Object.keys(val).every(function (prop) {
  2186. return isPostMessageable(val[prop]);
  2187. });
  2188. default:
  2189. return false;
  2190. }
  2191. };
  2192. var postMessageable = value$2(function (a) {
  2193. if (isPostMessageable(a)) {
  2194. return SimpleResult.svalue(a);
  2195. } else {
  2196. return SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  2197. }
  2198. });
  2199. var chooseFrom = function (path, input, branches, ch) {
  2200. var fields = get$e(branches, ch);
  2201. return fields.fold(function () {
  2202. return missingBranch(path, branches, ch);
  2203. }, function (vp) {
  2204. return vp.extract(path.concat(['branch: ' + ch]), input);
  2205. });
  2206. };
  2207. var choose$2 = function (key, branches) {
  2208. var extract = function (path, input) {
  2209. var choice = get$e(input, key);
  2210. return choice.fold(function () {
  2211. return missingKey(path, key);
  2212. }, function (chosen) {
  2213. return chooseFrom(path, input, branches, chosen);
  2214. });
  2215. };
  2216. var toString = function () {
  2217. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  2218. };
  2219. return {
  2220. extract: extract,
  2221. toString: toString
  2222. };
  2223. };
  2224. var arrOfVal = function () {
  2225. return arrOf(anyValue$1);
  2226. };
  2227. var valueOf = function (validator) {
  2228. return value$2(function (v) {
  2229. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  2230. });
  2231. };
  2232. var setOf = function (validator, prop) {
  2233. return setOf$1(function (v) {
  2234. return SimpleResult.fromResult(validator(v));
  2235. }, prop);
  2236. };
  2237. var extractValue = function (label, prop, obj) {
  2238. var res = prop.extract([label], obj);
  2239. return SimpleResult.mapError(res, function (errs) {
  2240. return {
  2241. input: obj,
  2242. errors: errs
  2243. };
  2244. });
  2245. };
  2246. var asRaw = function (label, prop, obj) {
  2247. return SimpleResult.toResult(extractValue(label, prop, obj));
  2248. };
  2249. var getOrDie = function (extraction) {
  2250. return extraction.fold(function (errInfo) {
  2251. throw new Error(formatError(errInfo));
  2252. }, identity$1);
  2253. };
  2254. var asRawOrDie$1 = function (label, prop, obj) {
  2255. return getOrDie(asRaw(label, prop, obj));
  2256. };
  2257. var formatError = function (errInfo) {
  2258. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  2259. };
  2260. var choose$1 = function (key, branches) {
  2261. return choose$2(key, map$1(branches, objOf));
  2262. };
  2263. var thunkOf = function (desc, schema) {
  2264. return thunk(desc, schema);
  2265. };
  2266. var field$1 = field$2;
  2267. var customField = customField$1;
  2268. var validateEnum = function (values) {
  2269. return valueOf(function (value) {
  2270. return contains$2(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  2271. });
  2272. };
  2273. var required$1 = function (key) {
  2274. return field$1(key, key, required$2(), anyValue());
  2275. };
  2276. var requiredOf = function (key, schema) {
  2277. return field$1(key, key, required$2(), schema);
  2278. };
  2279. var requiredNumber = function (key) {
  2280. return requiredOf(key, number);
  2281. };
  2282. var requiredString = function (key) {
  2283. return requiredOf(key, string);
  2284. };
  2285. var requiredStringEnum = function (key, values) {
  2286. return field$1(key, key, required$2(), validateEnum(values));
  2287. };
  2288. var requiredBoolean = function (key) {
  2289. return requiredOf(key, boolean);
  2290. };
  2291. var requiredFunction = function (key) {
  2292. return requiredOf(key, functionProcessor);
  2293. };
  2294. var forbid = function (key, message) {
  2295. return field$1(key, key, asOption(), value$2(function (_v) {
  2296. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  2297. }));
  2298. };
  2299. var requiredObjOf = function (key, objSchema) {
  2300. return field$1(key, key, required$2(), objOf(objSchema));
  2301. };
  2302. var requiredArrayOfObj = function (key, objFields) {
  2303. return field$1(key, key, required$2(), arrOfObj(objFields));
  2304. };
  2305. var requiredArrayOf = function (key, schema) {
  2306. return field$1(key, key, required$2(), arrOf(schema));
  2307. };
  2308. var option = function (key) {
  2309. return field$1(key, key, asOption(), anyValue());
  2310. };
  2311. var optionOf = function (key, schema) {
  2312. return field$1(key, key, asOption(), schema);
  2313. };
  2314. var optionNumber = function (key) {
  2315. return optionOf(key, number);
  2316. };
  2317. var optionString = function (key) {
  2318. return optionOf(key, string);
  2319. };
  2320. var optionFunction = function (key) {
  2321. return optionOf(key, functionProcessor);
  2322. };
  2323. var optionArrayOf = function (key, schema) {
  2324. return optionOf(key, arrOf(schema));
  2325. };
  2326. var optionObjOf = function (key, objSchema) {
  2327. return optionOf(key, objOf(objSchema));
  2328. };
  2329. var optionObjOfOnly = function (key, objSchema) {
  2330. return optionOf(key, objOfOnly(objSchema));
  2331. };
  2332. var defaulted = function (key, fallback) {
  2333. return field$1(key, key, defaulted$1(fallback), anyValue());
  2334. };
  2335. var defaultedOf = function (key, fallback, schema) {
  2336. return field$1(key, key, defaulted$1(fallback), schema);
  2337. };
  2338. var defaultedNumber = function (key, fallback) {
  2339. return defaultedOf(key, fallback, number);
  2340. };
  2341. var defaultedString = function (key, fallback) {
  2342. return defaultedOf(key, fallback, string);
  2343. };
  2344. var defaultedStringEnum = function (key, fallback, values) {
  2345. return defaultedOf(key, fallback, validateEnum(values));
  2346. };
  2347. var defaultedBoolean = function (key, fallback) {
  2348. return defaultedOf(key, fallback, boolean);
  2349. };
  2350. var defaultedFunction = function (key, fallback) {
  2351. return defaultedOf(key, fallback, functionProcessor);
  2352. };
  2353. var defaultedPostMsg = function (key, fallback) {
  2354. return defaultedOf(key, fallback, postMessageable);
  2355. };
  2356. var defaultedArrayOf = function (key, fallback, schema) {
  2357. return defaultedOf(key, fallback, arrOf(schema));
  2358. };
  2359. var defaultedObjOf = function (key, fallback, objSchema) {
  2360. return defaultedOf(key, fallback, objOf(objSchema));
  2361. };
  2362. var Cell = function (initial) {
  2363. var value = initial;
  2364. var get = function () {
  2365. return value;
  2366. };
  2367. var set = function (v) {
  2368. value = v;
  2369. };
  2370. return {
  2371. get: get,
  2372. set: set
  2373. };
  2374. };
  2375. var generate$7 = function (cases) {
  2376. if (!isArray(cases)) {
  2377. throw new Error('cases must be an array');
  2378. }
  2379. if (cases.length === 0) {
  2380. throw new Error('there must be at least one case');
  2381. }
  2382. var constructors = [];
  2383. var adt = {};
  2384. each$1(cases, function (acase, count) {
  2385. var keys$1 = keys(acase);
  2386. if (keys$1.length !== 1) {
  2387. throw new Error('one and only one name per case');
  2388. }
  2389. var key = keys$1[0];
  2390. var value = acase[key];
  2391. if (adt[key] !== undefined) {
  2392. throw new Error('duplicate key detected:' + key);
  2393. } else if (key === 'cata') {
  2394. throw new Error('cannot have a case named cata (sorry)');
  2395. } else if (!isArray(value)) {
  2396. throw new Error('case arguments must be an array');
  2397. }
  2398. constructors.push(key);
  2399. adt[key] = function () {
  2400. var args = [];
  2401. for (var _i = 0; _i < arguments.length; _i++) {
  2402. args[_i] = arguments[_i];
  2403. }
  2404. var argLength = args.length;
  2405. if (argLength !== value.length) {
  2406. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  2407. }
  2408. var match = function (branches) {
  2409. var branchKeys = keys(branches);
  2410. if (constructors.length !== branchKeys.length) {
  2411. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  2412. }
  2413. var allReqd = forall(constructors, function (reqKey) {
  2414. return contains$2(branchKeys, reqKey);
  2415. });
  2416. if (!allReqd) {
  2417. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  2418. }
  2419. return branches[key].apply(null, args);
  2420. };
  2421. return {
  2422. fold: function () {
  2423. var foldArgs = [];
  2424. for (var _i = 0; _i < arguments.length; _i++) {
  2425. foldArgs[_i] = arguments[_i];
  2426. }
  2427. if (foldArgs.length !== cases.length) {
  2428. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  2429. }
  2430. var target = foldArgs[count];
  2431. return target.apply(null, args);
  2432. },
  2433. match: match,
  2434. log: function (label) {
  2435. console.log(label, {
  2436. constructors: constructors,
  2437. constructor: key,
  2438. params: args
  2439. });
  2440. }
  2441. };
  2442. };
  2443. });
  2444. return adt;
  2445. };
  2446. var Adt = { generate: generate$7 };
  2447. Adt.generate([
  2448. {
  2449. bothErrors: [
  2450. 'error1',
  2451. 'error2'
  2452. ]
  2453. },
  2454. {
  2455. firstError: [
  2456. 'error1',
  2457. 'value2'
  2458. ]
  2459. },
  2460. {
  2461. secondError: [
  2462. 'value1',
  2463. 'error2'
  2464. ]
  2465. },
  2466. {
  2467. bothValues: [
  2468. 'value1',
  2469. 'value2'
  2470. ]
  2471. }
  2472. ]);
  2473. var partition$1 = function (results) {
  2474. var errors = [];
  2475. var values = [];
  2476. each$1(results, function (result) {
  2477. result.fold(function (err) {
  2478. errors.push(err);
  2479. }, function (value) {
  2480. values.push(value);
  2481. });
  2482. });
  2483. return {
  2484. errors: errors,
  2485. values: values
  2486. };
  2487. };
  2488. var exclude$1 = function (obj, fields) {
  2489. var r = {};
  2490. each(obj, function (v, k) {
  2491. if (!contains$2(fields, k)) {
  2492. r[k] = v;
  2493. }
  2494. });
  2495. return r;
  2496. };
  2497. var wrap$2 = function (key, value) {
  2498. var _a;
  2499. return _a = {}, _a[key] = value, _a;
  2500. };
  2501. var wrapAll$1 = function (keyvalues) {
  2502. var r = {};
  2503. each$1(keyvalues, function (kv) {
  2504. r[kv.key] = kv.value;
  2505. });
  2506. return r;
  2507. };
  2508. var exclude = function (obj, fields) {
  2509. return exclude$1(obj, fields);
  2510. };
  2511. var wrap$1 = function (key, value) {
  2512. return wrap$2(key, value);
  2513. };
  2514. var wrapAll = function (keyvalues) {
  2515. return wrapAll$1(keyvalues);
  2516. };
  2517. var mergeValues = function (values, base) {
  2518. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  2519. };
  2520. var mergeErrors = function (errors) {
  2521. return Result.error(flatten(errors));
  2522. };
  2523. var consolidate = function (objs, base) {
  2524. var partitions = partition$1(objs);
  2525. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2526. };
  2527. var ensureIsRoot = function (isRoot) {
  2528. return isFunction(isRoot) ? isRoot : never;
  2529. };
  2530. var ancestor$2 = function (scope, transform, isRoot) {
  2531. var element = scope.dom;
  2532. var stop = ensureIsRoot(isRoot);
  2533. while (element.parentNode) {
  2534. element = element.parentNode;
  2535. var el = SugarElement.fromDom(element);
  2536. var transformed = transform(el);
  2537. if (transformed.isSome()) {
  2538. return transformed;
  2539. } else if (stop(el)) {
  2540. break;
  2541. }
  2542. }
  2543. return Optional.none();
  2544. };
  2545. var closest$4 = function (scope, transform, isRoot) {
  2546. var current = transform(scope);
  2547. var stop = ensureIsRoot(isRoot);
  2548. return current.orThunk(function () {
  2549. return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  2550. });
  2551. };
  2552. var isSource = function (component, simulatedEvent) {
  2553. return eq(component.element, simulatedEvent.event.target);
  2554. };
  2555. var defaultEventHandler = {
  2556. can: always,
  2557. abort: never,
  2558. run: noop
  2559. };
  2560. var nu$9 = function (parts) {
  2561. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2562. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2563. }
  2564. return __assign(__assign({}, defaultEventHandler), parts);
  2565. };
  2566. var all$2 = function (handlers, f) {
  2567. return function () {
  2568. var args = [];
  2569. for (var _i = 0; _i < arguments.length; _i++) {
  2570. args[_i] = arguments[_i];
  2571. }
  2572. return foldl(handlers, function (acc, handler) {
  2573. return acc && f(handler).apply(undefined, args);
  2574. }, true);
  2575. };
  2576. };
  2577. var any = function (handlers, f) {
  2578. return function () {
  2579. var args = [];
  2580. for (var _i = 0; _i < arguments.length; _i++) {
  2581. args[_i] = arguments[_i];
  2582. }
  2583. return foldl(handlers, function (acc, handler) {
  2584. return acc || f(handler).apply(undefined, args);
  2585. }, false);
  2586. };
  2587. };
  2588. var read$2 = function (handler) {
  2589. return isFunction(handler) ? {
  2590. can: always,
  2591. abort: never,
  2592. run: handler
  2593. } : handler;
  2594. };
  2595. var fuse$1 = function (handlers) {
  2596. var can = all$2(handlers, function (handler) {
  2597. return handler.can;
  2598. });
  2599. var abort = any(handlers, function (handler) {
  2600. return handler.abort;
  2601. });
  2602. var run = function () {
  2603. var args = [];
  2604. for (var _i = 0; _i < arguments.length; _i++) {
  2605. args[_i] = arguments[_i];
  2606. }
  2607. each$1(handlers, function (handler) {
  2608. handler.run.apply(undefined, args);
  2609. });
  2610. };
  2611. return {
  2612. can: can,
  2613. abort: abort,
  2614. run: run
  2615. };
  2616. };
  2617. var constant = constant$1;
  2618. var touchstart = constant('touchstart');
  2619. var touchmove = constant('touchmove');
  2620. var touchend = constant('touchend');
  2621. var touchcancel = constant('touchcancel');
  2622. var mousedown = constant('mousedown');
  2623. var mousemove = constant('mousemove');
  2624. var mouseout = constant('mouseout');
  2625. var mouseup = constant('mouseup');
  2626. var mouseover = constant('mouseover');
  2627. var focusin = constant('focusin');
  2628. var focusout = constant('focusout');
  2629. var keydown = constant('keydown');
  2630. var keyup = constant('keyup');
  2631. var input = constant('input');
  2632. var change = constant('change');
  2633. var click = constant('click');
  2634. var transitioncancel = constant('transitioncancel');
  2635. var transitionend = constant('transitionend');
  2636. var transitionstart = constant('transitionstart');
  2637. var selectstart = constant('selectstart');
  2638. var prefixName = function (name) {
  2639. return constant$1('alloy.' + name);
  2640. };
  2641. var alloy = { tap: prefixName('tap') };
  2642. var focus$4 = prefixName('focus');
  2643. var postBlur = prefixName('blur.post');
  2644. var postPaste = prefixName('paste.post');
  2645. var receive = prefixName('receive');
  2646. var execute$5 = prefixName('execute');
  2647. var focusItem = prefixName('focus.item');
  2648. var tap = alloy.tap;
  2649. var longpress = prefixName('longpress');
  2650. var sandboxClose = prefixName('sandbox.close');
  2651. var typeaheadCancel = prefixName('typeahead.cancel');
  2652. var systemInit = prefixName('system.init');
  2653. var documentTouchmove = prefixName('system.touchmove');
  2654. var documentTouchend = prefixName('system.touchend');
  2655. var windowScroll = prefixName('system.scroll');
  2656. var windowResize = prefixName('system.resize');
  2657. var attachedToDom = prefixName('system.attached');
  2658. var detachedFromDom = prefixName('system.detached');
  2659. var dismissRequested = prefixName('system.dismissRequested');
  2660. var repositionRequested = prefixName('system.repositionRequested');
  2661. var focusShifted = prefixName('focusmanager.shifted');
  2662. var slotVisibility = prefixName('slotcontainer.visibility');
  2663. var changeTab = prefixName('change.tab');
  2664. var dismissTab = prefixName('dismiss.tab');
  2665. var highlight$1 = prefixName('highlight');
  2666. var dehighlight$1 = prefixName('dehighlight');
  2667. var emit = function (component, event) {
  2668. dispatchWith(component, component.element, event, {});
  2669. };
  2670. var emitWith = function (component, event, properties) {
  2671. dispatchWith(component, component.element, event, properties);
  2672. };
  2673. var emitExecute = function (component) {
  2674. emit(component, execute$5());
  2675. };
  2676. var dispatch = function (component, target, event) {
  2677. dispatchWith(component, target, event, {});
  2678. };
  2679. var dispatchWith = function (component, target, event, properties) {
  2680. var data = __assign({ target: target }, properties);
  2681. component.getSystem().triggerEvent(event, target, data);
  2682. };
  2683. var dispatchEvent = function (component, target, event, simulatedEvent) {
  2684. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  2685. };
  2686. var derive$2 = function (configs) {
  2687. return wrapAll(configs);
  2688. };
  2689. var abort = function (name, predicate) {
  2690. return {
  2691. key: name,
  2692. value: nu$9({ abort: predicate })
  2693. };
  2694. };
  2695. var can = function (name, predicate) {
  2696. return {
  2697. key: name,
  2698. value: nu$9({ can: predicate })
  2699. };
  2700. };
  2701. var preventDefault = function (name) {
  2702. return {
  2703. key: name,
  2704. value: nu$9({
  2705. run: function (component, simulatedEvent) {
  2706. simulatedEvent.event.prevent();
  2707. }
  2708. })
  2709. };
  2710. };
  2711. var run$1 = function (name, handler) {
  2712. return {
  2713. key: name,
  2714. value: nu$9({ run: handler })
  2715. };
  2716. };
  2717. var runActionExtra = function (name, action, extra) {
  2718. return {
  2719. key: name,
  2720. value: nu$9({
  2721. run: function (component, simulatedEvent) {
  2722. action.apply(undefined, [
  2723. component,
  2724. simulatedEvent
  2725. ].concat(extra));
  2726. }
  2727. })
  2728. };
  2729. };
  2730. var runOnName = function (name) {
  2731. return function (handler) {
  2732. return run$1(name, handler);
  2733. };
  2734. };
  2735. var runOnSourceName = function (name) {
  2736. return function (handler) {
  2737. return {
  2738. key: name,
  2739. value: nu$9({
  2740. run: function (component, simulatedEvent) {
  2741. if (isSource(component, simulatedEvent)) {
  2742. handler(component, simulatedEvent);
  2743. }
  2744. }
  2745. })
  2746. };
  2747. };
  2748. };
  2749. var redirectToUid = function (name, uid) {
  2750. return run$1(name, function (component, simulatedEvent) {
  2751. component.getSystem().getByUid(uid).each(function (redirectee) {
  2752. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2753. });
  2754. });
  2755. };
  2756. var redirectToPart = function (name, detail, partName) {
  2757. var uid = detail.partUids[partName];
  2758. return redirectToUid(name, uid);
  2759. };
  2760. var runWithTarget = function (name, f) {
  2761. return run$1(name, function (component, simulatedEvent) {
  2762. var ev = simulatedEvent.event;
  2763. var target = component.getSystem().getByDom(ev.target).getOrThunk(function () {
  2764. var closest = closest$4(ev.target, function (el) {
  2765. return component.getSystem().getByDom(el).toOptional();
  2766. }, never);
  2767. return closest.getOr(component);
  2768. });
  2769. f(component, target, simulatedEvent);
  2770. });
  2771. };
  2772. var cutter = function (name) {
  2773. return run$1(name, function (component, simulatedEvent) {
  2774. simulatedEvent.cut();
  2775. });
  2776. };
  2777. var stopper = function (name) {
  2778. return run$1(name, function (component, simulatedEvent) {
  2779. simulatedEvent.stop();
  2780. });
  2781. };
  2782. var runOnSource = function (name, f) {
  2783. return runOnSourceName(name)(f);
  2784. };
  2785. var runOnAttached = runOnSourceName(attachedToDom());
  2786. var runOnDetached = runOnSourceName(detachedFromDom());
  2787. var runOnInit = runOnSourceName(systemInit());
  2788. var runOnExecute$1 = runOnName(execute$5());
  2789. var fromHtml$1 = function (html, scope) {
  2790. var doc = scope || document;
  2791. var div = doc.createElement('div');
  2792. div.innerHTML = html;
  2793. return children(SugarElement.fromDom(div));
  2794. };
  2795. var get$7 = function (element) {
  2796. return element.dom.innerHTML;
  2797. };
  2798. var set$5 = function (element, content) {
  2799. var owner = owner$4(element);
  2800. var docDom = owner.dom;
  2801. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2802. var contentElements = fromHtml$1(content, docDom);
  2803. append$1(fragment, contentElements);
  2804. empty(element);
  2805. append$2(element, fragment);
  2806. };
  2807. var getOuter = function (element) {
  2808. var container = SugarElement.fromTag('div');
  2809. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2810. append$2(container, clone);
  2811. return get$7(container);
  2812. };
  2813. var clone$1 = function (original, isDeep) {
  2814. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2815. };
  2816. var shallow = function (original) {
  2817. return clone$1(original, false);
  2818. };
  2819. var getHtml = function (element) {
  2820. if (isShadowRoot(element)) {
  2821. return '#shadow-root';
  2822. } else {
  2823. var clone = shallow(element);
  2824. return getOuter(clone);
  2825. }
  2826. };
  2827. var element = function (elem) {
  2828. return getHtml(elem);
  2829. };
  2830. var isRecursive = function (component, originator, target) {
  2831. return eq(originator, component.element) && !eq(originator, target);
  2832. };
  2833. var events$i = derive$2([can(focus$4(), function (component, simulatedEvent) {
  2834. var event = simulatedEvent.event;
  2835. var originator = event.originator;
  2836. var target = event.target;
  2837. if (isRecursive(component, originator, target)) {
  2838. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  2839. return false;
  2840. } else {
  2841. return true;
  2842. }
  2843. })]);
  2844. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2845. __proto__: null,
  2846. events: events$i
  2847. });
  2848. var unique = 0;
  2849. var generate$6 = function (prefix) {
  2850. var date = new Date();
  2851. var time = date.getTime();
  2852. var random = Math.floor(Math.random() * 1000000000);
  2853. unique++;
  2854. return prefix + '_' + random + unique + String(time);
  2855. };
  2856. var prefix$1 = constant$1('alloy-id-');
  2857. var idAttr$1 = constant$1('data-alloy-id');
  2858. var prefix = prefix$1();
  2859. var idAttr = idAttr$1();
  2860. var write = function (label, elem) {
  2861. var id = generate$6(prefix + label);
  2862. writeOnly(elem, id);
  2863. return id;
  2864. };
  2865. var writeOnly = function (elem, uid) {
  2866. Object.defineProperty(elem.dom, idAttr, {
  2867. value: uid,
  2868. writable: true
  2869. });
  2870. };
  2871. var read$1 = function (elem) {
  2872. var id = isElement$2(elem) ? elem.dom[idAttr] : null;
  2873. return Optional.from(id);
  2874. };
  2875. var generate$5 = function (prefix) {
  2876. return generate$6(prefix);
  2877. };
  2878. var make$8 = identity$1;
  2879. var NoContextApi = function (getComp) {
  2880. var getMessage = function (event) {
  2881. return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  2882. };
  2883. var fail = function (event) {
  2884. return function () {
  2885. throw new Error(getMessage(event));
  2886. };
  2887. };
  2888. var warn = function (event) {
  2889. return function () {
  2890. console.warn(getMessage(event));
  2891. };
  2892. };
  2893. return {
  2894. debugInfo: constant$1('fake'),
  2895. triggerEvent: warn('triggerEvent'),
  2896. triggerFocus: warn('triggerFocus'),
  2897. triggerEscape: warn('triggerEscape'),
  2898. broadcast: warn('broadcast'),
  2899. broadcastOn: warn('broadcastOn'),
  2900. broadcastEvent: warn('broadcastEvent'),
  2901. build: fail('build'),
  2902. addToWorld: fail('addToWorld'),
  2903. removeFromWorld: fail('removeFromWorld'),
  2904. addToGui: fail('addToGui'),
  2905. removeFromGui: fail('removeFromGui'),
  2906. getByUid: fail('getByUid'),
  2907. getByDom: fail('getByDom'),
  2908. isConnected: never
  2909. };
  2910. };
  2911. var singleton$1 = NoContextApi();
  2912. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2913. var delegate = apiFunction.toString();
  2914. var endIndex = delegate.indexOf(')') + 1;
  2915. var openBracketIndex = delegate.indexOf('(');
  2916. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2917. f.toFunctionAnnotation = function () {
  2918. return {
  2919. name: apiName,
  2920. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2921. };
  2922. };
  2923. return f;
  2924. };
  2925. var cleanParameters = function (parameters) {
  2926. return map$2(parameters, function (p) {
  2927. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2928. });
  2929. };
  2930. var markAsExtraApi = function (f, extraName) {
  2931. var delegate = f.toString();
  2932. var endIndex = delegate.indexOf(')') + 1;
  2933. var openBracketIndex = delegate.indexOf('(');
  2934. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2935. f.toFunctionAnnotation = function () {
  2936. return {
  2937. name: extraName,
  2938. parameters: cleanParameters(parameters)
  2939. };
  2940. };
  2941. return f;
  2942. };
  2943. var markAsSketchApi = function (f, apiFunction) {
  2944. var delegate = apiFunction.toString();
  2945. var endIndex = delegate.indexOf(')') + 1;
  2946. var openBracketIndex = delegate.indexOf('(');
  2947. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2948. f.toFunctionAnnotation = function () {
  2949. return {
  2950. name: 'OVERRIDE',
  2951. parameters: cleanParameters(parameters.slice(1))
  2952. };
  2953. };
  2954. return f;
  2955. };
  2956. var premadeTag = generate$6('alloy-premade');
  2957. var premade$1 = function (comp) {
  2958. return wrap$1(premadeTag, comp);
  2959. };
  2960. var getPremade = function (spec) {
  2961. return get$e(spec, premadeTag);
  2962. };
  2963. var makeApi = function (f) {
  2964. return markAsSketchApi(function (component) {
  2965. var rest = [];
  2966. for (var _i = 1; _i < arguments.length; _i++) {
  2967. rest[_i - 1] = arguments[_i];
  2968. }
  2969. return f.apply(void 0, __spreadArray([
  2970. component.getApis(),
  2971. component
  2972. ], rest, false));
  2973. }, f);
  2974. };
  2975. var NoState = {
  2976. init: function () {
  2977. return nu$8({ readState: constant$1('No State required') });
  2978. }
  2979. };
  2980. var nu$8 = function (spec) {
  2981. return spec;
  2982. };
  2983. var generateFrom$1 = function (spec, all) {
  2984. var schema = map$2(all, function (a) {
  2985. return optionObjOf(a.name(), [
  2986. required$1('config'),
  2987. defaulted('state', NoState)
  2988. ]);
  2989. });
  2990. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2991. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2992. }, identity$1);
  2993. return {
  2994. list: all,
  2995. data: map$1(validated, function (optBlobThunk) {
  2996. var output = optBlobThunk.map(function (blob) {
  2997. return {
  2998. config: blob.config,
  2999. state: blob.state.init(blob.config)
  3000. };
  3001. });
  3002. return constant$1(output);
  3003. })
  3004. };
  3005. };
  3006. var getBehaviours$3 = function (bData) {
  3007. return bData.list;
  3008. };
  3009. var getData$2 = function (bData) {
  3010. return bData.data;
  3011. };
  3012. var byInnerKey = function (data, tuple) {
  3013. var r = {};
  3014. each(data, function (detail, key) {
  3015. each(detail, function (value, indexKey) {
  3016. var chain = get$e(r, indexKey).getOr([]);
  3017. r[indexKey] = chain.concat([tuple(key, value)]);
  3018. });
  3019. });
  3020. return r;
  3021. };
  3022. var nu$7 = function (s) {
  3023. return {
  3024. classes: isUndefined(s.classes) ? [] : s.classes,
  3025. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  3026. styles: isUndefined(s.styles) ? {} : s.styles
  3027. };
  3028. };
  3029. var merge = function (defnA, mod) {
  3030. return __assign(__assign({}, defnA), {
  3031. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  3032. styles: __assign(__assign({}, defnA.styles), mod.styles),
  3033. classes: defnA.classes.concat(mod.classes)
  3034. });
  3035. };
  3036. var combine$2 = function (info, baseMod, behaviours, base) {
  3037. var modsByBehaviour = __assign({}, baseMod);
  3038. each$1(behaviours, function (behaviour) {
  3039. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  3040. });
  3041. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  3042. return {
  3043. name: name,
  3044. modification: modification
  3045. };
  3046. });
  3047. var combineObjects = function (objects) {
  3048. return foldr(objects, function (b, a) {
  3049. return __assign(__assign({}, a.modification), b);
  3050. }, {});
  3051. };
  3052. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  3053. return a.modification.concat(b);
  3054. }, []);
  3055. var combinedAttributes = combineObjects(byAspect.attributes);
  3056. var combinedStyles = combineObjects(byAspect.styles);
  3057. return nu$7({
  3058. classes: combinedClasses,
  3059. attributes: combinedAttributes,
  3060. styles: combinedStyles
  3061. });
  3062. };
  3063. var sortKeys = function (label, keyName, array, order) {
  3064. try {
  3065. var sorted = sort(array, function (a, b) {
  3066. var aKey = a[keyName];
  3067. var bKey = b[keyName];
  3068. var aIndex = order.indexOf(aKey);
  3069. var bIndex = order.indexOf(bKey);
  3070. if (aIndex === -1) {
  3071. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  3072. }
  3073. if (bIndex === -1) {
  3074. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  3075. }
  3076. if (aIndex < bIndex) {
  3077. return -1;
  3078. } else if (bIndex < aIndex) {
  3079. return 1;
  3080. } else {
  3081. return 0;
  3082. }
  3083. });
  3084. return Result.value(sorted);
  3085. } catch (err) {
  3086. return Result.error([err]);
  3087. }
  3088. };
  3089. var uncurried = function (handler, purpose) {
  3090. return {
  3091. handler: handler,
  3092. purpose: purpose
  3093. };
  3094. };
  3095. var curried = function (handler, purpose) {
  3096. return {
  3097. cHandler: handler,
  3098. purpose: purpose
  3099. };
  3100. };
  3101. var curryArgs = function (descHandler, extraArgs) {
  3102. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  3103. };
  3104. var getCurried = function (descHandler) {
  3105. return descHandler.cHandler;
  3106. };
  3107. var behaviourTuple = function (name, handler) {
  3108. return {
  3109. name: name,
  3110. handler: handler
  3111. };
  3112. };
  3113. var nameToHandlers = function (behaviours, info) {
  3114. var r = {};
  3115. each$1(behaviours, function (behaviour) {
  3116. r[behaviour.name()] = behaviour.handlers(info);
  3117. });
  3118. return r;
  3119. };
  3120. var groupByEvents = function (info, behaviours, base) {
  3121. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  3122. return byInnerKey(behaviourEvents, behaviourTuple);
  3123. };
  3124. var combine$1 = function (info, eventOrder, behaviours, base) {
  3125. var byEventName = groupByEvents(info, behaviours, base);
  3126. return combineGroups(byEventName, eventOrder);
  3127. };
  3128. var assemble = function (rawHandler) {
  3129. var handler = read$2(rawHandler);
  3130. return function (component, simulatedEvent) {
  3131. var rest = [];
  3132. for (var _i = 2; _i < arguments.length; _i++) {
  3133. rest[_i - 2] = arguments[_i];
  3134. }
  3135. var args = [
  3136. component,
  3137. simulatedEvent
  3138. ].concat(rest);
  3139. if (handler.abort.apply(undefined, args)) {
  3140. simulatedEvent.stop();
  3141. } else if (handler.can.apply(undefined, args)) {
  3142. handler.run.apply(undefined, args);
  3143. }
  3144. };
  3145. };
  3146. var missingOrderError = function (eventName, tuples) {
  3147. 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) {
  3148. return c.name;
  3149. }), null, 2)]);
  3150. };
  3151. var fuse = function (tuples, eventOrder, eventName) {
  3152. var order = eventOrder[eventName];
  3153. if (!order) {
  3154. return missingOrderError(eventName, tuples);
  3155. } else {
  3156. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  3157. var handlers = map$2(sortedTuples, function (tuple) {
  3158. return tuple.handler;
  3159. });
  3160. return fuse$1(handlers);
  3161. });
  3162. }
  3163. };
  3164. var combineGroups = function (byEventName, eventOrder) {
  3165. var r = mapToArray(byEventName, function (tuples, eventName) {
  3166. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  3167. return combined.map(function (handler) {
  3168. var assembled = assemble(handler);
  3169. var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  3170. return exists(tuples, function (t) {
  3171. return t.name === o;
  3172. });
  3173. }).join(' > ') : tuples[0].name;
  3174. return wrap$1(eventName, uncurried(assembled, purpose));
  3175. });
  3176. });
  3177. return consolidate(r, {});
  3178. };
  3179. var _a$2;
  3180. var baseBehaviour = 'alloy.base.behaviour';
  3181. var schema$z = objOf([
  3182. field$1('dom', 'dom', required$2(), objOf([
  3183. required$1('tag'),
  3184. defaulted('styles', {}),
  3185. defaulted('classes', []),
  3186. defaulted('attributes', {}),
  3187. option('value'),
  3188. option('innerHtml')
  3189. ])),
  3190. required$1('components'),
  3191. required$1('uid'),
  3192. defaulted('events', {}),
  3193. defaulted('apis', {}),
  3194. field$1('eventOrder', 'eventOrder', mergeWith((_a$2 = {}, _a$2[execute$5()] = [
  3195. 'disabling',
  3196. baseBehaviour,
  3197. 'toggling',
  3198. 'typeaheadevents'
  3199. ], _a$2[focus$4()] = [
  3200. baseBehaviour,
  3201. 'focusing',
  3202. 'keying'
  3203. ], _a$2[systemInit()] = [
  3204. baseBehaviour,
  3205. 'disabling',
  3206. 'toggling',
  3207. 'representing'
  3208. ], _a$2[input()] = [
  3209. baseBehaviour,
  3210. 'representing',
  3211. 'streaming',
  3212. 'invalidating'
  3213. ], _a$2[detachedFromDom()] = [
  3214. baseBehaviour,
  3215. 'representing',
  3216. 'item-events',
  3217. 'tooltipping'
  3218. ], _a$2[mousedown()] = [
  3219. 'focusing',
  3220. baseBehaviour,
  3221. 'item-type-events'
  3222. ], _a$2[touchstart()] = [
  3223. 'focusing',
  3224. baseBehaviour,
  3225. 'item-type-events'
  3226. ], _a$2[mouseover()] = [
  3227. 'item-type-events',
  3228. 'tooltipping'
  3229. ], _a$2[receive()] = [
  3230. 'receiving',
  3231. 'reflecting',
  3232. 'tooltipping'
  3233. ], _a$2)), anyValue()),
  3234. option('domModification')
  3235. ]);
  3236. var toInfo = function (spec) {
  3237. return asRaw('custom.definition', schema$z, spec);
  3238. };
  3239. var toDefinition = function (detail) {
  3240. return __assign(__assign({}, detail.dom), {
  3241. uid: detail.uid,
  3242. domChildren: map$2(detail.components, function (comp) {
  3243. return comp.element;
  3244. })
  3245. });
  3246. };
  3247. var toModification = function (detail) {
  3248. return detail.domModification.fold(function () {
  3249. return nu$7({});
  3250. }, nu$7);
  3251. };
  3252. var toEvents = function (info) {
  3253. return info.events;
  3254. };
  3255. var read = function (element, attr) {
  3256. var value = get$d(element, attr);
  3257. return value === undefined || value === '' ? [] : value.split(' ');
  3258. };
  3259. var add$4 = function (element, attr, id) {
  3260. var old = read(element, attr);
  3261. var nu = old.concat([id]);
  3262. set$8(element, attr, nu.join(' '));
  3263. return true;
  3264. };
  3265. var remove$4 = function (element, attr, id) {
  3266. var nu = filter$2(read(element, attr), function (v) {
  3267. return v !== id;
  3268. });
  3269. if (nu.length > 0) {
  3270. set$8(element, attr, nu.join(' '));
  3271. } else {
  3272. remove$7(element, attr);
  3273. }
  3274. return false;
  3275. };
  3276. var supports = function (element) {
  3277. return element.dom.classList !== undefined;
  3278. };
  3279. var get$6 = function (element) {
  3280. return read(element, 'class');
  3281. };
  3282. var add$3 = function (element, clazz) {
  3283. return add$4(element, 'class', clazz);
  3284. };
  3285. var remove$3 = function (element, clazz) {
  3286. return remove$4(element, 'class', clazz);
  3287. };
  3288. var add$2 = function (element, clazz) {
  3289. if (supports(element)) {
  3290. element.dom.classList.add(clazz);
  3291. } else {
  3292. add$3(element, clazz);
  3293. }
  3294. };
  3295. var cleanClass = function (element) {
  3296. var classList = supports(element) ? element.dom.classList : get$6(element);
  3297. if (classList.length === 0) {
  3298. remove$7(element, 'class');
  3299. }
  3300. };
  3301. var remove$2 = function (element, clazz) {
  3302. if (supports(element)) {
  3303. var classList = element.dom.classList;
  3304. classList.remove(clazz);
  3305. } else {
  3306. remove$3(element, clazz);
  3307. }
  3308. cleanClass(element);
  3309. };
  3310. var has = function (element, clazz) {
  3311. return supports(element) && element.dom.classList.contains(clazz);
  3312. };
  3313. var add$1 = function (element, classes) {
  3314. each$1(classes, function (x) {
  3315. add$2(element, x);
  3316. });
  3317. };
  3318. var remove$1 = function (element, classes) {
  3319. each$1(classes, function (x) {
  3320. remove$2(element, x);
  3321. });
  3322. };
  3323. var hasAll = function (element, classes) {
  3324. return forall(classes, function (clazz) {
  3325. return has(element, clazz);
  3326. });
  3327. };
  3328. var get$5 = function (element) {
  3329. return element.dom.value;
  3330. };
  3331. var set$4 = function (element, value) {
  3332. if (value === undefined) {
  3333. throw new Error('Value.set was undefined');
  3334. }
  3335. element.dom.value = value;
  3336. };
  3337. var renderToDom = function (definition) {
  3338. var subject = SugarElement.fromTag(definition.tag);
  3339. setAll$1(subject, definition.attributes);
  3340. add$1(subject, definition.classes);
  3341. setAll(subject, definition.styles);
  3342. definition.innerHtml.each(function (html) {
  3343. return set$5(subject, html);
  3344. });
  3345. var children = definition.domChildren;
  3346. append$1(subject, children);
  3347. definition.value.each(function (value) {
  3348. set$4(subject, value);
  3349. });
  3350. if (!definition.uid) {
  3351. debugger;
  3352. }
  3353. writeOnly(subject, definition.uid);
  3354. return subject;
  3355. };
  3356. var getBehaviours$2 = function (spec) {
  3357. var behaviours = get$e(spec, 'behaviours').getOr({});
  3358. return bind$3(keys(behaviours), function (name) {
  3359. var behaviour = behaviours[name];
  3360. return isNonNullable(behaviour) ? [behaviour.me] : [];
  3361. });
  3362. };
  3363. var generateFrom = function (spec, all) {
  3364. return generateFrom$1(spec, all);
  3365. };
  3366. var generate$4 = function (spec) {
  3367. var all = getBehaviours$2(spec);
  3368. return generateFrom(spec, all);
  3369. };
  3370. var getDomDefinition = function (info, bList, bData) {
  3371. var definition = toDefinition(info);
  3372. var infoModification = toModification(info);
  3373. var baseModification = { 'alloy.base.modification': infoModification };
  3374. var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification;
  3375. return merge(definition, modification);
  3376. };
  3377. var getEvents = function (info, bList, bData) {
  3378. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  3379. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  3380. };
  3381. var build$2 = function (spec) {
  3382. var getMe = function () {
  3383. return me;
  3384. };
  3385. var systemApi = Cell(singleton$1);
  3386. var info = getOrDie(toInfo(spec));
  3387. var bBlob = generate$4(spec);
  3388. var bList = getBehaviours$3(bBlob);
  3389. var bData = getData$2(bBlob);
  3390. var modDefinition = getDomDefinition(info, bList, bData);
  3391. var item = renderToDom(modDefinition);
  3392. var events = getEvents(info, bList, bData);
  3393. var subcomponents = Cell(info.components);
  3394. var connect = function (newApi) {
  3395. systemApi.set(newApi);
  3396. };
  3397. var disconnect = function () {
  3398. systemApi.set(NoContextApi(getMe));
  3399. };
  3400. var syncComponents = function () {
  3401. var children$1 = children(item);
  3402. var subs = bind$3(children$1, function (child) {
  3403. return systemApi.get().getByDom(child).fold(function () {
  3404. return [];
  3405. }, pure$2);
  3406. });
  3407. subcomponents.set(subs);
  3408. };
  3409. var config = function (behaviour) {
  3410. var b = bData;
  3411. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  3412. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  3413. };
  3414. return f();
  3415. };
  3416. var hasConfigured = function (behaviour) {
  3417. return isFunction(bData[behaviour.name()]);
  3418. };
  3419. var getApis = function () {
  3420. return info.apis;
  3421. };
  3422. var readState = function (behaviourName) {
  3423. return bData[behaviourName]().map(function (b) {
  3424. return b.state.readState();
  3425. }).getOr('not enabled');
  3426. };
  3427. var me = {
  3428. uid: spec.uid,
  3429. getSystem: systemApi.get,
  3430. config: config,
  3431. hasConfigured: hasConfigured,
  3432. spec: spec,
  3433. readState: readState,
  3434. getApis: getApis,
  3435. connect: connect,
  3436. disconnect: disconnect,
  3437. element: item,
  3438. syncComponents: syncComponents,
  3439. components: subcomponents.get,
  3440. events: events
  3441. };
  3442. return me;
  3443. };
  3444. var buildSubcomponents = function (spec) {
  3445. var components = get$e(spec, 'components').getOr([]);
  3446. return map$2(components, build$1);
  3447. };
  3448. var buildFromSpec = function (userSpec) {
  3449. var _a = make$8(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  3450. var components = buildSubcomponents(spec);
  3451. var completeSpec = __assign(__assign({}, spec), {
  3452. events: __assign(__assign({}, DefaultEvents), specEvents),
  3453. components: components
  3454. });
  3455. return Result.value(build$2(completeSpec));
  3456. };
  3457. var text = function (textContent) {
  3458. var element = SugarElement.fromText(textContent);
  3459. return external$2({ element: element });
  3460. };
  3461. var external$2 = function (spec) {
  3462. var extSpec = asRawOrDie$1('external.component', objOfOnly([
  3463. required$1('element'),
  3464. option('uid')
  3465. ]), spec);
  3466. var systemApi = Cell(NoContextApi());
  3467. var connect = function (newApi) {
  3468. systemApi.set(newApi);
  3469. };
  3470. var disconnect = function () {
  3471. systemApi.set(NoContextApi(function () {
  3472. return me;
  3473. }));
  3474. };
  3475. var uid = extSpec.uid.getOrThunk(function () {
  3476. return generate$5('external');
  3477. });
  3478. writeOnly(extSpec.element, uid);
  3479. var me = {
  3480. uid: uid,
  3481. getSystem: systemApi.get,
  3482. config: Optional.none,
  3483. hasConfigured: never,
  3484. connect: connect,
  3485. disconnect: disconnect,
  3486. getApis: function () {
  3487. return {};
  3488. },
  3489. element: extSpec.element,
  3490. spec: spec,
  3491. readState: constant$1('No state'),
  3492. syncComponents: noop,
  3493. components: constant$1([]),
  3494. events: {}
  3495. };
  3496. return premade$1(me);
  3497. };
  3498. var uids = generate$5;
  3499. var isSketchSpec$1 = function (spec) {
  3500. return has$2(spec, 'uid');
  3501. };
  3502. var build$1 = function (spec) {
  3503. return getPremade(spec).getOrThunk(function () {
  3504. var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids('') }, spec);
  3505. return buildFromSpec(userSpecWithUid).getOrDie();
  3506. });
  3507. };
  3508. var premade = premade$1;
  3509. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3510. if (is(scope, a)) {
  3511. return Optional.some(scope);
  3512. } else if (isFunction(isRoot) && isRoot(scope)) {
  3513. return Optional.none();
  3514. } else {
  3515. return ancestor(scope, a, isRoot);
  3516. }
  3517. }
  3518. var ancestor$1 = function (scope, predicate, isRoot) {
  3519. var element = scope.dom;
  3520. var stop = isFunction(isRoot) ? isRoot : never;
  3521. while (element.parentNode) {
  3522. element = element.parentNode;
  3523. var el = SugarElement.fromDom(element);
  3524. if (predicate(el)) {
  3525. return Optional.some(el);
  3526. } else if (stop(el)) {
  3527. break;
  3528. }
  3529. }
  3530. return Optional.none();
  3531. };
  3532. var closest$3 = function (scope, predicate, isRoot) {
  3533. var is = function (s, test) {
  3534. return test(s);
  3535. };
  3536. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3537. };
  3538. var child$1 = function (scope, predicate) {
  3539. var pred = function (node) {
  3540. return predicate(SugarElement.fromDom(node));
  3541. };
  3542. var result = find$5(scope.dom.childNodes, pred);
  3543. return result.map(SugarElement.fromDom);
  3544. };
  3545. var descendant$1 = function (scope, predicate) {
  3546. var descend = function (node) {
  3547. for (var i = 0; i < node.childNodes.length; i++) {
  3548. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3549. if (predicate(child_1)) {
  3550. return Optional.some(child_1);
  3551. }
  3552. var res = descend(node.childNodes[i]);
  3553. if (res.isSome()) {
  3554. return res;
  3555. }
  3556. }
  3557. return Optional.none();
  3558. };
  3559. return descend(scope.dom);
  3560. };
  3561. var closest$2 = function (scope, predicate, isRoot) {
  3562. return closest$3(scope, predicate, isRoot).isSome();
  3563. };
  3564. var ancestor = function (scope, selector, isRoot) {
  3565. return ancestor$1(scope, function (e) {
  3566. return is(e, selector);
  3567. }, isRoot);
  3568. };
  3569. var child = function (scope, selector) {
  3570. return child$1(scope, function (e) {
  3571. return is(e, selector);
  3572. });
  3573. };
  3574. var descendant = function (scope, selector) {
  3575. return one(selector, scope);
  3576. };
  3577. var closest$1 = function (scope, selector, isRoot) {
  3578. var is$1 = function (element, selector) {
  3579. return is(element, selector);
  3580. };
  3581. return ClosestOrAncestor(is$1, ancestor, scope, selector, isRoot);
  3582. };
  3583. var find$1 = function (queryElem) {
  3584. var dependent = closest$3(queryElem, function (elem) {
  3585. if (!isElement$2(elem)) {
  3586. return false;
  3587. }
  3588. var id = get$d(elem, 'id');
  3589. return id !== undefined && id.indexOf('aria-owns') > -1;
  3590. });
  3591. return dependent.bind(function (dep) {
  3592. var id = get$d(dep, 'id');
  3593. var dos = getRootNode(dep);
  3594. return descendant(dos, '[aria-owns="' + id + '"]');
  3595. });
  3596. };
  3597. var manager = function () {
  3598. var ariaId = generate$6('aria-owns');
  3599. var link = function (elem) {
  3600. set$8(elem, 'aria-owns', ariaId);
  3601. };
  3602. var unlink = function (elem) {
  3603. remove$7(elem, 'aria-owns');
  3604. };
  3605. return {
  3606. id: ariaId,
  3607. link: link,
  3608. unlink: unlink
  3609. };
  3610. };
  3611. var isAriaPartOf = function (component, queryElem) {
  3612. return find$1(queryElem).exists(function (owner) {
  3613. return isPartOf$1(component, owner);
  3614. });
  3615. };
  3616. var isPartOf$1 = function (component, queryElem) {
  3617. return closest$2(queryElem, function (el) {
  3618. return eq(el, component.element);
  3619. }, never) || isAriaPartOf(component, queryElem);
  3620. };
  3621. var unknown = 'unknown';
  3622. var EventConfiguration;
  3623. (function (EventConfiguration) {
  3624. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3625. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3626. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3627. }(EventConfiguration || (EventConfiguration = {})));
  3628. var eventConfig = Cell({});
  3629. var makeEventLogger = function (eventName, initialTarget) {
  3630. var sequence = [];
  3631. var startTime = new Date().getTime();
  3632. return {
  3633. logEventCut: function (_name, target, purpose) {
  3634. sequence.push({
  3635. outcome: 'cut',
  3636. target: target,
  3637. purpose: purpose
  3638. });
  3639. },
  3640. logEventStopped: function (_name, target, purpose) {
  3641. sequence.push({
  3642. outcome: 'stopped',
  3643. target: target,
  3644. purpose: purpose
  3645. });
  3646. },
  3647. logNoParent: function (_name, target, purpose) {
  3648. sequence.push({
  3649. outcome: 'no-parent',
  3650. target: target,
  3651. purpose: purpose
  3652. });
  3653. },
  3654. logEventNoHandlers: function (_name, target) {
  3655. sequence.push({
  3656. outcome: 'no-handlers-left',
  3657. target: target
  3658. });
  3659. },
  3660. logEventResponse: function (_name, target, purpose) {
  3661. sequence.push({
  3662. outcome: 'response',
  3663. purpose: purpose,
  3664. target: target
  3665. });
  3666. },
  3667. write: function () {
  3668. var finishTime = new Date().getTime();
  3669. if (contains$2([
  3670. 'mousemove',
  3671. 'mouseover',
  3672. 'mouseout',
  3673. systemInit()
  3674. ], eventName)) {
  3675. return;
  3676. }
  3677. console.log(eventName, {
  3678. event: eventName,
  3679. time: finishTime - startTime,
  3680. target: initialTarget.dom,
  3681. sequence: map$2(sequence, function (s) {
  3682. if (!contains$2([
  3683. 'cut',
  3684. 'stopped',
  3685. 'response'
  3686. ], s.outcome)) {
  3687. return s.outcome;
  3688. } else {
  3689. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3690. }
  3691. })
  3692. });
  3693. }
  3694. };
  3695. };
  3696. var processEvent = function (eventName, initialTarget, f) {
  3697. var status = get$e(eventConfig.get(), eventName).orThunk(function () {
  3698. var patterns = keys(eventConfig.get());
  3699. return findMap(patterns, function (p) {
  3700. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  3701. });
  3702. }).getOr(EventConfiguration.NORMAL);
  3703. switch (status) {
  3704. case EventConfiguration.NORMAL:
  3705. return f(noLogger());
  3706. case EventConfiguration.LOGGING: {
  3707. var logger = makeEventLogger(eventName, initialTarget);
  3708. var output = f(logger);
  3709. logger.write();
  3710. return output;
  3711. }
  3712. case EventConfiguration.STOP:
  3713. return true;
  3714. }
  3715. };
  3716. var path = [
  3717. 'alloy/data/Fields',
  3718. 'alloy/debugging/Debugging'
  3719. ];
  3720. var getTrace = function () {
  3721. var err = new Error();
  3722. if (err.stack !== undefined) {
  3723. var lines = err.stack.split('\n');
  3724. return find$5(lines, function (line) {
  3725. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3726. return line.indexOf(p) > -1;
  3727. });
  3728. }).getOr(unknown);
  3729. } else {
  3730. return unknown;
  3731. }
  3732. };
  3733. var ignoreEvent = {
  3734. logEventCut: noop,
  3735. logEventStopped: noop,
  3736. logNoParent: noop,
  3737. logEventNoHandlers: noop,
  3738. logEventResponse: noop,
  3739. write: noop
  3740. };
  3741. var monitorEvent = function (eventName, initialTarget, f) {
  3742. return processEvent(eventName, initialTarget, f);
  3743. };
  3744. var noLogger = constant$1(ignoreEvent);
  3745. var menuFields = constant$1([
  3746. required$1('menu'),
  3747. required$1('selectedMenu')
  3748. ]);
  3749. var itemFields = constant$1([
  3750. required$1('item'),
  3751. required$1('selectedItem')
  3752. ]);
  3753. constant$1(objOf(itemFields().concat(menuFields())));
  3754. var itemSchema$3 = constant$1(objOf(itemFields()));
  3755. var _initSize = requiredObjOf('initSize', [
  3756. required$1('numColumns'),
  3757. required$1('numRows')
  3758. ]);
  3759. var itemMarkers = function () {
  3760. return requiredOf('markers', itemSchema$3());
  3761. };
  3762. var tieredMenuMarkers = function () {
  3763. return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3764. };
  3765. var markers$1 = function (required) {
  3766. return requiredObjOf('markers', map$2(required, required$1));
  3767. };
  3768. var onPresenceHandler = function (label, fieldName, presence) {
  3769. getTrace();
  3770. return field$1(fieldName, fieldName, presence, valueOf(function (f) {
  3771. return Result.value(function () {
  3772. var args = [];
  3773. for (var _i = 0; _i < arguments.length; _i++) {
  3774. args[_i] = arguments[_i];
  3775. }
  3776. return f.apply(undefined, args);
  3777. });
  3778. }));
  3779. };
  3780. var onHandler = function (fieldName) {
  3781. return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  3782. };
  3783. var onKeyboardHandler = function (fieldName) {
  3784. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  3785. };
  3786. var onStrictHandler = function (fieldName) {
  3787. return onPresenceHandler('onHandler', fieldName, required$2());
  3788. };
  3789. var onStrictKeyboardHandler = function (fieldName) {
  3790. return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  3791. };
  3792. var output$1 = function (name, value) {
  3793. return customField(name, constant$1(value));
  3794. };
  3795. var snapshot = function (name) {
  3796. return customField(name, identity$1);
  3797. };
  3798. var initSize = constant$1(_initSize);
  3799. var nu$6 = function (x, y, bubble, direction, placement, boundsRestriction, labelPrefix, alwaysFit) {
  3800. if (alwaysFit === void 0) {
  3801. alwaysFit = false;
  3802. }
  3803. return {
  3804. x: x,
  3805. y: y,
  3806. bubble: bubble,
  3807. direction: direction,
  3808. placement: placement,
  3809. restriction: boundsRestriction,
  3810. label: labelPrefix + '-' + placement,
  3811. alwaysFit: alwaysFit
  3812. };
  3813. };
  3814. var adt$a = Adt.generate([
  3815. { southeast: [] },
  3816. { southwest: [] },
  3817. { northeast: [] },
  3818. { northwest: [] },
  3819. { south: [] },
  3820. { north: [] },
  3821. { east: [] },
  3822. { west: [] }
  3823. ]);
  3824. var cata$2 = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3825. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3826. };
  3827. var cataVertical = function (subject, south, middle, north) {
  3828. return subject.fold(south, south, north, north, south, north, middle, middle);
  3829. };
  3830. var cataHorizontal = function (subject, east, middle, west) {
  3831. return subject.fold(east, west, east, west, middle, middle, east, west);
  3832. };
  3833. var southeast$3 = adt$a.southeast;
  3834. var southwest$3 = adt$a.southwest;
  3835. var northeast$3 = adt$a.northeast;
  3836. var northwest$3 = adt$a.northwest;
  3837. var south$3 = adt$a.south;
  3838. var north$3 = adt$a.north;
  3839. var east$3 = adt$a.east;
  3840. var west$3 = adt$a.west;
  3841. var cycleBy = function (value, delta, min, max) {
  3842. var r = value + delta;
  3843. if (r > max) {
  3844. return min;
  3845. } else if (r < min) {
  3846. return max;
  3847. } else {
  3848. return r;
  3849. }
  3850. };
  3851. var clamp$1 = function (value, min, max) {
  3852. return Math.min(Math.max(value, min), max);
  3853. };
  3854. var getRestriction = function (anchor, restriction) {
  3855. switch (restriction) {
  3856. case 1:
  3857. return anchor.x;
  3858. case 0:
  3859. return anchor.x + anchor.width;
  3860. case 2:
  3861. return anchor.y;
  3862. case 3:
  3863. return anchor.y + anchor.height;
  3864. }
  3865. };
  3866. var boundsRestriction = function (anchor, restrictions) {
  3867. return mapToObject([
  3868. 'left',
  3869. 'right',
  3870. 'top',
  3871. 'bottom'
  3872. ], function (dir) {
  3873. return get$e(restrictions, dir).map(function (restriction) {
  3874. return getRestriction(anchor, restriction);
  3875. });
  3876. });
  3877. };
  3878. var adjustBounds = function (bounds$1, restriction, bubbleOffset) {
  3879. var applyRestriction = function (dir, current) {
  3880. return restriction[dir].map(function (pos) {
  3881. var isVerticalAxis = dir === 'top' || dir === 'bottom';
  3882. var offset = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left;
  3883. var comparator = dir === 'left' || dir === 'top' ? Math.max : Math.min;
  3884. var newPos = comparator(pos, current) + offset;
  3885. return isVerticalAxis ? clamp$1(newPos, bounds$1.y, bounds$1.bottom) : clamp$1(newPos, bounds$1.x, bounds$1.right);
  3886. }).getOr(current);
  3887. };
  3888. var adjustedLeft = applyRestriction('left', bounds$1.x);
  3889. var adjustedTop = applyRestriction('top', bounds$1.y);
  3890. var adjustedRight = applyRestriction('right', bounds$1.right);
  3891. var adjustedBottom = applyRestriction('bottom', bounds$1.bottom);
  3892. return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  3893. };
  3894. var labelPrefix$2 = 'layout';
  3895. var eastX$1 = function (anchor) {
  3896. return anchor.x;
  3897. };
  3898. var middleX$1 = function (anchor, element) {
  3899. return anchor.x + anchor.width / 2 - element.width / 2;
  3900. };
  3901. var westX$1 = function (anchor, element) {
  3902. return anchor.x + anchor.width - element.width;
  3903. };
  3904. var northY$2 = function (anchor, element) {
  3905. return anchor.y - element.height;
  3906. };
  3907. var southY$2 = function (anchor) {
  3908. return anchor.y + anchor.height;
  3909. };
  3910. var centreY$1 = function (anchor, element) {
  3911. return anchor.y + anchor.height / 2 - element.height / 2;
  3912. };
  3913. var eastEdgeX$1 = function (anchor) {
  3914. return anchor.x + anchor.width;
  3915. };
  3916. var westEdgeX$1 = function (anchor, element) {
  3917. return anchor.x - element.width;
  3918. };
  3919. var southeast$2 = function (anchor, element, bubbles) {
  3920. return nu$6(eastX$1(anchor), southY$2(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  3921. left: 1,
  3922. top: 3
  3923. }), labelPrefix$2);
  3924. };
  3925. var southwest$2 = function (anchor, element, bubbles) {
  3926. return nu$6(westX$1(anchor, element), southY$2(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  3927. right: 0,
  3928. top: 3
  3929. }), labelPrefix$2);
  3930. };
  3931. var northeast$2 = function (anchor, element, bubbles) {
  3932. return nu$6(eastX$1(anchor), northY$2(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  3933. left: 1,
  3934. bottom: 2
  3935. }), labelPrefix$2);
  3936. };
  3937. var northwest$2 = function (anchor, element, bubbles) {
  3938. return nu$6(westX$1(anchor, element), northY$2(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  3939. right: 0,
  3940. bottom: 2
  3941. }), labelPrefix$2);
  3942. };
  3943. var north$2 = function (anchor, element, bubbles) {
  3944. return nu$6(middleX$1(anchor, element), northY$2(anchor, element), bubbles.north(), north$3(), 'north', boundsRestriction(anchor, { bottom: 2 }), labelPrefix$2);
  3945. };
  3946. var south$2 = function (anchor, element, bubbles) {
  3947. return nu$6(middleX$1(anchor, element), southY$2(anchor), bubbles.south(), south$3(), 'south', boundsRestriction(anchor, { top: 3 }), labelPrefix$2);
  3948. };
  3949. var east$2 = function (anchor, element, bubbles) {
  3950. return nu$6(eastEdgeX$1(anchor), centreY$1(anchor, element), bubbles.east(), east$3(), 'east', boundsRestriction(anchor, { left: 0 }), labelPrefix$2);
  3951. };
  3952. var west$2 = function (anchor, element, bubbles) {
  3953. return nu$6(westEdgeX$1(anchor, element), centreY$1(anchor, element), bubbles.west(), west$3(), 'west', boundsRestriction(anchor, { right: 1 }), labelPrefix$2);
  3954. };
  3955. var all$1 = function () {
  3956. return [
  3957. southeast$2,
  3958. southwest$2,
  3959. northeast$2,
  3960. northwest$2,
  3961. south$2,
  3962. north$2,
  3963. east$2,
  3964. west$2
  3965. ];
  3966. };
  3967. var allRtl$1 = function () {
  3968. return [
  3969. southwest$2,
  3970. southeast$2,
  3971. northwest$2,
  3972. northeast$2,
  3973. south$2,
  3974. north$2,
  3975. east$2,
  3976. west$2
  3977. ];
  3978. };
  3979. var aboveOrBelow = function () {
  3980. return [
  3981. northeast$2,
  3982. northwest$2,
  3983. southeast$2,
  3984. southwest$2,
  3985. north$2,
  3986. south$2
  3987. ];
  3988. };
  3989. var aboveOrBelowRtl = function () {
  3990. return [
  3991. northwest$2,
  3992. northeast$2,
  3993. southwest$2,
  3994. southeast$2,
  3995. north$2,
  3996. south$2
  3997. ];
  3998. };
  3999. var belowOrAbove = function () {
  4000. return [
  4001. southeast$2,
  4002. southwest$2,
  4003. northeast$2,
  4004. northwest$2,
  4005. south$2,
  4006. north$2
  4007. ];
  4008. };
  4009. var belowOrAboveRtl = function () {
  4010. return [
  4011. southwest$2,
  4012. southeast$2,
  4013. northwest$2,
  4014. northeast$2,
  4015. south$2,
  4016. north$2
  4017. ];
  4018. };
  4019. var chooseChannels = function (channels, message) {
  4020. return message.universal ? channels : filter$2(channels, function (ch) {
  4021. return contains$2(message.channels, ch);
  4022. });
  4023. };
  4024. var events$h = function (receiveConfig) {
  4025. return derive$2([run$1(receive(), function (component, message) {
  4026. var channelMap = receiveConfig.channels;
  4027. var channels = keys(channelMap);
  4028. var receivingData = message;
  4029. var targetChannels = chooseChannels(channels, receivingData);
  4030. each$1(targetChannels, function (ch) {
  4031. var channelInfo = channelMap[ch];
  4032. var channelSchema = channelInfo.schema;
  4033. var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  4034. channelInfo.onReceive(component, data);
  4035. });
  4036. })]);
  4037. };
  4038. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  4039. __proto__: null,
  4040. events: events$h
  4041. });
  4042. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  4043. onStrictHandler('onReceive'),
  4044. defaulted('schema', anyValue())
  4045. ])))];
  4046. var executeEvent = function (bConfig, bState, executor) {
  4047. return runOnExecute$1(function (component) {
  4048. executor(component, bConfig, bState);
  4049. });
  4050. };
  4051. var loadEvent = function (bConfig, bState, f) {
  4052. return runOnInit(function (component, _simulatedEvent) {
  4053. f(component, bConfig, bState);
  4054. });
  4055. };
  4056. var create$8 = function (schema, name, active, apis, extra, state) {
  4057. var configSchema = objOfOnly(schema);
  4058. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  4059. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4060. };
  4061. var createModes$1 = function (modes, name, active, apis, extra, state) {
  4062. var configSchema = modes;
  4063. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  4064. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  4065. };
  4066. var wrapApi = function (bName, apiFunction, apiName) {
  4067. var f = function (component) {
  4068. var rest = [];
  4069. for (var _i = 1; _i < arguments.length; _i++) {
  4070. rest[_i - 1] = arguments[_i];
  4071. }
  4072. var args = [component].concat(rest);
  4073. return component.config({ name: constant$1(bName) }).fold(function () {
  4074. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  4075. }, function (info) {
  4076. var rest = Array.prototype.slice.call(args, 1);
  4077. return apiFunction.apply(undefined, [
  4078. component,
  4079. info.config,
  4080. info.state
  4081. ].concat(rest));
  4082. });
  4083. };
  4084. return markAsBehaviourApi(f, apiName, apiFunction);
  4085. };
  4086. var revokeBehaviour = function (name) {
  4087. return {
  4088. key: name,
  4089. value: undefined
  4090. };
  4091. };
  4092. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  4093. var getConfig = function (info) {
  4094. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  4095. };
  4096. var wrappedApis = map$1(apis, function (apiF, apiName) {
  4097. return wrapApi(name, apiF, apiName);
  4098. });
  4099. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  4100. return markAsExtraApi(extraF, extraName);
  4101. });
  4102. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  4103. revoke: curry(revokeBehaviour, name),
  4104. config: function (spec) {
  4105. var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  4106. return {
  4107. key: name,
  4108. value: {
  4109. config: prepared,
  4110. me: me,
  4111. configAsRaw: cached(function () {
  4112. return asRawOrDie$1(name + '-config', configSchema, spec);
  4113. }),
  4114. initialConfig: spec,
  4115. state: state
  4116. }
  4117. };
  4118. },
  4119. schema: constant$1(schemaSchema),
  4120. exhibit: function (info, base) {
  4121. return lift2(getConfig(info), get$e(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  4122. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  4123. }).getOrThunk(function () {
  4124. return nu$7({});
  4125. });
  4126. },
  4127. name: constant$1(name),
  4128. handlers: function (info) {
  4129. return getConfig(info).map(function (behaviourInfo) {
  4130. var getEvents = get$e(active, 'events').getOr(function () {
  4131. return {};
  4132. });
  4133. return getEvents(behaviourInfo.config, behaviourInfo.state);
  4134. }).getOr({});
  4135. }
  4136. });
  4137. return me;
  4138. };
  4139. var derive$1 = function (capabilities) {
  4140. return wrapAll(capabilities);
  4141. };
  4142. var simpleSchema = objOfOnly([
  4143. required$1('fields'),
  4144. required$1('name'),
  4145. defaulted('active', {}),
  4146. defaulted('apis', {}),
  4147. defaulted('state', NoState),
  4148. defaulted('extra', {})
  4149. ]);
  4150. var create$7 = function (data) {
  4151. var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  4152. return create$8(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  4153. };
  4154. var modeSchema = objOfOnly([
  4155. required$1('branchKey'),
  4156. required$1('branches'),
  4157. required$1('name'),
  4158. defaulted('active', {}),
  4159. defaulted('apis', {}),
  4160. defaulted('state', NoState),
  4161. defaulted('extra', {})
  4162. ]);
  4163. var createModes = function (data) {
  4164. var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  4165. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  4166. };
  4167. var revoke = constant$1(undefined);
  4168. var Receiving = create$7({
  4169. fields: ReceivingSchema,
  4170. name: 'receiving',
  4171. active: ActiveReceiving
  4172. });
  4173. var exhibit$6 = function (base, posConfig) {
  4174. return nu$7({
  4175. classes: [],
  4176. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  4177. });
  4178. };
  4179. var ActivePosition = /*#__PURE__*/Object.freeze({
  4180. __proto__: null,
  4181. exhibit: exhibit$6
  4182. });
  4183. var getDocument = function () {
  4184. return SugarElement.fromDom(document);
  4185. };
  4186. var focus$3 = function (element) {
  4187. return element.dom.focus();
  4188. };
  4189. var blur$1 = function (element) {
  4190. return element.dom.blur();
  4191. };
  4192. var hasFocus = function (element) {
  4193. var root = getRootNode(element).dom;
  4194. return element.dom === root.activeElement;
  4195. };
  4196. var active = function (root) {
  4197. if (root === void 0) {
  4198. root = getDocument();
  4199. }
  4200. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  4201. };
  4202. var search = function (element) {
  4203. return active(getRootNode(element)).filter(function (e) {
  4204. return element.dom.contains(e.dom);
  4205. });
  4206. };
  4207. var preserve$1 = function (f, container) {
  4208. var dos = getRootNode(container);
  4209. var refocus = active(dos).bind(function (focused) {
  4210. var hasFocus = function (elem) {
  4211. return eq(focused, elem);
  4212. };
  4213. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  4214. });
  4215. var result = f(container);
  4216. refocus.each(function (oldFocus) {
  4217. active(dos).filter(function (newFocus) {
  4218. return eq(newFocus, oldFocus);
  4219. }).fold(function () {
  4220. focus$3(oldFocus);
  4221. }, noop);
  4222. });
  4223. return result;
  4224. };
  4225. var NuPositionCss = function (position, left, top, right, bottom) {
  4226. var toPx = function (num) {
  4227. return num + 'px';
  4228. };
  4229. return {
  4230. position: position,
  4231. left: left.map(toPx),
  4232. top: top.map(toPx),
  4233. right: right.map(toPx),
  4234. bottom: bottom.map(toPx)
  4235. };
  4236. };
  4237. var toOptions = function (position) {
  4238. return __assign(__assign({}, position), { position: Optional.some(position.position) });
  4239. };
  4240. var applyPositionCss = function (element, position) {
  4241. setOptions(element, toOptions(position));
  4242. };
  4243. var adt$9 = Adt.generate([
  4244. { none: [] },
  4245. {
  4246. relative: [
  4247. 'x',
  4248. 'y',
  4249. 'width',
  4250. 'height'
  4251. ]
  4252. },
  4253. {
  4254. fixed: [
  4255. 'x',
  4256. 'y',
  4257. 'width',
  4258. 'height'
  4259. ]
  4260. }
  4261. ]);
  4262. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4263. var decisionRect = decision.rect;
  4264. var decisionX = decisionRect.x - x;
  4265. var decisionY = decisionRect.y - y;
  4266. var decisionWidth = decisionRect.width;
  4267. var decisionHeight = decisionRect.height;
  4268. var decisionRight = width - (decisionX + decisionWidth);
  4269. var decisionBottom = height - (decisionY + decisionHeight);
  4270. var left = Optional.some(decisionX);
  4271. var top = Optional.some(decisionY);
  4272. var right = Optional.some(decisionRight);
  4273. var bottom = Optional.some(decisionBottom);
  4274. var none = Optional.none();
  4275. return cata$2(decision.direction, function () {
  4276. return NuPositionCss(posName, left, top, none, none);
  4277. }, function () {
  4278. return NuPositionCss(posName, none, top, right, none);
  4279. }, function () {
  4280. return NuPositionCss(posName, left, none, none, bottom);
  4281. }, function () {
  4282. return NuPositionCss(posName, none, none, right, bottom);
  4283. }, function () {
  4284. return NuPositionCss(posName, left, top, none, none);
  4285. }, function () {
  4286. return NuPositionCss(posName, left, none, none, bottom);
  4287. }, function () {
  4288. return NuPositionCss(posName, left, top, none, none);
  4289. }, function () {
  4290. return NuPositionCss(posName, none, top, right, none);
  4291. });
  4292. };
  4293. var reposition = function (origin, decision) {
  4294. return origin.fold(function () {
  4295. var decisionRect = decision.rect;
  4296. return NuPositionCss('absolute', Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none());
  4297. }, function (x, y, width, height) {
  4298. return positionWithDirection('absolute', decision, x, y, width, height);
  4299. }, function (x, y, width, height) {
  4300. return positionWithDirection('fixed', decision, x, y, width, height);
  4301. });
  4302. };
  4303. var toBox = function (origin, element) {
  4304. var rel = curry(find$2, element);
  4305. var position = origin.fold(rel, rel, function () {
  4306. var scroll = get$9();
  4307. return find$2(element).translate(-scroll.left, -scroll.top);
  4308. });
  4309. var width = getOuter$1(element);
  4310. var height = getOuter$2(element);
  4311. return bounds(position.left, position.top, width, height);
  4312. };
  4313. var viewport = function (origin, getBounds) {
  4314. return getBounds.fold(function () {
  4315. return origin.fold(win, win, bounds);
  4316. }, function (b) {
  4317. return origin.fold(b, b, function () {
  4318. var bounds$1 = b();
  4319. var pos = translate$2(origin, bounds$1.x, bounds$1.y);
  4320. return bounds(pos.left, pos.top, bounds$1.width, bounds$1.height);
  4321. });
  4322. });
  4323. };
  4324. var translate$2 = function (origin, x, y) {
  4325. var pos = SugarPosition(x, y);
  4326. var removeScroll = function () {
  4327. var outerScroll = get$9();
  4328. return pos.translate(-outerScroll.left, -outerScroll.top);
  4329. };
  4330. return origin.fold(constant$1(pos), constant$1(pos), removeScroll);
  4331. };
  4332. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4333. return subject.fold(onNone, onRelative, onFixed);
  4334. };
  4335. adt$9.none;
  4336. var relative$1 = adt$9.relative;
  4337. var fixed$1 = adt$9.fixed;
  4338. var anchor = function (anchorBox, origin) {
  4339. return {
  4340. anchorBox: anchorBox,
  4341. origin: origin
  4342. };
  4343. };
  4344. var box = function (anchorBox, origin) {
  4345. return anchor(anchorBox, origin);
  4346. };
  4347. var placementAttribute = 'data-alloy-placement';
  4348. var setPlacement$1 = function (element, placement) {
  4349. set$8(element, placementAttribute, placement);
  4350. };
  4351. var getPlacement = function (element) {
  4352. return getOpt(element, placementAttribute);
  4353. };
  4354. var reset$2 = function (element) {
  4355. return remove$7(element, placementAttribute);
  4356. };
  4357. var adt$8 = Adt.generate([
  4358. { fit: ['reposition'] },
  4359. {
  4360. nofit: [
  4361. 'reposition',
  4362. 'visibleW',
  4363. 'visibleH',
  4364. 'isVisible'
  4365. ]
  4366. }
  4367. ]);
  4368. var determinePosition = function (box, bounds) {
  4369. var boundsX = bounds.x, boundsY = bounds.y, boundsRight = bounds.right, boundsBottom = bounds.bottom;
  4370. var x = box.x, y = box.y, right = box.right, bottom = box.bottom, width = box.width, height = box.height;
  4371. var xInBounds = x >= boundsX && x <= boundsRight;
  4372. var yInBounds = y >= boundsY && y <= boundsBottom;
  4373. var originInBounds = xInBounds && yInBounds;
  4374. var rightInBounds = right <= boundsRight && right >= boundsX;
  4375. var bottomInBounds = bottom <= boundsBottom && bottom >= boundsY;
  4376. var sizeInBounds = rightInBounds && bottomInBounds;
  4377. var visibleW = Math.min(width, x >= boundsX ? boundsRight - x : right - boundsX);
  4378. var visibleH = Math.min(height, y >= boundsY ? boundsBottom - y : bottom - boundsY);
  4379. return {
  4380. originInBounds: originInBounds,
  4381. sizeInBounds: sizeInBounds,
  4382. visibleW: visibleW,
  4383. visibleH: visibleH
  4384. };
  4385. };
  4386. var calcReposition = function (box, bounds$1) {
  4387. var boundsX = bounds$1.x, boundsY = bounds$1.y, boundsRight = bounds$1.right, boundsBottom = bounds$1.bottom;
  4388. var x = box.x, y = box.y, width = box.width, height = box.height;
  4389. var maxX = Math.max(boundsX, boundsRight - width);
  4390. var maxY = Math.max(boundsY, boundsBottom - height);
  4391. var restrictedX = clamp$1(x, boundsX, maxX);
  4392. var restrictedY = clamp$1(y, boundsY, maxY);
  4393. var restrictedWidth = Math.min(restrictedX + width, boundsRight) - restrictedX;
  4394. var restrictedHeight = Math.min(restrictedY + height, boundsBottom) - restrictedY;
  4395. return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight);
  4396. };
  4397. var calcMaxSizes = function (direction, box, bounds) {
  4398. var upAvailable = constant$1(box.bottom - bounds.y);
  4399. var downAvailable = constant$1(bounds.bottom - box.y);
  4400. var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable);
  4401. var westAvailable = constant$1(box.right - bounds.x);
  4402. var eastAvailable = constant$1(bounds.right - box.x);
  4403. var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable);
  4404. return {
  4405. maxWidth: maxWidth,
  4406. maxHeight: maxHeight
  4407. };
  4408. };
  4409. var attempt = function (candidate, width, height, bounds$1) {
  4410. var bubble = candidate.bubble;
  4411. var bubbleOffset = bubble.offset;
  4412. var adjustedBounds = adjustBounds(bounds$1, candidate.restriction, bubbleOffset);
  4413. var newX = candidate.x + bubbleOffset.left;
  4414. var newY = candidate.y + bubbleOffset.top;
  4415. var box = bounds(newX, newY, width, height);
  4416. var _a = determinePosition(box, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, visibleW = _a.visibleW, visibleH = _a.visibleH;
  4417. var fits = originInBounds && sizeInBounds;
  4418. var fittedBox = fits ? box : calcReposition(box, adjustedBounds);
  4419. var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0;
  4420. var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$1), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight;
  4421. var reposition = {
  4422. rect: fittedBox,
  4423. maxHeight: maxHeight,
  4424. maxWidth: maxWidth,
  4425. direction: candidate.direction,
  4426. placement: candidate.placement,
  4427. classes: {
  4428. on: bubble.classesOn,
  4429. off: bubble.classesOff
  4430. },
  4431. layout: candidate.label,
  4432. testY: newY
  4433. };
  4434. return fits || candidate.alwaysFit ? adt$8.fit(reposition) : adt$8.nofit(reposition, visibleW, visibleH, isPartlyVisible);
  4435. };
  4436. var attempts = function (element, candidates, anchorBox, elementBox, bubbles, bounds) {
  4437. var panelWidth = elementBox.width;
  4438. var panelHeight = elementBox.height;
  4439. var attemptBestFit = function (layout, reposition, visibleW, visibleH, isVisible) {
  4440. var next = layout(anchorBox, elementBox, bubbles, element, bounds);
  4441. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4442. return attemptLayout.fold(constant$1(attemptLayout), function (newReposition, newVisibleW, newVisibleH, newIsVisible) {
  4443. var improved = isVisible === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible && newIsVisible;
  4444. return improved ? attemptLayout : adt$8.nofit(reposition, visibleW, visibleH, isVisible);
  4445. });
  4446. };
  4447. var abc = foldl(candidates, function (b, a) {
  4448. var bestNext = curry(attemptBestFit, a);
  4449. return b.fold(constant$1(b), bestNext);
  4450. }, adt$8.nofit({
  4451. rect: anchorBox,
  4452. maxHeight: elementBox.height,
  4453. maxWidth: elementBox.width,
  4454. direction: southeast$3(),
  4455. placement: 'southeast',
  4456. classes: {
  4457. on: [],
  4458. off: []
  4459. },
  4460. layout: 'none',
  4461. testY: anchorBox.y
  4462. }, -1, -1, false));
  4463. return abc.fold(identity$1, identity$1);
  4464. };
  4465. var singleton = function (doRevoke) {
  4466. var subject = Cell(Optional.none());
  4467. var revoke = function () {
  4468. return subject.get().each(doRevoke);
  4469. };
  4470. var clear = function () {
  4471. revoke();
  4472. subject.set(Optional.none());
  4473. };
  4474. var isSet = function () {
  4475. return subject.get().isSome();
  4476. };
  4477. var get = function () {
  4478. return subject.get();
  4479. };
  4480. var set = function (s) {
  4481. revoke();
  4482. subject.set(Optional.some(s));
  4483. };
  4484. return {
  4485. clear: clear,
  4486. isSet: isSet,
  4487. get: get,
  4488. set: set
  4489. };
  4490. };
  4491. var destroyable = function () {
  4492. return singleton(function (s) {
  4493. return s.destroy();
  4494. });
  4495. };
  4496. var unbindable = function () {
  4497. return singleton(function (s) {
  4498. return s.unbind();
  4499. });
  4500. };
  4501. var api$1 = function () {
  4502. var subject = destroyable();
  4503. var run = function (f) {
  4504. return subject.get().each(f);
  4505. };
  4506. return __assign(__assign({}, subject), { run: run });
  4507. };
  4508. var value$1 = function () {
  4509. var subject = singleton(noop);
  4510. var on = function (f) {
  4511. return subject.get().each(f);
  4512. };
  4513. return __assign(__assign({}, subject), { on: on });
  4514. };
  4515. var filter = always;
  4516. var bind = function (element, event, handler) {
  4517. return bind$2(element, event, filter, handler);
  4518. };
  4519. var capture = function (element, event, handler) {
  4520. return capture$1(element, event, filter, handler);
  4521. };
  4522. var fromRawEvent = fromRawEvent$1;
  4523. var properties = [
  4524. 'top',
  4525. 'bottom',
  4526. 'right',
  4527. 'left'
  4528. ];
  4529. var timerAttr = 'data-alloy-transition-timer';
  4530. var isTransitioning$1 = function (element, transition) {
  4531. return hasAll(element, transition.classes);
  4532. };
  4533. var shouldApplyTransitionCss = function (transition, decision, lastPlacement) {
  4534. return lastPlacement.exists(function (placer) {
  4535. var mode = transition.mode;
  4536. return mode === 'all' ? true : placer[mode] !== decision[mode];
  4537. });
  4538. };
  4539. var hasChanges = function (position, intermediate) {
  4540. var round = function (value) {
  4541. return parseFloat(value).toFixed(3);
  4542. };
  4543. return find$4(intermediate, function (value, key) {
  4544. var newValue = position[key].map(round);
  4545. var val = value.map(round);
  4546. return !equals(newValue, val);
  4547. }).isSome();
  4548. };
  4549. var getTransitionDuration = function (element) {
  4550. var get = function (name) {
  4551. var style = get$c(element, name);
  4552. var times = isString(style) ? style.split(/\s*,\s*/) : [];
  4553. return filter$2(times, isNotEmpty);
  4554. };
  4555. var parse = function (value) {
  4556. if (isString(value) && /^[\d.]+/.test(value)) {
  4557. var num = parseFloat(value);
  4558. return endsWith(value, 'ms') ? num : num * 1000;
  4559. } else {
  4560. return 0;
  4561. }
  4562. };
  4563. var delay = get('transition-delay');
  4564. var duration = get('transition-duration');
  4565. return foldl(duration, function (acc, dur, i) {
  4566. var time = parse(delay[i]) + parse(dur);
  4567. return Math.max(acc, time);
  4568. }, 0);
  4569. };
  4570. var setupTransitionListeners = function (element, transition) {
  4571. var transitionEnd = unbindable();
  4572. var transitionCancel = unbindable();
  4573. var timer;
  4574. var isSourceTransition = function (e) {
  4575. var _a;
  4576. var pseudoElement = (_a = e.raw.pseudoElement) !== null && _a !== void 0 ? _a : '';
  4577. return eq(e.target, element) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName);
  4578. };
  4579. var transitionDone = function (e) {
  4580. if (isNullable(e) || isSourceTransition(e)) {
  4581. transitionEnd.clear();
  4582. transitionCancel.clear();
  4583. var type = e === null || e === void 0 ? void 0 : e.raw.type;
  4584. if (isNullable(type) || type === transitionend()) {
  4585. clearTimeout(timer);
  4586. remove$7(element, timerAttr);
  4587. remove$1(element, transition.classes);
  4588. }
  4589. }
  4590. };
  4591. var transitionStarted = function () {
  4592. transitionEnd.set(bind(element, transitionend(), transitionDone));
  4593. transitionCancel.set(bind(element, transitioncancel(), transitionDone));
  4594. };
  4595. if ('ontransitionstart' in element.dom) {
  4596. var transitionStart_1 = bind(element, transitionstart(), function (e) {
  4597. if (isSourceTransition(e)) {
  4598. transitionStart_1.unbind();
  4599. transitionStarted();
  4600. }
  4601. });
  4602. } else {
  4603. transitionStarted();
  4604. }
  4605. var duration = getTransitionDuration(element);
  4606. requestAnimationFrame(function () {
  4607. timer = setTimeout(transitionDone, duration + 17);
  4608. set$8(element, timerAttr, timer);
  4609. });
  4610. };
  4611. var startTransitioning = function (element, transition) {
  4612. add$1(element, transition.classes);
  4613. getOpt(element, timerAttr).each(function (timerId) {
  4614. clearTimeout(parseInt(timerId, 10));
  4615. remove$7(element, timerAttr);
  4616. });
  4617. setupTransitionListeners(element, transition);
  4618. };
  4619. var applyTransitionCss = function (element, origin, position, transition, decision, lastPlacement) {
  4620. var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement);
  4621. if (shouldTransition || isTransitioning$1(element, transition)) {
  4622. set$7(element, 'position', position.position);
  4623. var rect = toBox(origin, element);
  4624. var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect }));
  4625. var intermediateCssOptions = mapToObject(properties, function (prop) {
  4626. return intermediatePosition_1[prop];
  4627. });
  4628. if (hasChanges(position, intermediateCssOptions)) {
  4629. setOptions(element, intermediateCssOptions);
  4630. if (shouldTransition) {
  4631. startTransitioning(element, transition);
  4632. }
  4633. reflow(element);
  4634. }
  4635. } else {
  4636. remove$1(element, transition.classes);
  4637. }
  4638. };
  4639. var elementSize = function (p) {
  4640. return {
  4641. width: getOuter$1(p),
  4642. height: getOuter$2(p)
  4643. };
  4644. };
  4645. var layout = function (anchorBox, element, bubbles, options) {
  4646. remove$6(element, 'max-height');
  4647. remove$6(element, 'max-width');
  4648. var elementBox = elementSize(element);
  4649. return attempts(element, options.preference, anchorBox, elementBox, bubbles, options.bounds);
  4650. };
  4651. var setClasses = function (element, decision) {
  4652. var classInfo = decision.classes;
  4653. remove$1(element, classInfo.off);
  4654. add$1(element, classInfo.on);
  4655. };
  4656. var setHeight = function (element, decision, options) {
  4657. var maxHeightFunction = options.maxHeightFunction;
  4658. maxHeightFunction(element, decision.maxHeight);
  4659. };
  4660. var setWidth = function (element, decision, options) {
  4661. var maxWidthFunction = options.maxWidthFunction;
  4662. maxWidthFunction(element, decision.maxWidth);
  4663. };
  4664. var position$2 = function (element, decision, options) {
  4665. var positionCss = reposition(options.origin, decision);
  4666. options.transition.each(function (transition) {
  4667. applyTransitionCss(element, options.origin, positionCss, transition, decision, options.lastPlacement);
  4668. });
  4669. applyPositionCss(element, positionCss);
  4670. };
  4671. var setPlacement = function (element, decision) {
  4672. setPlacement$1(element, decision.placement);
  4673. };
  4674. var setMaxHeight = function (element, maxHeight) {
  4675. setMax$1(element, Math.floor(maxHeight));
  4676. };
  4677. var anchored = constant$1(function (element, available) {
  4678. setMaxHeight(element, available);
  4679. setAll(element, {
  4680. 'overflow-x': 'hidden',
  4681. 'overflow-y': 'auto'
  4682. });
  4683. });
  4684. var expandable$1 = constant$1(function (element, available) {
  4685. setMaxHeight(element, available);
  4686. });
  4687. var defaultOr = function (options, key, dephault) {
  4688. return options[key] === undefined ? dephault : options[key];
  4689. };
  4690. var simple = function (anchor, element, bubble, layouts, lastPlacement, getBounds, overrideOptions, transition) {
  4691. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4692. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4693. var anchorBox = anchor.anchorBox;
  4694. var origin = anchor.origin;
  4695. var options = {
  4696. bounds: viewport(origin, getBounds),
  4697. origin: origin,
  4698. preference: layouts,
  4699. maxHeightFunction: maxHeightFunction,
  4700. maxWidthFunction: maxWidthFunction,
  4701. lastPlacement: lastPlacement,
  4702. transition: transition
  4703. };
  4704. return go(anchorBox, element, bubble, options);
  4705. };
  4706. var go = function (anchorBox, element, bubble, options) {
  4707. var decision = layout(anchorBox, element, bubble, options);
  4708. position$2(element, decision, options);
  4709. setPlacement(element, decision);
  4710. setClasses(element, decision);
  4711. setHeight(element, decision, options);
  4712. setWidth(element, decision, options);
  4713. return {
  4714. layout: decision.layout,
  4715. placement: decision.placement
  4716. };
  4717. };
  4718. var allAlignments = [
  4719. 'valignCentre',
  4720. 'alignLeft',
  4721. 'alignRight',
  4722. 'alignCentre',
  4723. 'top',
  4724. 'bottom',
  4725. 'left',
  4726. 'right',
  4727. 'inset'
  4728. ];
  4729. var nu$5 = function (xOffset, yOffset, classes, insetModifier) {
  4730. if (insetModifier === void 0) {
  4731. insetModifier = 1;
  4732. }
  4733. var insetXOffset = xOffset * insetModifier;
  4734. var insetYOffset = yOffset * insetModifier;
  4735. var getClasses = function (prop) {
  4736. return get$e(classes, prop).getOr([]);
  4737. };
  4738. var make = function (xDelta, yDelta, alignmentsOn) {
  4739. var alignmentsOff = difference(allAlignments, alignmentsOn);
  4740. return {
  4741. offset: SugarPosition(xDelta, yDelta),
  4742. classesOn: bind$3(alignmentsOn, getClasses),
  4743. classesOff: bind$3(alignmentsOff, getClasses)
  4744. };
  4745. };
  4746. return {
  4747. southeast: function () {
  4748. return make(-xOffset, yOffset, [
  4749. 'top',
  4750. 'alignLeft'
  4751. ]);
  4752. },
  4753. southwest: function () {
  4754. return make(xOffset, yOffset, [
  4755. 'top',
  4756. 'alignRight'
  4757. ]);
  4758. },
  4759. south: function () {
  4760. return make(-xOffset / 2, yOffset, [
  4761. 'top',
  4762. 'alignCentre'
  4763. ]);
  4764. },
  4765. northeast: function () {
  4766. return make(-xOffset, -yOffset, [
  4767. 'bottom',
  4768. 'alignLeft'
  4769. ]);
  4770. },
  4771. northwest: function () {
  4772. return make(xOffset, -yOffset, [
  4773. 'bottom',
  4774. 'alignRight'
  4775. ]);
  4776. },
  4777. north: function () {
  4778. return make(-xOffset / 2, -yOffset, [
  4779. 'bottom',
  4780. 'alignCentre'
  4781. ]);
  4782. },
  4783. east: function () {
  4784. return make(xOffset, -yOffset / 2, [
  4785. 'valignCentre',
  4786. 'left'
  4787. ]);
  4788. },
  4789. west: function () {
  4790. return make(-xOffset, -yOffset / 2, [
  4791. 'valignCentre',
  4792. 'right'
  4793. ]);
  4794. },
  4795. insetNortheast: function () {
  4796. return make(insetXOffset, insetYOffset, [
  4797. 'top',
  4798. 'alignLeft',
  4799. 'inset'
  4800. ]);
  4801. },
  4802. insetNorthwest: function () {
  4803. return make(-insetXOffset, insetYOffset, [
  4804. 'top',
  4805. 'alignRight',
  4806. 'inset'
  4807. ]);
  4808. },
  4809. insetNorth: function () {
  4810. return make(-insetXOffset / 2, insetYOffset, [
  4811. 'top',
  4812. 'alignCentre',
  4813. 'inset'
  4814. ]);
  4815. },
  4816. insetSoutheast: function () {
  4817. return make(insetXOffset, -insetYOffset, [
  4818. 'bottom',
  4819. 'alignLeft',
  4820. 'inset'
  4821. ]);
  4822. },
  4823. insetSouthwest: function () {
  4824. return make(-insetXOffset, -insetYOffset, [
  4825. 'bottom',
  4826. 'alignRight',
  4827. 'inset'
  4828. ]);
  4829. },
  4830. insetSouth: function () {
  4831. return make(-insetXOffset / 2, -insetYOffset, [
  4832. 'bottom',
  4833. 'alignCentre',
  4834. 'inset'
  4835. ]);
  4836. },
  4837. insetEast: function () {
  4838. return make(-insetXOffset, -insetYOffset / 2, [
  4839. 'valignCentre',
  4840. 'right',
  4841. 'inset'
  4842. ]);
  4843. },
  4844. insetWest: function () {
  4845. return make(insetXOffset, -insetYOffset / 2, [
  4846. 'valignCentre',
  4847. 'left',
  4848. 'inset'
  4849. ]);
  4850. }
  4851. };
  4852. };
  4853. var fallback = function () {
  4854. return nu$5(0, 0, {});
  4855. };
  4856. var nu$4 = identity$1;
  4857. var onDirection = function (isLtr, isRtl) {
  4858. return function (element) {
  4859. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4860. };
  4861. };
  4862. var getDirection = function (element) {
  4863. return get$c(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4864. };
  4865. var AttributeValue;
  4866. (function (AttributeValue) {
  4867. AttributeValue['TopToBottom'] = 'toptobottom';
  4868. AttributeValue['BottomToTop'] = 'bottomtotop';
  4869. }(AttributeValue || (AttributeValue = {})));
  4870. var Attribute = 'data-alloy-vertical-dir';
  4871. var isBottomToTopDir = function (el) {
  4872. return closest$2(el, function (current) {
  4873. return isElement$2(current) && get$d(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop;
  4874. });
  4875. };
  4876. var schema$y = function () {
  4877. return optionObjOf('layouts', [
  4878. required$1('onLtr'),
  4879. required$1('onRtl'),
  4880. option('onBottomLtr'),
  4881. option('onBottomRtl')
  4882. ]);
  4883. };
  4884. var get$4 = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  4885. var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4886. var customLtr = info.layouts.map(function (ls) {
  4887. return ls.onLtr(elem);
  4888. });
  4889. var customRtl = info.layouts.map(function (ls) {
  4890. return ls.onRtl(elem);
  4891. });
  4892. var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  4893. return ls.onBottomLtr.map(function (f) {
  4894. return f(elem);
  4895. });
  4896. }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4897. var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  4898. return ls.onBottomRtl.map(function (f) {
  4899. return f(elem);
  4900. });
  4901. }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4902. var f = onDirection(ltr, rtl);
  4903. return f(elem);
  4904. };
  4905. var placement$4 = function (component, anchorInfo, origin) {
  4906. var hotspot = anchorInfo.hotspot;
  4907. var anchorBox = toBox(origin, hotspot.element);
  4908. var layouts = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element));
  4909. return Optional.some(nu$4({
  4910. anchorBox: anchorBox,
  4911. bubble: anchorInfo.bubble.getOr(fallback()),
  4912. overrides: anchorInfo.overrides,
  4913. layouts: layouts,
  4914. placer: Optional.none()
  4915. }));
  4916. };
  4917. var HotspotAnchor = [
  4918. required$1('hotspot'),
  4919. option('bubble'),
  4920. defaulted('overrides', {}),
  4921. schema$y(),
  4922. output$1('placement', placement$4)
  4923. ];
  4924. var placement$3 = function (component, anchorInfo, origin) {
  4925. var pos = translate$2(origin, anchorInfo.x, anchorInfo.y);
  4926. var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height);
  4927. var layouts = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none());
  4928. return Optional.some(nu$4({
  4929. anchorBox: anchorBox,
  4930. bubble: anchorInfo.bubble,
  4931. overrides: anchorInfo.overrides,
  4932. layouts: layouts,
  4933. placer: Optional.none()
  4934. }));
  4935. };
  4936. var MakeshiftAnchor = [
  4937. required$1('x'),
  4938. required$1('y'),
  4939. defaulted('height', 0),
  4940. defaulted('width', 0),
  4941. defaulted('bubble', fallback()),
  4942. defaulted('overrides', {}),
  4943. schema$y(),
  4944. output$1('placement', placement$3)
  4945. ];
  4946. var adt$7 = Adt.generate([
  4947. { screen: ['point'] },
  4948. {
  4949. absolute: [
  4950. 'point',
  4951. 'scrollLeft',
  4952. 'scrollTop'
  4953. ]
  4954. }
  4955. ]);
  4956. var toFixed = function (pos) {
  4957. return pos.fold(identity$1, function (point, scrollLeft, scrollTop) {
  4958. return point.translate(-scrollLeft, -scrollTop);
  4959. });
  4960. };
  4961. var toAbsolute = function (pos) {
  4962. return pos.fold(identity$1, identity$1);
  4963. };
  4964. var sum = function (points) {
  4965. return foldl(points, function (b, a) {
  4966. return b.translate(a.left, a.top);
  4967. }, SugarPosition(0, 0));
  4968. };
  4969. var sumAsFixed = function (positions) {
  4970. var points = map$2(positions, toFixed);
  4971. return sum(points);
  4972. };
  4973. var sumAsAbsolute = function (positions) {
  4974. var points = map$2(positions, toAbsolute);
  4975. return sum(points);
  4976. };
  4977. var screen = adt$7.screen;
  4978. var absolute$1 = adt$7.absolute;
  4979. var getOffset = function (component, origin, anchorInfo) {
  4980. var win = defaultView(anchorInfo.root).dom;
  4981. var hasSameOwner = function (frame) {
  4982. var frameOwner = owner$4(frame);
  4983. var compOwner = owner$4(component.element);
  4984. return eq(frameOwner, compOwner);
  4985. };
  4986. return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3);
  4987. };
  4988. var getRootPoint = function (component, origin, anchorInfo) {
  4989. var doc = owner$4(component.element);
  4990. var outerScroll = get$9(doc);
  4991. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4992. return absolute$1(offset, outerScroll.left, outerScroll.top);
  4993. };
  4994. var getBox = function (left, top, width, height) {
  4995. var point = screen(SugarPosition(left, top));
  4996. return Optional.some(pointed(point, width, height));
  4997. };
  4998. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  4999. return optBox.map(function (box) {
  5000. var points = [
  5001. rootPoint,
  5002. box.point
  5003. ];
  5004. var topLeft = cata$1(origin, function () {
  5005. return sumAsAbsolute(points);
  5006. }, function () {
  5007. return sumAsAbsolute(points);
  5008. }, function () {
  5009. return sumAsFixed(points);
  5010. });
  5011. var anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height);
  5012. var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  5013. var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl();
  5014. var layouts = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none());
  5015. return nu$4({
  5016. anchorBox: anchorBox,
  5017. bubble: anchorInfo.bubble.getOr(fallback()),
  5018. overrides: anchorInfo.overrides,
  5019. layouts: layouts,
  5020. placer: Optional.none()
  5021. });
  5022. });
  5023. };
  5024. var placement$2 = function (component, anchorInfo, origin) {
  5025. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5026. return anchorInfo.node.filter(inBody).bind(function (target) {
  5027. var rect = target.dom.getBoundingClientRect();
  5028. var nodeBox = getBox(rect.left, rect.top, rect.width, rect.height);
  5029. var elem = anchorInfo.node.getOr(component.element);
  5030. return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5031. });
  5032. };
  5033. var NodeAnchor = [
  5034. required$1('node'),
  5035. required$1('root'),
  5036. option('bubble'),
  5037. schema$y(),
  5038. defaulted('overrides', {}),
  5039. defaulted('showAbove', false),
  5040. output$1('placement', placement$2)
  5041. ];
  5042. var zeroWidth = '\uFEFF';
  5043. var nbsp = '\xA0';
  5044. var create$6 = function (start, soffset, finish, foffset) {
  5045. return {
  5046. start: start,
  5047. soffset: soffset,
  5048. finish: finish,
  5049. foffset: foffset
  5050. };
  5051. };
  5052. var SimRange = { create: create$6 };
  5053. var adt$6 = Adt.generate([
  5054. { before: ['element'] },
  5055. {
  5056. on: [
  5057. 'element',
  5058. 'offset'
  5059. ]
  5060. },
  5061. { after: ['element'] }
  5062. ]);
  5063. var cata = function (subject, onBefore, onOn, onAfter) {
  5064. return subject.fold(onBefore, onOn, onAfter);
  5065. };
  5066. var getStart$1 = function (situ) {
  5067. return situ.fold(identity$1, identity$1, identity$1);
  5068. };
  5069. var before = adt$6.before;
  5070. var on$1 = adt$6.on;
  5071. var after$1 = adt$6.after;
  5072. var Situ = {
  5073. before: before,
  5074. on: on$1,
  5075. after: after$1,
  5076. cata: cata,
  5077. getStart: getStart$1
  5078. };
  5079. var adt$5 = Adt.generate([
  5080. { domRange: ['rng'] },
  5081. {
  5082. relative: [
  5083. 'startSitu',
  5084. 'finishSitu'
  5085. ]
  5086. },
  5087. {
  5088. exact: [
  5089. 'start',
  5090. 'soffset',
  5091. 'finish',
  5092. 'foffset'
  5093. ]
  5094. }
  5095. ]);
  5096. var exactFromRange = function (simRange) {
  5097. return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  5098. };
  5099. var getStart = function (selection) {
  5100. return selection.match({
  5101. domRange: function (rng) {
  5102. return SugarElement.fromDom(rng.startContainer);
  5103. },
  5104. relative: function (startSitu, _finishSitu) {
  5105. return Situ.getStart(startSitu);
  5106. },
  5107. exact: function (start, _soffset, _finish, _foffset) {
  5108. return start;
  5109. }
  5110. });
  5111. };
  5112. var domRange = adt$5.domRange;
  5113. var relative = adt$5.relative;
  5114. var exact = adt$5.exact;
  5115. var getWin = function (selection) {
  5116. var start = getStart(selection);
  5117. return defaultView(start);
  5118. };
  5119. var range$1 = SimRange.create;
  5120. var SimSelection = {
  5121. domRange: domRange,
  5122. relative: relative,
  5123. exact: exact,
  5124. exactFromRange: exactFromRange,
  5125. getWin: getWin,
  5126. range: range$1
  5127. };
  5128. var setStart = function (rng, situ) {
  5129. situ.fold(function (e) {
  5130. rng.setStartBefore(e.dom);
  5131. }, function (e, o) {
  5132. rng.setStart(e.dom, o);
  5133. }, function (e) {
  5134. rng.setStartAfter(e.dom);
  5135. });
  5136. };
  5137. var setFinish = function (rng, situ) {
  5138. situ.fold(function (e) {
  5139. rng.setEndBefore(e.dom);
  5140. }, function (e, o) {
  5141. rng.setEnd(e.dom, o);
  5142. }, function (e) {
  5143. rng.setEndAfter(e.dom);
  5144. });
  5145. };
  5146. var relativeToNative = function (win, startSitu, finishSitu) {
  5147. var range = win.document.createRange();
  5148. setStart(range, startSitu);
  5149. setFinish(range, finishSitu);
  5150. return range;
  5151. };
  5152. var exactToNative = function (win, start, soffset, finish, foffset) {
  5153. var rng = win.document.createRange();
  5154. rng.setStart(start.dom, soffset);
  5155. rng.setEnd(finish.dom, foffset);
  5156. return rng;
  5157. };
  5158. var toRect = function (rect) {
  5159. return {
  5160. left: rect.left,
  5161. top: rect.top,
  5162. right: rect.right,
  5163. bottom: rect.bottom,
  5164. width: rect.width,
  5165. height: rect.height
  5166. };
  5167. };
  5168. var getFirstRect$1 = function (rng) {
  5169. var rects = rng.getClientRects();
  5170. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  5171. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5172. };
  5173. var getBounds$2 = function (rng) {
  5174. var rect = rng.getBoundingClientRect();
  5175. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
  5176. };
  5177. var adt$4 = Adt.generate([
  5178. {
  5179. ltr: [
  5180. 'start',
  5181. 'soffset',
  5182. 'finish',
  5183. 'foffset'
  5184. ]
  5185. },
  5186. {
  5187. rtl: [
  5188. 'start',
  5189. 'soffset',
  5190. 'finish',
  5191. 'foffset'
  5192. ]
  5193. }
  5194. ]);
  5195. var fromRange = function (win, type, range) {
  5196. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  5197. };
  5198. var getRanges = function (win, selection) {
  5199. return selection.match({
  5200. domRange: function (rng) {
  5201. return {
  5202. ltr: constant$1(rng),
  5203. rtl: Optional.none
  5204. };
  5205. },
  5206. relative: function (startSitu, finishSitu) {
  5207. return {
  5208. ltr: cached(function () {
  5209. return relativeToNative(win, startSitu, finishSitu);
  5210. }),
  5211. rtl: cached(function () {
  5212. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  5213. })
  5214. };
  5215. },
  5216. exact: function (start, soffset, finish, foffset) {
  5217. return {
  5218. ltr: cached(function () {
  5219. return exactToNative(win, start, soffset, finish, foffset);
  5220. }),
  5221. rtl: cached(function () {
  5222. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  5223. })
  5224. };
  5225. }
  5226. });
  5227. };
  5228. var doDiagnose = function (win, ranges) {
  5229. var rng = ranges.ltr();
  5230. if (rng.collapsed) {
  5231. var reversed = ranges.rtl().filter(function (rev) {
  5232. return rev.collapsed === false;
  5233. });
  5234. return reversed.map(function (rev) {
  5235. return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  5236. }).getOrThunk(function () {
  5237. return fromRange(win, adt$4.ltr, rng);
  5238. });
  5239. } else {
  5240. return fromRange(win, adt$4.ltr, rng);
  5241. }
  5242. };
  5243. var diagnose = function (win, selection) {
  5244. var ranges = getRanges(win, selection);
  5245. return doDiagnose(win, ranges);
  5246. };
  5247. var asLtrRange = function (win, selection) {
  5248. var diagnosis = diagnose(win, selection);
  5249. return diagnosis.match({
  5250. ltr: function (start, soffset, finish, foffset) {
  5251. var rng = win.document.createRange();
  5252. rng.setStart(start.dom, soffset);
  5253. rng.setEnd(finish.dom, foffset);
  5254. return rng;
  5255. },
  5256. rtl: function (start, soffset, finish, foffset) {
  5257. var rng = win.document.createRange();
  5258. rng.setStart(finish.dom, foffset);
  5259. rng.setEnd(start.dom, soffset);
  5260. return rng;
  5261. }
  5262. });
  5263. };
  5264. adt$4.ltr;
  5265. adt$4.rtl;
  5266. var NodeValue = function (is, name) {
  5267. var get = function (element) {
  5268. if (!is(element)) {
  5269. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  5270. }
  5271. return getOption(element).getOr('');
  5272. };
  5273. var getOption = function (element) {
  5274. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  5275. };
  5276. var set = function (element, value) {
  5277. if (!is(element)) {
  5278. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  5279. }
  5280. element.dom.nodeValue = value;
  5281. };
  5282. return {
  5283. get: get,
  5284. getOption: getOption,
  5285. set: set
  5286. };
  5287. };
  5288. var api = NodeValue(isText$1, 'text');
  5289. var get$3 = function (element) {
  5290. return api.get(element);
  5291. };
  5292. var getOption = function (element) {
  5293. return api.getOption(element);
  5294. };
  5295. var getEnd = function (element) {
  5296. return name$2(element) === 'img' ? 1 : getOption(element).fold(function () {
  5297. return children(element).length;
  5298. }, function (v) {
  5299. return v.length;
  5300. });
  5301. };
  5302. var isTextNodeWithCursorPosition = function (el) {
  5303. return getOption(el).filter(function (text) {
  5304. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  5305. }).isSome();
  5306. };
  5307. var elementsWithCursorPosition = [
  5308. 'img',
  5309. 'br'
  5310. ];
  5311. var isCursorPosition = function (elem) {
  5312. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  5313. return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem));
  5314. };
  5315. var last$1 = function (element) {
  5316. return descendantRtl(element, isCursorPosition);
  5317. };
  5318. var descendantRtl = function (scope, predicate) {
  5319. var descend = function (element) {
  5320. var children$1 = children(element);
  5321. for (var i = children$1.length - 1; i >= 0; i--) {
  5322. var child = children$1[i];
  5323. if (predicate(child)) {
  5324. return Optional.some(child);
  5325. }
  5326. var res = descend(child);
  5327. if (res.isSome()) {
  5328. return res;
  5329. }
  5330. }
  5331. return Optional.none();
  5332. };
  5333. return descend(scope);
  5334. };
  5335. var descendants = function (scope, selector) {
  5336. return all$3(selector, scope);
  5337. };
  5338. var makeRange = function (start, soffset, finish, foffset) {
  5339. var doc = owner$4(start);
  5340. var rng = doc.dom.createRange();
  5341. rng.setStart(start.dom, soffset);
  5342. rng.setEnd(finish.dom, foffset);
  5343. return rng;
  5344. };
  5345. var after = function (start, soffset, finish, foffset) {
  5346. var r = makeRange(start, soffset, finish, foffset);
  5347. var same = eq(start, finish) && soffset === foffset;
  5348. return r.collapsed && !same;
  5349. };
  5350. var getNativeSelection = function (win) {
  5351. return Optional.from(win.getSelection());
  5352. };
  5353. var readRange = function (selection) {
  5354. if (selection.rangeCount > 0) {
  5355. var firstRng = selection.getRangeAt(0);
  5356. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  5357. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  5358. } else {
  5359. return Optional.none();
  5360. }
  5361. };
  5362. var doGetExact = function (selection) {
  5363. if (selection.anchorNode === null || selection.focusNode === null) {
  5364. return readRange(selection);
  5365. } else {
  5366. var anchor = SugarElement.fromDom(selection.anchorNode);
  5367. var focus_1 = SugarElement.fromDom(selection.focusNode);
  5368. return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  5369. }
  5370. };
  5371. var getExact = function (win) {
  5372. return getNativeSelection(win).filter(function (sel) {
  5373. return sel.rangeCount > 0;
  5374. }).bind(doGetExact);
  5375. };
  5376. var getFirstRect = function (win, selection) {
  5377. var rng = asLtrRange(win, selection);
  5378. return getFirstRect$1(rng);
  5379. };
  5380. var getBounds$1 = function (win, selection) {
  5381. var rng = asLtrRange(win, selection);
  5382. return getBounds$2(rng);
  5383. };
  5384. var point$1 = function (element, offset) {
  5385. return {
  5386. element: element,
  5387. offset: offset
  5388. };
  5389. };
  5390. var descendOnce$1 = function (element, offset) {
  5391. var children$1 = children(element);
  5392. if (children$1.length === 0) {
  5393. return point$1(element, offset);
  5394. } else if (offset < children$1.length) {
  5395. return point$1(children$1[offset], 0);
  5396. } else {
  5397. var last = children$1[children$1.length - 1];
  5398. var len = isText$1(last) ? get$3(last).length : children(last).length;
  5399. return point$1(last, len);
  5400. }
  5401. };
  5402. var descendOnce = function (element, offset) {
  5403. return isText$1(element) ? point$1(element, offset) : descendOnce$1(element, offset);
  5404. };
  5405. var getAnchorSelection = function (win, anchorInfo) {
  5406. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  5407. return function () {
  5408. return getExact(win);
  5409. };
  5410. });
  5411. return getSelection().map(function (sel) {
  5412. var modStart = descendOnce(sel.start, sel.soffset);
  5413. var modFinish = descendOnce(sel.finish, sel.foffset);
  5414. return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  5415. });
  5416. };
  5417. var placement$1 = function (component, anchorInfo, origin) {
  5418. var win = defaultView(anchorInfo.root).dom;
  5419. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5420. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5421. var optRect = getBounds$1(win, SimSelection.exactFromRange(sel)).orThunk(function () {
  5422. var x = SugarElement.fromText(zeroWidth);
  5423. before$2(sel.start, x);
  5424. var rect = getFirstRect(win, SimSelection.exact(x, 0, x, 1));
  5425. remove$5(x);
  5426. return rect;
  5427. });
  5428. return optRect.bind(function (rawRect) {
  5429. return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height);
  5430. });
  5431. });
  5432. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5433. return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start);
  5434. });
  5435. var elem = targetElement.getOr(component.element);
  5436. return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  5437. };
  5438. var SelectionAnchor = [
  5439. option('getSelection'),
  5440. required$1('root'),
  5441. option('bubble'),
  5442. schema$y(),
  5443. defaulted('overrides', {}),
  5444. defaulted('showAbove', false),
  5445. output$1('placement', placement$1)
  5446. ];
  5447. var labelPrefix$1 = 'link-layout';
  5448. var eastX = function (anchor) {
  5449. return anchor.x + anchor.width;
  5450. };
  5451. var westX = function (anchor, element) {
  5452. return anchor.x - element.width;
  5453. };
  5454. var northY$1 = function (anchor, element) {
  5455. return anchor.y - element.height + anchor.height;
  5456. };
  5457. var southY$1 = function (anchor) {
  5458. return anchor.y;
  5459. };
  5460. var southeast$1 = function (anchor, element, bubbles) {
  5461. return nu$6(eastX(anchor), southY$1(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, {
  5462. left: 0,
  5463. top: 2
  5464. }), labelPrefix$1);
  5465. };
  5466. var southwest$1 = function (anchor, element, bubbles) {
  5467. return nu$6(westX(anchor, element), southY$1(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, {
  5468. right: 1,
  5469. top: 2
  5470. }), labelPrefix$1);
  5471. };
  5472. var northeast$1 = function (anchor, element, bubbles) {
  5473. return nu$6(eastX(anchor), northY$1(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, {
  5474. left: 0,
  5475. bottom: 3
  5476. }), labelPrefix$1);
  5477. };
  5478. var northwest$1 = function (anchor, element, bubbles) {
  5479. return nu$6(westX(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, {
  5480. right: 1,
  5481. bottom: 3
  5482. }), labelPrefix$1);
  5483. };
  5484. var all = function () {
  5485. return [
  5486. southeast$1,
  5487. southwest$1,
  5488. northeast$1,
  5489. northwest$1
  5490. ];
  5491. };
  5492. var allRtl = function () {
  5493. return [
  5494. southwest$1,
  5495. southeast$1,
  5496. northwest$1,
  5497. northeast$1
  5498. ];
  5499. };
  5500. var placement = function (component, submenuInfo, origin) {
  5501. var anchorBox = toBox(origin, submenuInfo.item.element);
  5502. var layouts = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none());
  5503. return Optional.some(nu$4({
  5504. anchorBox: anchorBox,
  5505. bubble: fallback(),
  5506. overrides: submenuInfo.overrides,
  5507. layouts: layouts,
  5508. placer: Optional.none()
  5509. }));
  5510. };
  5511. var SubmenuAnchor = [
  5512. required$1('item'),
  5513. schema$y(),
  5514. defaulted('overrides', {}),
  5515. output$1('placement', placement)
  5516. ];
  5517. var AnchorSchema = choose$1('type', {
  5518. selection: SelectionAnchor,
  5519. node: NodeAnchor,
  5520. hotspot: HotspotAnchor,
  5521. submenu: SubmenuAnchor,
  5522. makeshift: MakeshiftAnchor
  5523. });
  5524. var TransitionSchema = [
  5525. requiredArrayOf('classes', string),
  5526. defaultedStringEnum('mode', 'all', [
  5527. 'all',
  5528. 'layout',
  5529. 'placement'
  5530. ])
  5531. ];
  5532. var PositionSchema = [
  5533. defaulted('useFixed', never),
  5534. option('getBounds')
  5535. ];
  5536. var PlacementSchema = [
  5537. requiredOf('anchor', AnchorSchema),
  5538. optionObjOf('transition', TransitionSchema)
  5539. ];
  5540. var getFixedOrigin = function () {
  5541. var html = document.documentElement;
  5542. return fixed$1(0, 0, html.clientWidth, html.clientHeight);
  5543. };
  5544. var getRelativeOrigin = function (component) {
  5545. var position = absolute$3(component.element);
  5546. var bounds = component.element.dom.getBoundingClientRect();
  5547. return relative$1(position.left, position.top, bounds.width, bounds.height);
  5548. };
  5549. var place = function (component, origin, anchoring, getBounds, placee, lastPlace, transition) {
  5550. var anchor = box(anchoring.anchorBox, origin);
  5551. return simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds, anchoring.overrides, transition);
  5552. };
  5553. var position$1 = function (component, posConfig, posState, placee, placementSpec) {
  5554. positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none());
  5555. };
  5556. var positionWithin = function (component, posConfig, posState, placee, placementSpec, boxElement) {
  5557. var boundsBox = boxElement.map(box$1);
  5558. return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox);
  5559. };
  5560. var positionWithinBounds = function (component, posConfig, posState, placee, placementSpec, bounds) {
  5561. var placeeDetail = asRawOrDie$1('placement.info', objOf(PlacementSchema), placementSpec);
  5562. var anchorage = placeeDetail.anchor;
  5563. var element = placee.element;
  5564. var placeeState = posState.get(placee.uid);
  5565. preserve$1(function () {
  5566. set$7(element, 'position', 'fixed');
  5567. var oldVisibility = getRaw(element, 'visibility');
  5568. set$7(element, 'visibility', 'hidden');
  5569. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5570. var placer = anchorage.placement;
  5571. var getBounds = bounds.map(constant$1).or(posConfig.getBounds);
  5572. placer(component, anchorage, origin).each(function (anchoring) {
  5573. var doPlace = anchoring.placer.getOr(place);
  5574. var newState = doPlace(component, origin, anchoring, getBounds, placee, placeeState, placeeDetail.transition);
  5575. posState.set(placee.uid, newState);
  5576. });
  5577. oldVisibility.fold(function () {
  5578. remove$6(element, 'visibility');
  5579. }, function (vis) {
  5580. set$7(element, 'visibility', vis);
  5581. });
  5582. if (getRaw(element, 'left').isNone() && getRaw(element, 'top').isNone() && getRaw(element, 'right').isNone() && getRaw(element, 'bottom').isNone() && is$1(getRaw(element, 'position'), 'fixed')) {
  5583. remove$6(element, 'position');
  5584. }
  5585. }, element);
  5586. };
  5587. var getMode = function (component, pConfig, _pState) {
  5588. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5589. };
  5590. var reset$1 = function (component, pConfig, posState, placee) {
  5591. var element = placee.element;
  5592. each$1([
  5593. 'position',
  5594. 'left',
  5595. 'right',
  5596. 'top',
  5597. 'bottom'
  5598. ], function (prop) {
  5599. return remove$6(element, prop);
  5600. });
  5601. reset$2(element);
  5602. posState.clear(placee.uid);
  5603. };
  5604. var PositionApis = /*#__PURE__*/Object.freeze({
  5605. __proto__: null,
  5606. position: position$1,
  5607. positionWithin: positionWithin,
  5608. positionWithinBounds: positionWithinBounds,
  5609. getMode: getMode,
  5610. reset: reset$1
  5611. });
  5612. var init$g = function () {
  5613. var state = {};
  5614. var set = function (id, data) {
  5615. state[id] = data;
  5616. };
  5617. var get = function (id) {
  5618. return get$e(state, id);
  5619. };
  5620. var clear = function (id) {
  5621. if (isNonNullable(id)) {
  5622. delete state[id];
  5623. } else {
  5624. state = {};
  5625. }
  5626. };
  5627. return nu$8({
  5628. readState: function () {
  5629. return state;
  5630. },
  5631. clear: clear,
  5632. set: set,
  5633. get: get
  5634. });
  5635. };
  5636. var PositioningState = /*#__PURE__*/Object.freeze({
  5637. __proto__: null,
  5638. init: init$g
  5639. });
  5640. var Positioning = create$7({
  5641. fields: PositionSchema,
  5642. name: 'positioning',
  5643. active: ActivePosition,
  5644. apis: PositionApis,
  5645. state: PositioningState
  5646. });
  5647. var fireDetaching = function (component) {
  5648. emit(component, detachedFromDom());
  5649. var children = component.components();
  5650. each$1(children, fireDetaching);
  5651. };
  5652. var fireAttaching = function (component) {
  5653. var children = component.components();
  5654. each$1(children, fireAttaching);
  5655. emit(component, attachedToDom());
  5656. };
  5657. var attach$1 = function (parent, child) {
  5658. append$2(parent.element, child.element);
  5659. };
  5660. var detachChildren$1 = function (component) {
  5661. each$1(component.components(), function (childComp) {
  5662. return remove$5(childComp.element);
  5663. });
  5664. empty(component.element);
  5665. component.syncComponents();
  5666. };
  5667. var replaceChildren = function (component, newChildren) {
  5668. var subs = component.components();
  5669. detachChildren$1(component);
  5670. var deleted = difference(subs, newChildren);
  5671. each$1(deleted, function (comp) {
  5672. fireDetaching(comp);
  5673. component.getSystem().removeFromWorld(comp);
  5674. });
  5675. each$1(newChildren, function (childComp) {
  5676. if (!childComp.getSystem().isConnected()) {
  5677. component.getSystem().addToWorld(childComp);
  5678. attach$1(component, childComp);
  5679. if (inBody(component.element)) {
  5680. fireAttaching(childComp);
  5681. }
  5682. } else {
  5683. attach$1(component, childComp);
  5684. }
  5685. component.syncComponents();
  5686. });
  5687. };
  5688. var attach = function (parent, child) {
  5689. attachWith(parent, child, append$2);
  5690. };
  5691. var attachWith = function (parent, child, insertion) {
  5692. parent.getSystem().addToWorld(child);
  5693. insertion(parent.element, child.element);
  5694. if (inBody(parent.element)) {
  5695. fireAttaching(child);
  5696. }
  5697. parent.syncComponents();
  5698. };
  5699. var doDetach = function (component) {
  5700. fireDetaching(component);
  5701. remove$5(component.element);
  5702. component.getSystem().removeFromWorld(component);
  5703. };
  5704. var detach = function (component) {
  5705. var parent$1 = parent(component.element).bind(function (p) {
  5706. return component.getSystem().getByDom(p).toOptional();
  5707. });
  5708. doDetach(component);
  5709. parent$1.each(function (p) {
  5710. p.syncComponents();
  5711. });
  5712. };
  5713. var detachChildren = function (component) {
  5714. var subs = component.components();
  5715. each$1(subs, doDetach);
  5716. empty(component.element);
  5717. component.syncComponents();
  5718. };
  5719. var attachSystem = function (element, guiSystem) {
  5720. attachSystemWith(element, guiSystem, append$2);
  5721. };
  5722. var attachSystemAfter = function (element, guiSystem) {
  5723. attachSystemWith(element, guiSystem, after$2);
  5724. };
  5725. var attachSystemWith = function (element, guiSystem, inserter) {
  5726. inserter(element, guiSystem.element);
  5727. var children$1 = children(guiSystem.element);
  5728. each$1(children$1, function (child) {
  5729. guiSystem.getByDom(child).each(fireAttaching);
  5730. });
  5731. };
  5732. var detachSystem = function (guiSystem) {
  5733. var children$1 = children(guiSystem.element);
  5734. each$1(children$1, function (child) {
  5735. guiSystem.getByDom(child).each(fireDetaching);
  5736. });
  5737. remove$5(guiSystem.element);
  5738. };
  5739. var rebuild = function (sandbox, sConfig, sState, data) {
  5740. sState.get().each(function (_data) {
  5741. detachChildren(sandbox);
  5742. });
  5743. var point = sConfig.getAttachPoint(sandbox);
  5744. attach(point, sandbox);
  5745. var built = sandbox.getSystem().build(data);
  5746. attach(sandbox, built);
  5747. sState.set(built);
  5748. return built;
  5749. };
  5750. var open$1 = function (sandbox, sConfig, sState, data) {
  5751. var newState = rebuild(sandbox, sConfig, sState, data);
  5752. sConfig.onOpen(sandbox, newState);
  5753. return newState;
  5754. };
  5755. var setContent = function (sandbox, sConfig, sState, data) {
  5756. return sState.get().map(function () {
  5757. return rebuild(sandbox, sConfig, sState, data);
  5758. });
  5759. };
  5760. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5761. cloak(sandbox, sConfig);
  5762. open$1(sandbox, sConfig, sState, data);
  5763. transaction();
  5764. decloak(sandbox, sConfig);
  5765. };
  5766. var close$1 = function (sandbox, sConfig, sState) {
  5767. sState.get().each(function (data) {
  5768. detachChildren(sandbox);
  5769. detach(sandbox);
  5770. sConfig.onClose(sandbox, data);
  5771. sState.clear();
  5772. });
  5773. };
  5774. var isOpen$1 = function (_sandbox, _sConfig, sState) {
  5775. return sState.isOpen();
  5776. };
  5777. var isPartOf = function (sandbox, sConfig, sState, queryElem) {
  5778. return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5779. return sConfig.isPartOf(sandbox, data, queryElem);
  5780. });
  5781. };
  5782. var getState$2 = function (_sandbox, _sConfig, sState) {
  5783. return sState.get();
  5784. };
  5785. var store = function (sandbox, cssKey, attr, newValue) {
  5786. getRaw(sandbox.element, cssKey).fold(function () {
  5787. remove$7(sandbox.element, attr);
  5788. }, function (v) {
  5789. set$8(sandbox.element, attr, v);
  5790. });
  5791. set$7(sandbox.element, cssKey, newValue);
  5792. };
  5793. var restore = function (sandbox, cssKey, attr) {
  5794. getOpt(sandbox.element, attr).fold(function () {
  5795. return remove$6(sandbox.element, cssKey);
  5796. }, function (oldValue) {
  5797. return set$7(sandbox.element, cssKey, oldValue);
  5798. });
  5799. };
  5800. var cloak = function (sandbox, sConfig, _sState) {
  5801. var sink = sConfig.getAttachPoint(sandbox);
  5802. set$7(sandbox.element, 'position', Positioning.getMode(sink));
  5803. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5804. };
  5805. var hasPosition = function (element) {
  5806. return exists([
  5807. 'top',
  5808. 'left',
  5809. 'right',
  5810. 'bottom'
  5811. ], function (pos) {
  5812. return getRaw(element, pos).isSome();
  5813. });
  5814. };
  5815. var decloak = function (sandbox, sConfig, _sState) {
  5816. if (!hasPosition(sandbox.element)) {
  5817. remove$6(sandbox.element, 'position');
  5818. }
  5819. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5820. };
  5821. var SandboxApis = /*#__PURE__*/Object.freeze({
  5822. __proto__: null,
  5823. cloak: cloak,
  5824. decloak: decloak,
  5825. open: open$1,
  5826. openWhileCloaked: openWhileCloaked,
  5827. close: close$1,
  5828. isOpen: isOpen$1,
  5829. isPartOf: isPartOf,
  5830. getState: getState$2,
  5831. setContent: setContent
  5832. });
  5833. var events$g = function (sandboxConfig, sandboxState) {
  5834. return derive$2([run$1(sandboxClose(), function (sandbox, _simulatedEvent) {
  5835. close$1(sandbox, sandboxConfig, sandboxState);
  5836. })]);
  5837. };
  5838. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5839. __proto__: null,
  5840. events: events$g
  5841. });
  5842. var SandboxSchema = [
  5843. onHandler('onOpen'),
  5844. onHandler('onClose'),
  5845. required$1('isPartOf'),
  5846. required$1('getAttachPoint'),
  5847. defaulted('cloakVisibilityAttr', 'data-precloak-visibility')
  5848. ];
  5849. var init$f = function () {
  5850. var contents = value$1();
  5851. var readState = constant$1('not-implemented');
  5852. return nu$8({
  5853. readState: readState,
  5854. isOpen: contents.isSet,
  5855. clear: contents.clear,
  5856. set: contents.set,
  5857. get: contents.get
  5858. });
  5859. };
  5860. var SandboxState = /*#__PURE__*/Object.freeze({
  5861. __proto__: null,
  5862. init: init$f
  5863. });
  5864. var Sandboxing = create$7({
  5865. fields: SandboxSchema,
  5866. name: 'sandboxing',
  5867. active: ActiveSandbox,
  5868. apis: SandboxApis,
  5869. state: SandboxState
  5870. });
  5871. var dismissPopups = constant$1('dismiss.popups');
  5872. var repositionPopups = constant$1('reposition.popups');
  5873. var mouseReleased = constant$1('mouse.released');
  5874. var schema$x = objOfOnly([
  5875. defaulted('isExtraPart', never),
  5876. optionObjOf('fireEventInstead', [defaulted('event', dismissRequested())])
  5877. ]);
  5878. var receivingChannel$1 = function (rawSpec) {
  5879. var _a;
  5880. var detail = asRawOrDie$1('Dismissal', schema$x, rawSpec);
  5881. return _a = {}, _a[dismissPopups()] = {
  5882. schema: objOfOnly([required$1('target')]),
  5883. onReceive: function (sandbox, data) {
  5884. if (Sandboxing.isOpen(sandbox)) {
  5885. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5886. if (!isPart) {
  5887. detail.fireEventInstead.fold(function () {
  5888. return Sandboxing.close(sandbox);
  5889. }, function (fe) {
  5890. return emit(sandbox, fe.event);
  5891. });
  5892. }
  5893. }
  5894. }
  5895. }, _a;
  5896. };
  5897. var schema$w = objOfOnly([
  5898. optionObjOf('fireEventInstead', [defaulted('event', repositionRequested())]),
  5899. requiredFunction('doReposition')
  5900. ]);
  5901. var receivingChannel = function (rawSpec) {
  5902. var _a;
  5903. var detail = asRawOrDie$1('Reposition', schema$w, rawSpec);
  5904. return _a = {}, _a[repositionPopups()] = {
  5905. onReceive: function (sandbox) {
  5906. if (Sandboxing.isOpen(sandbox)) {
  5907. detail.fireEventInstead.fold(function () {
  5908. return detail.doReposition(sandbox);
  5909. }, function (fe) {
  5910. return emit(sandbox, fe.event);
  5911. });
  5912. }
  5913. }
  5914. }, _a;
  5915. };
  5916. var onLoad$5 = function (component, repConfig, repState) {
  5917. repConfig.store.manager.onLoad(component, repConfig, repState);
  5918. };
  5919. var onUnload$2 = function (component, repConfig, repState) {
  5920. repConfig.store.manager.onUnload(component, repConfig, repState);
  5921. };
  5922. var setValue$3 = function (component, repConfig, repState, data) {
  5923. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5924. };
  5925. var getValue$3 = function (component, repConfig, repState) {
  5926. return repConfig.store.manager.getValue(component, repConfig, repState);
  5927. };
  5928. var getState$1 = function (component, repConfig, repState) {
  5929. return repState;
  5930. };
  5931. var RepresentApis = /*#__PURE__*/Object.freeze({
  5932. __proto__: null,
  5933. onLoad: onLoad$5,
  5934. onUnload: onUnload$2,
  5935. setValue: setValue$3,
  5936. getValue: getValue$3,
  5937. getState: getState$1
  5938. });
  5939. var events$f = function (repConfig, repState) {
  5940. var es = repConfig.resetOnDom ? [
  5941. runOnAttached(function (comp, _se) {
  5942. onLoad$5(comp, repConfig, repState);
  5943. }),
  5944. runOnDetached(function (comp, _se) {
  5945. onUnload$2(comp, repConfig, repState);
  5946. })
  5947. ] : [loadEvent(repConfig, repState, onLoad$5)];
  5948. return derive$2(es);
  5949. };
  5950. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5951. __proto__: null,
  5952. events: events$f
  5953. });
  5954. var memory$1 = function () {
  5955. var data = Cell(null);
  5956. var readState = function () {
  5957. return {
  5958. mode: 'memory',
  5959. value: data.get()
  5960. };
  5961. };
  5962. var isNotSet = function () {
  5963. return data.get() === null;
  5964. };
  5965. var clear = function () {
  5966. data.set(null);
  5967. };
  5968. return nu$8({
  5969. set: data.set,
  5970. get: data.get,
  5971. isNotSet: isNotSet,
  5972. clear: clear,
  5973. readState: readState
  5974. });
  5975. };
  5976. var manual = function () {
  5977. var readState = noop;
  5978. return nu$8({ readState: readState });
  5979. };
  5980. var dataset = function () {
  5981. var dataByValue = Cell({});
  5982. var dataByText = Cell({});
  5983. var readState = function () {
  5984. return {
  5985. mode: 'dataset',
  5986. dataByValue: dataByValue.get(),
  5987. dataByText: dataByText.get()
  5988. };
  5989. };
  5990. var clear = function () {
  5991. dataByValue.set({});
  5992. dataByText.set({});
  5993. };
  5994. var lookup = function (itemString) {
  5995. return get$e(dataByValue.get(), itemString).orThunk(function () {
  5996. return get$e(dataByText.get(), itemString);
  5997. });
  5998. };
  5999. var update = function (items) {
  6000. var currentDataByValue = dataByValue.get();
  6001. var currentDataByText = dataByText.get();
  6002. var newDataByValue = {};
  6003. var newDataByText = {};
  6004. each$1(items, function (item) {
  6005. newDataByValue[item.value] = item;
  6006. get$e(item, 'meta').each(function (meta) {
  6007. get$e(meta, 'text').each(function (text) {
  6008. newDataByText[text] = item;
  6009. });
  6010. });
  6011. });
  6012. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  6013. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  6014. };
  6015. return nu$8({
  6016. readState: readState,
  6017. lookup: lookup,
  6018. update: update,
  6019. clear: clear
  6020. });
  6021. };
  6022. var init$e = function (spec) {
  6023. return spec.store.manager.state(spec);
  6024. };
  6025. var RepresentState = /*#__PURE__*/Object.freeze({
  6026. __proto__: null,
  6027. memory: memory$1,
  6028. dataset: dataset,
  6029. manual: manual,
  6030. init: init$e
  6031. });
  6032. var setValue$2 = function (component, repConfig, repState, data) {
  6033. var store = repConfig.store;
  6034. repState.update([data]);
  6035. store.setValue(component, data);
  6036. repConfig.onSetValue(component, data);
  6037. };
  6038. var getValue$2 = function (component, repConfig, repState) {
  6039. var store = repConfig.store;
  6040. var key = store.getDataKey(component);
  6041. return repState.lookup(key).getOrThunk(function () {
  6042. return store.getFallbackEntry(key);
  6043. });
  6044. };
  6045. var onLoad$4 = function (component, repConfig, repState) {
  6046. var store = repConfig.store;
  6047. store.initialValue.each(function (data) {
  6048. setValue$2(component, repConfig, repState, data);
  6049. });
  6050. };
  6051. var onUnload$1 = function (component, repConfig, repState) {
  6052. repState.clear();
  6053. };
  6054. var DatasetStore = [
  6055. option('initialValue'),
  6056. required$1('getFallbackEntry'),
  6057. required$1('getDataKey'),
  6058. required$1('setValue'),
  6059. output$1('manager', {
  6060. setValue: setValue$2,
  6061. getValue: getValue$2,
  6062. onLoad: onLoad$4,
  6063. onUnload: onUnload$1,
  6064. state: dataset
  6065. })
  6066. ];
  6067. var getValue$1 = function (component, repConfig, _repState) {
  6068. return repConfig.store.getValue(component);
  6069. };
  6070. var setValue$1 = function (component, repConfig, _repState, data) {
  6071. repConfig.store.setValue(component, data);
  6072. repConfig.onSetValue(component, data);
  6073. };
  6074. var onLoad$3 = function (component, repConfig, _repState) {
  6075. repConfig.store.initialValue.each(function (data) {
  6076. repConfig.store.setValue(component, data);
  6077. });
  6078. };
  6079. var ManualStore = [
  6080. required$1('getValue'),
  6081. defaulted('setValue', noop),
  6082. option('initialValue'),
  6083. output$1('manager', {
  6084. setValue: setValue$1,
  6085. getValue: getValue$1,
  6086. onLoad: onLoad$3,
  6087. onUnload: noop,
  6088. state: NoState.init
  6089. })
  6090. ];
  6091. var setValue = function (component, repConfig, repState, data) {
  6092. repState.set(data);
  6093. repConfig.onSetValue(component, data);
  6094. };
  6095. var getValue = function (component, repConfig, repState) {
  6096. return repState.get();
  6097. };
  6098. var onLoad$2 = function (component, repConfig, repState) {
  6099. repConfig.store.initialValue.each(function (initVal) {
  6100. if (repState.isNotSet()) {
  6101. repState.set(initVal);
  6102. }
  6103. });
  6104. };
  6105. var onUnload = function (component, repConfig, repState) {
  6106. repState.clear();
  6107. };
  6108. var MemoryStore = [
  6109. option('initialValue'),
  6110. output$1('manager', {
  6111. setValue: setValue,
  6112. getValue: getValue,
  6113. onLoad: onLoad$2,
  6114. onUnload: onUnload,
  6115. state: memory$1
  6116. })
  6117. ];
  6118. var RepresentSchema = [
  6119. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  6120. memory: MemoryStore,
  6121. manual: ManualStore,
  6122. dataset: DatasetStore
  6123. })),
  6124. onHandler('onSetValue'),
  6125. defaulted('resetOnDom', false)
  6126. ];
  6127. var Representing = create$7({
  6128. fields: RepresentSchema,
  6129. name: 'representing',
  6130. active: ActiveRepresenting,
  6131. apis: RepresentApis,
  6132. extra: {
  6133. setValueFrom: function (component, source) {
  6134. var value = Representing.getValue(source);
  6135. Representing.setValue(component, value);
  6136. }
  6137. },
  6138. state: RepresentState
  6139. });
  6140. var field = function (name, forbidden) {
  6141. return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  6142. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  6143. }).concat([customField('dump', identity$1)]));
  6144. };
  6145. var get$2 = function (data) {
  6146. return data.dump;
  6147. };
  6148. var augment = function (data, original) {
  6149. return __assign(__assign({}, derive$1(original)), data.dump);
  6150. };
  6151. var SketchBehaviours = {
  6152. field: field,
  6153. augment: augment,
  6154. get: get$2
  6155. };
  6156. var _placeholder = 'placeholder';
  6157. var adt$3 = Adt.generate([
  6158. {
  6159. single: [
  6160. 'required',
  6161. 'valueThunk'
  6162. ]
  6163. },
  6164. {
  6165. multiple: [
  6166. 'required',
  6167. 'valueThunks'
  6168. ]
  6169. }
  6170. ]);
  6171. var isSubstituted = function (spec) {
  6172. return has$2(spec, 'uiType');
  6173. };
  6174. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  6175. if (owner.exists(function (o) {
  6176. return o !== compSpec.owner;
  6177. })) {
  6178. return adt$3.single(true, constant$1(compSpec));
  6179. }
  6180. return get$e(placeholders, compSpec.name).fold(function () {
  6181. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  6182. }, function (newSpec) {
  6183. return newSpec.replace();
  6184. });
  6185. };
  6186. var scan = function (owner, detail, compSpec, placeholders) {
  6187. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  6188. return subPlaceholder(owner, detail, compSpec, placeholders);
  6189. } else {
  6190. return adt$3.single(false, constant$1(compSpec));
  6191. }
  6192. };
  6193. var substitute = function (owner, detail, compSpec, placeholders) {
  6194. var base = scan(owner, detail, compSpec, placeholders);
  6195. return base.fold(function (req, valueThunk) {
  6196. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  6197. var childSpecs = get$e(value, 'components').getOr([]);
  6198. var substituted = bind$3(childSpecs, function (c) {
  6199. return substitute(owner, detail, c, placeholders);
  6200. });
  6201. return [__assign(__assign({}, value), { components: substituted })];
  6202. }, function (req, valuesThunk) {
  6203. if (isSubstituted(compSpec)) {
  6204. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  6205. var preprocessor = compSpec.validated.preprocess.getOr(identity$1);
  6206. return preprocessor(values);
  6207. } else {
  6208. return valuesThunk(detail);
  6209. }
  6210. });
  6211. };
  6212. var substituteAll = function (owner, detail, components, placeholders) {
  6213. return bind$3(components, function (c) {
  6214. return substitute(owner, detail, c, placeholders);
  6215. });
  6216. };
  6217. var oneReplace = function (label, replacements) {
  6218. var called = false;
  6219. var used = function () {
  6220. return called;
  6221. };
  6222. var replace = function () {
  6223. if (called) {
  6224. throw new Error('Trying to use the same placeholder more than once: ' + label);
  6225. }
  6226. called = true;
  6227. return replacements;
  6228. };
  6229. var required = function () {
  6230. return replacements.fold(function (req, _) {
  6231. return req;
  6232. }, function (req, _) {
  6233. return req;
  6234. });
  6235. };
  6236. return {
  6237. name: constant$1(label),
  6238. required: required,
  6239. used: used,
  6240. replace: replace
  6241. };
  6242. };
  6243. var substitutePlaces = function (owner, detail, components, placeholders) {
  6244. var ps = map$1(placeholders, function (ph, name) {
  6245. return oneReplace(name, ph);
  6246. });
  6247. var outcome = substituteAll(owner, detail, components, ps);
  6248. each(ps, function (p) {
  6249. if (p.used() === false && p.required()) {
  6250. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  6251. }
  6252. });
  6253. return outcome;
  6254. };
  6255. var single$2 = adt$3.single;
  6256. var multiple = adt$3.multiple;
  6257. var placeholder = constant$1(_placeholder);
  6258. var adt$2 = Adt.generate([
  6259. { required: ['data'] },
  6260. { external: ['data'] },
  6261. { optional: ['data'] },
  6262. { group: ['data'] }
  6263. ]);
  6264. var fFactory = defaulted('factory', { sketch: identity$1 });
  6265. var fSchema = defaulted('schema', []);
  6266. var fName = required$1('name');
  6267. var fPname = field$1('pname', 'pname', defaultedThunk(function (typeSpec) {
  6268. return '<alloy.' + generate$6(typeSpec.name) + '>';
  6269. }), anyValue());
  6270. var fGroupSchema = customField('schema', function () {
  6271. return [option('preprocess')];
  6272. });
  6273. var fDefaults = defaulted('defaults', constant$1({}));
  6274. var fOverrides = defaulted('overrides', constant$1({}));
  6275. var requiredSpec = objOf([
  6276. fFactory,
  6277. fSchema,
  6278. fName,
  6279. fPname,
  6280. fDefaults,
  6281. fOverrides
  6282. ]);
  6283. var externalSpec = objOf([
  6284. fFactory,
  6285. fSchema,
  6286. fName,
  6287. fDefaults,
  6288. fOverrides
  6289. ]);
  6290. var optionalSpec = objOf([
  6291. fFactory,
  6292. fSchema,
  6293. fName,
  6294. fPname,
  6295. fDefaults,
  6296. fOverrides
  6297. ]);
  6298. var groupSpec = objOf([
  6299. fFactory,
  6300. fGroupSchema,
  6301. fName,
  6302. required$1('unit'),
  6303. fPname,
  6304. fDefaults,
  6305. fOverrides
  6306. ]);
  6307. var asNamedPart = function (part) {
  6308. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  6309. };
  6310. var name$1 = function (part) {
  6311. var get = function (data) {
  6312. return data.name;
  6313. };
  6314. return part.fold(get, get, get, get);
  6315. };
  6316. var asCommon = function (part) {
  6317. return part.fold(identity$1, identity$1, identity$1, identity$1);
  6318. };
  6319. var convert = function (adtConstructor, partSchema) {
  6320. return function (spec) {
  6321. var data = asRawOrDie$1('Converting part type', partSchema, spec);
  6322. return adtConstructor(data);
  6323. };
  6324. };
  6325. var required = convert(adt$2.required, requiredSpec);
  6326. var external$1 = convert(adt$2.external, externalSpec);
  6327. var optional = convert(adt$2.optional, optionalSpec);
  6328. var group = convert(adt$2.group, groupSpec);
  6329. var original = constant$1('entirety');
  6330. var PartType = /*#__PURE__*/Object.freeze({
  6331. __proto__: null,
  6332. required: required,
  6333. external: external$1,
  6334. optional: optional,
  6335. group: group,
  6336. asNamedPart: asNamedPart,
  6337. name: name$1,
  6338. asCommon: asCommon,
  6339. original: original
  6340. });
  6341. var combine = function (detail, data, partSpec, partValidated) {
  6342. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  6343. };
  6344. var subs = function (owner, detail, parts) {
  6345. var internals = {};
  6346. var externals = {};
  6347. each$1(parts, function (part) {
  6348. part.fold(function (data) {
  6349. internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  6350. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6351. });
  6352. }, function (data) {
  6353. var partSpec = detail.parts[data.name];
  6354. externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec));
  6355. }, function (data) {
  6356. internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  6357. return data.factory.sketch(combine(detail, data, partSpec, partValidated));
  6358. });
  6359. }, function (data) {
  6360. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  6361. var units = detail[data.name];
  6362. return map$2(units, function (u) {
  6363. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  6364. });
  6365. });
  6366. });
  6367. });
  6368. return {
  6369. internals: constant$1(internals),
  6370. externals: constant$1(externals)
  6371. };
  6372. };
  6373. var generate$3 = function (owner, parts) {
  6374. var r = {};
  6375. each$1(parts, function (part) {
  6376. asNamedPart(part).each(function (np) {
  6377. var g = doGenerateOne(owner, np.pname);
  6378. r[np.name] = function (config) {
  6379. var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  6380. return __assign(__assign({}, g), {
  6381. config: config,
  6382. validated: validated
  6383. });
  6384. };
  6385. });
  6386. });
  6387. return r;
  6388. };
  6389. var doGenerateOne = function (owner, pname) {
  6390. return {
  6391. uiType: placeholder(),
  6392. owner: owner,
  6393. name: pname
  6394. };
  6395. };
  6396. var generateOne$1 = function (owner, pname, config) {
  6397. return {
  6398. uiType: placeholder(),
  6399. owner: owner,
  6400. name: pname,
  6401. config: config,
  6402. validated: {}
  6403. };
  6404. };
  6405. var schemas = function (parts) {
  6406. return bind$3(parts, function (part) {
  6407. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  6408. return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  6409. }).toArray();
  6410. });
  6411. };
  6412. var names = function (parts) {
  6413. return map$2(parts, name$1);
  6414. };
  6415. var substitutes = function (owner, detail, parts) {
  6416. return subs(owner, detail, parts);
  6417. };
  6418. var components$1 = function (owner, detail, internals) {
  6419. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  6420. };
  6421. var getPart = function (component, detail, partKey) {
  6422. var uid = detail.partUids[partKey];
  6423. return component.getSystem().getByUid(uid).toOptional();
  6424. };
  6425. var getPartOrDie = function (component, detail, partKey) {
  6426. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  6427. };
  6428. var getParts = function (component, detail, partKeys) {
  6429. var r = {};
  6430. var uids = detail.partUids;
  6431. var system = component.getSystem();
  6432. each$1(partKeys, function (pk) {
  6433. r[pk] = constant$1(system.getByUid(uids[pk]));
  6434. });
  6435. return r;
  6436. };
  6437. var getAllParts = function (component, detail) {
  6438. var system = component.getSystem();
  6439. return map$1(detail.partUids, function (pUid, _k) {
  6440. return constant$1(system.getByUid(pUid));
  6441. });
  6442. };
  6443. var getAllPartNames = function (detail) {
  6444. return keys(detail.partUids);
  6445. };
  6446. var getPartsOrDie = function (component, detail, partKeys) {
  6447. var r = {};
  6448. var uids = detail.partUids;
  6449. var system = component.getSystem();
  6450. each$1(partKeys, function (pk) {
  6451. r[pk] = constant$1(system.getByUid(uids[pk]).getOrDie());
  6452. });
  6453. return r;
  6454. };
  6455. var defaultUids = function (baseUid, partTypes) {
  6456. var partNames = names(partTypes);
  6457. return wrapAll(map$2(partNames, function (pn) {
  6458. return {
  6459. key: pn,
  6460. value: baseUid + '-' + pn
  6461. };
  6462. }));
  6463. };
  6464. var defaultUidsSchema = function (partTypes) {
  6465. return field$1('partUids', 'partUids', mergeWithThunk(function (spec) {
  6466. return defaultUids(spec.uid, partTypes);
  6467. }), anyValue());
  6468. };
  6469. var AlloyParts = /*#__PURE__*/Object.freeze({
  6470. __proto__: null,
  6471. generate: generate$3,
  6472. generateOne: generateOne$1,
  6473. schemas: schemas,
  6474. names: names,
  6475. substitutes: substitutes,
  6476. components: components$1,
  6477. defaultUids: defaultUids,
  6478. defaultUidsSchema: defaultUidsSchema,
  6479. getAllParts: getAllParts,
  6480. getAllPartNames: getAllPartNames,
  6481. getPart: getPart,
  6482. getPartOrDie: getPartOrDie,
  6483. getParts: getParts,
  6484. getPartsOrDie: getPartsOrDie
  6485. });
  6486. var base = function (partSchemas, partUidsSchemas) {
  6487. var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  6488. return ps.concat([
  6489. required$1('uid'),
  6490. defaulted('dom', {}),
  6491. defaulted('components', []),
  6492. snapshot('originalSpec'),
  6493. defaulted('debug.sketcher', {})
  6494. ]).concat(partUidsSchemas);
  6495. };
  6496. var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6497. var baseS = base(partSchemas, partUidsSchemas);
  6498. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6499. };
  6500. var single$1 = function (owner, schema, factory, spec) {
  6501. var specWithUid = supplyUid(spec);
  6502. var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  6503. return factory(detail, specWithUid);
  6504. };
  6505. var composite$1 = function (owner, schema, partTypes, factory, spec) {
  6506. var specWithUid = supplyUid(spec);
  6507. var partSchemas = schemas(partTypes);
  6508. var partUidsSchema = defaultUidsSchema(partTypes);
  6509. var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6510. var subs = substitutes(owner, detail, partTypes);
  6511. var components = components$1(owner, detail, subs.internals());
  6512. return factory(detail, components, specWithUid, subs.externals());
  6513. };
  6514. var hasUid = function (spec) {
  6515. return has$2(spec, 'uid');
  6516. };
  6517. var supplyUid = function (spec) {
  6518. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5('uid') });
  6519. };
  6520. var isSketchSpec = function (spec) {
  6521. return spec.uid !== undefined;
  6522. };
  6523. var singleSchema = objOfOnly([
  6524. required$1('name'),
  6525. required$1('factory'),
  6526. required$1('configFields'),
  6527. defaulted('apis', {}),
  6528. defaulted('extraApis', {})
  6529. ]);
  6530. var compositeSchema = objOfOnly([
  6531. required$1('name'),
  6532. required$1('factory'),
  6533. required$1('configFields'),
  6534. required$1('partFields'),
  6535. defaulted('apis', {}),
  6536. defaulted('extraApis', {})
  6537. ]);
  6538. var single = function (rawConfig) {
  6539. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6540. var sketch = function (spec) {
  6541. return single$1(config.name, config.configFields, config.factory, spec);
  6542. };
  6543. var apis = map$1(config.apis, makeApi);
  6544. var extraApis = map$1(config.extraApis, function (f, k) {
  6545. return markAsExtraApi(f, k);
  6546. });
  6547. return __assign(__assign({
  6548. name: config.name,
  6549. configFields: config.configFields,
  6550. sketch: sketch
  6551. }, apis), extraApis);
  6552. };
  6553. var composite = function (rawConfig) {
  6554. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6555. var sketch = function (spec) {
  6556. return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  6557. };
  6558. var parts = generate$3(config.name, config.partFields);
  6559. var apis = map$1(config.apis, makeApi);
  6560. var extraApis = map$1(config.extraApis, function (f, k) {
  6561. return markAsExtraApi(f, k);
  6562. });
  6563. return __assign(__assign({
  6564. name: config.name,
  6565. partFields: config.partFields,
  6566. configFields: config.configFields,
  6567. sketch: sketch,
  6568. parts: parts
  6569. }, apis), extraApis);
  6570. };
  6571. var inside = function (target) {
  6572. return name$2(target) === 'input' && get$d(target, 'type') !== 'radio' || name$2(target) === 'textarea';
  6573. };
  6574. var getCurrent = function (component, composeConfig, _composeState) {
  6575. return composeConfig.find(component);
  6576. };
  6577. var ComposeApis = /*#__PURE__*/Object.freeze({
  6578. __proto__: null,
  6579. getCurrent: getCurrent
  6580. });
  6581. var ComposeSchema = [required$1('find')];
  6582. var Composing = create$7({
  6583. fields: ComposeSchema,
  6584. name: 'composing',
  6585. apis: ComposeApis
  6586. });
  6587. var nativeDisabled = [
  6588. 'input',
  6589. 'button',
  6590. 'textarea',
  6591. 'select'
  6592. ];
  6593. var onLoad$1 = function (component, disableConfig, disableState) {
  6594. var f = disableConfig.disabled() ? disable$1 : enable$1;
  6595. f(component, disableConfig);
  6596. };
  6597. var hasNative = function (component, config) {
  6598. return config.useNative === true && contains$2(nativeDisabled, name$2(component.element));
  6599. };
  6600. var nativeIsDisabled = function (component) {
  6601. return has$1(component.element, 'disabled');
  6602. };
  6603. var nativeDisable = function (component) {
  6604. set$8(component.element, 'disabled', 'disabled');
  6605. };
  6606. var nativeEnable = function (component) {
  6607. remove$7(component.element, 'disabled');
  6608. };
  6609. var ariaIsDisabled = function (component) {
  6610. return get$d(component.element, 'aria-disabled') === 'true';
  6611. };
  6612. var ariaDisable = function (component) {
  6613. set$8(component.element, 'aria-disabled', 'true');
  6614. };
  6615. var ariaEnable = function (component) {
  6616. set$8(component.element, 'aria-disabled', 'false');
  6617. };
  6618. var disable$1 = function (component, disableConfig, _disableState) {
  6619. disableConfig.disableClass.each(function (disableClass) {
  6620. add$2(component.element, disableClass);
  6621. });
  6622. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6623. f(component);
  6624. disableConfig.onDisabled(component);
  6625. };
  6626. var enable$1 = function (component, disableConfig, _disableState) {
  6627. disableConfig.disableClass.each(function (disableClass) {
  6628. remove$2(component.element, disableClass);
  6629. });
  6630. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6631. f(component);
  6632. disableConfig.onEnabled(component);
  6633. };
  6634. var isDisabled = function (component, disableConfig) {
  6635. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6636. };
  6637. var set$3 = function (component, disableConfig, disableState, disabled) {
  6638. var f = disabled ? disable$1 : enable$1;
  6639. f(component, disableConfig);
  6640. };
  6641. var DisableApis = /*#__PURE__*/Object.freeze({
  6642. __proto__: null,
  6643. enable: enable$1,
  6644. disable: disable$1,
  6645. isDisabled: isDisabled,
  6646. onLoad: onLoad$1,
  6647. set: set$3
  6648. });
  6649. var exhibit$5 = function (base, disableConfig) {
  6650. return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6651. };
  6652. var events$e = function (disableConfig, disableState) {
  6653. return derive$2([
  6654. abort(execute$5(), function (component, _simulatedEvent) {
  6655. return isDisabled(component, disableConfig);
  6656. }),
  6657. loadEvent(disableConfig, disableState, onLoad$1)
  6658. ]);
  6659. };
  6660. var ActiveDisable = /*#__PURE__*/Object.freeze({
  6661. __proto__: null,
  6662. exhibit: exhibit$5,
  6663. events: events$e
  6664. });
  6665. var DisableSchema = [
  6666. defaultedFunction('disabled', never),
  6667. defaulted('useNative', true),
  6668. option('disableClass'),
  6669. onHandler('onDisabled'),
  6670. onHandler('onEnabled')
  6671. ];
  6672. var Disabling = create$7({
  6673. fields: DisableSchema,
  6674. name: 'disabling',
  6675. active: ActiveDisable,
  6676. apis: DisableApis
  6677. });
  6678. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6679. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  6680. each$1(highlighted, function (h) {
  6681. if (!exists(skip, function (skipComp) {
  6682. return skipComp.element === h;
  6683. })) {
  6684. remove$2(h, hConfig.highlightClass);
  6685. component.getSystem().getByDom(h).each(function (target) {
  6686. hConfig.onDehighlight(component, target);
  6687. emit(target, dehighlight$1());
  6688. });
  6689. }
  6690. });
  6691. };
  6692. var dehighlightAll = function (component, hConfig, hState) {
  6693. return dehighlightAllExcept(component, hConfig, hState, []);
  6694. };
  6695. var dehighlight = function (component, hConfig, hState, target) {
  6696. if (isHighlighted(component, hConfig, hState, target)) {
  6697. remove$2(target.element, hConfig.highlightClass);
  6698. hConfig.onDehighlight(component, target);
  6699. emit(target, dehighlight$1());
  6700. }
  6701. };
  6702. var highlight = function (component, hConfig, hState, target) {
  6703. dehighlightAllExcept(component, hConfig, hState, [target]);
  6704. if (!isHighlighted(component, hConfig, hState, target)) {
  6705. add$2(target.element, hConfig.highlightClass);
  6706. hConfig.onHighlight(component, target);
  6707. emit(target, highlight$1());
  6708. }
  6709. };
  6710. var highlightFirst = function (component, hConfig, hState) {
  6711. getFirst(component, hConfig).each(function (firstComp) {
  6712. highlight(component, hConfig, hState, firstComp);
  6713. });
  6714. };
  6715. var highlightLast = function (component, hConfig, hState) {
  6716. getLast(component, hConfig).each(function (lastComp) {
  6717. highlight(component, hConfig, hState, lastComp);
  6718. });
  6719. };
  6720. var highlightAt = function (component, hConfig, hState, index) {
  6721. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6722. throw err;
  6723. }, function (firstComp) {
  6724. highlight(component, hConfig, hState, firstComp);
  6725. });
  6726. };
  6727. var highlightBy = function (component, hConfig, hState, predicate) {
  6728. var candidates = getCandidates(component, hConfig);
  6729. var targetComp = find$5(candidates, predicate);
  6730. targetComp.each(function (c) {
  6731. highlight(component, hConfig, hState, c);
  6732. });
  6733. };
  6734. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6735. return has(queryTarget.element, hConfig.highlightClass);
  6736. };
  6737. var getHighlighted = function (component, hConfig, _hState) {
  6738. return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  6739. return component.getSystem().getByDom(e).toOptional();
  6740. });
  6741. };
  6742. var getByIndex = function (component, hConfig, hState, index) {
  6743. var items = descendants(component.element, '.' + hConfig.itemClass);
  6744. return Optional.from(items[index]).fold(function () {
  6745. return Result.error(new Error('No element found with index ' + index));
  6746. }, component.getSystem().getByDom);
  6747. };
  6748. var getFirst = function (component, hConfig, _hState) {
  6749. return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  6750. return component.getSystem().getByDom(e).toOptional();
  6751. });
  6752. };
  6753. var getLast = function (component, hConfig, _hState) {
  6754. var items = descendants(component.element, '.' + hConfig.itemClass);
  6755. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  6756. return last.bind(function (c) {
  6757. return component.getSystem().getByDom(c).toOptional();
  6758. });
  6759. };
  6760. var getDelta$2 = function (component, hConfig, hState, delta) {
  6761. var items = descendants(component.element, '.' + hConfig.itemClass);
  6762. var current = findIndex$1(items, function (item) {
  6763. return has(item, hConfig.highlightClass);
  6764. });
  6765. return current.bind(function (selected) {
  6766. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6767. return component.getSystem().getByDom(items[dest]).toOptional();
  6768. });
  6769. };
  6770. var getPrevious = function (component, hConfig, hState) {
  6771. return getDelta$2(component, hConfig, hState, -1);
  6772. };
  6773. var getNext = function (component, hConfig, hState) {
  6774. return getDelta$2(component, hConfig, hState, +1);
  6775. };
  6776. var getCandidates = function (component, hConfig, _hState) {
  6777. var items = descendants(component.element, '.' + hConfig.itemClass);
  6778. return cat(map$2(items, function (i) {
  6779. return component.getSystem().getByDom(i).toOptional();
  6780. }));
  6781. };
  6782. var HighlightApis = /*#__PURE__*/Object.freeze({
  6783. __proto__: null,
  6784. dehighlightAll: dehighlightAll,
  6785. dehighlight: dehighlight,
  6786. highlight: highlight,
  6787. highlightFirst: highlightFirst,
  6788. highlightLast: highlightLast,
  6789. highlightAt: highlightAt,
  6790. highlightBy: highlightBy,
  6791. isHighlighted: isHighlighted,
  6792. getHighlighted: getHighlighted,
  6793. getFirst: getFirst,
  6794. getLast: getLast,
  6795. getPrevious: getPrevious,
  6796. getNext: getNext,
  6797. getCandidates: getCandidates
  6798. });
  6799. var HighlightSchema = [
  6800. required$1('highlightClass'),
  6801. required$1('itemClass'),
  6802. onHandler('onHighlight'),
  6803. onHandler('onDehighlight')
  6804. ];
  6805. var Highlighting = create$7({
  6806. fields: HighlightSchema,
  6807. name: 'highlighting',
  6808. apis: HighlightApis
  6809. });
  6810. var BACKSPACE = [8];
  6811. var TAB = [9];
  6812. var ENTER = [13];
  6813. var ESCAPE = [27];
  6814. var SPACE = [32];
  6815. var LEFT = [37];
  6816. var UP = [38];
  6817. var RIGHT = [39];
  6818. var DOWN = [40];
  6819. var cyclePrev = function (values, index, predicate) {
  6820. var before = reverse(values.slice(0, index));
  6821. var after = reverse(values.slice(index + 1));
  6822. return find$5(before.concat(after), predicate);
  6823. };
  6824. var tryPrev = function (values, index, predicate) {
  6825. var before = reverse(values.slice(0, index));
  6826. return find$5(before, predicate);
  6827. };
  6828. var cycleNext = function (values, index, predicate) {
  6829. var before = values.slice(0, index);
  6830. var after = values.slice(index + 1);
  6831. return find$5(after.concat(before), predicate);
  6832. };
  6833. var tryNext = function (values, index, predicate) {
  6834. var after = values.slice(index + 1);
  6835. return find$5(after, predicate);
  6836. };
  6837. var inSet = function (keys) {
  6838. return function (event) {
  6839. var raw = event.raw;
  6840. return contains$2(keys, raw.which);
  6841. };
  6842. };
  6843. var and = function (preds) {
  6844. return function (event) {
  6845. return forall(preds, function (pred) {
  6846. return pred(event);
  6847. });
  6848. };
  6849. };
  6850. var isShift = function (event) {
  6851. var raw = event.raw;
  6852. return raw.shiftKey === true;
  6853. };
  6854. var isControl = function (event) {
  6855. var raw = event.raw;
  6856. return raw.ctrlKey === true;
  6857. };
  6858. var isNotShift = not(isShift);
  6859. var rule = function (matches, action) {
  6860. return {
  6861. matches: matches,
  6862. classification: action
  6863. };
  6864. };
  6865. var choose = function (transitions, event) {
  6866. var transition = find$5(transitions, function (t) {
  6867. return t.matches(event);
  6868. });
  6869. return transition.map(function (t) {
  6870. return t.classification;
  6871. });
  6872. };
  6873. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6874. var noChange = prevFocus.exists(function (p) {
  6875. return newFocus.exists(function (n) {
  6876. return eq(n, p);
  6877. });
  6878. });
  6879. if (!noChange) {
  6880. emitWith(component, focusShifted(), {
  6881. prevFocus: prevFocus,
  6882. newFocus: newFocus
  6883. });
  6884. }
  6885. };
  6886. var dom$2 = function () {
  6887. var get = function (component) {
  6888. return search(component.element);
  6889. };
  6890. var set = function (component, focusee) {
  6891. var prevFocus = get(component);
  6892. component.getSystem().triggerFocus(focusee, component.element);
  6893. var newFocus = get(component);
  6894. reportFocusShifting(component, prevFocus, newFocus);
  6895. };
  6896. return {
  6897. get: get,
  6898. set: set
  6899. };
  6900. };
  6901. var highlights = function () {
  6902. var get = function (component) {
  6903. return Highlighting.getHighlighted(component).map(function (item) {
  6904. return item.element;
  6905. });
  6906. };
  6907. var set = function (component, element) {
  6908. var prevFocus = get(component);
  6909. component.getSystem().getByDom(element).fold(noop, function (item) {
  6910. Highlighting.highlight(component, item);
  6911. });
  6912. var newFocus = get(component);
  6913. reportFocusShifting(component, prevFocus, newFocus);
  6914. };
  6915. return {
  6916. get: get,
  6917. set: set
  6918. };
  6919. };
  6920. var FocusInsideModes;
  6921. (function (FocusInsideModes) {
  6922. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6923. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6924. FocusInsideModes['OnApiMode'] = 'onApi';
  6925. }(FocusInsideModes || (FocusInsideModes = {})));
  6926. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6927. var schema = function () {
  6928. return infoSchema.concat([
  6929. defaulted('focusManager', dom$2()),
  6930. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6931. return contains$2([
  6932. 'onFocus',
  6933. 'onEnterOrSpace',
  6934. 'onApi'
  6935. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6936. })),
  6937. output$1('handler', me),
  6938. output$1('state', stateInit),
  6939. output$1('sendFocusIn', optFocusIn)
  6940. ]);
  6941. };
  6942. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6943. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6944. return choose(rules, simulatedEvent.event).bind(function (rule) {
  6945. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6946. });
  6947. };
  6948. var toEvents = function (keyingConfig, keyingState) {
  6949. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6950. return run$1(focus$4(), function (component, simulatedEvent) {
  6951. focusIn(component, keyingConfig, keyingState);
  6952. simulatedEvent.stop();
  6953. });
  6954. });
  6955. var tryGoInsideComponent = function (component, simulatedEvent) {
  6956. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  6957. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6958. optFocusIn(keyingConfig).each(function (focusIn) {
  6959. focusIn(component, keyingConfig, keyingState);
  6960. simulatedEvent.stop();
  6961. });
  6962. }
  6963. };
  6964. var keyboardEvents = [
  6965. run$1(keydown(), function (component, simulatedEvent) {
  6966. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6967. tryGoInsideComponent(component, simulatedEvent);
  6968. }, function (_) {
  6969. simulatedEvent.stop();
  6970. });
  6971. }),
  6972. run$1(keyup(), function (component, simulatedEvent) {
  6973. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6974. simulatedEvent.stop();
  6975. });
  6976. })
  6977. ];
  6978. return derive$2(onFocusHandler.toArray().concat(keyboardEvents));
  6979. };
  6980. var me = {
  6981. schema: schema,
  6982. processKey: processKey,
  6983. toEvents: toEvents
  6984. };
  6985. return me;
  6986. };
  6987. var create$5 = function (cyclicField) {
  6988. var schema = [
  6989. option('onEscape'),
  6990. option('onEnter'),
  6991. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6992. defaulted('firstTabstop', 0),
  6993. defaulted('useTabstopAt', always),
  6994. option('visibilitySelector')
  6995. ].concat([cyclicField]);
  6996. var isVisible = function (tabbingConfig, element) {
  6997. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6998. return closest$1(element, sel);
  6999. }).getOr(element);
  7000. return get$b(target) > 0;
  7001. };
  7002. var findInitial = function (component, tabbingConfig) {
  7003. var tabstops = descendants(component.element, tabbingConfig.selector);
  7004. var visibles = filter$2(tabstops, function (elem) {
  7005. return isVisible(tabbingConfig, elem);
  7006. });
  7007. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  7008. };
  7009. var findCurrent = function (component, tabbingConfig) {
  7010. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  7011. return closest$1(elem, tabbingConfig.selector);
  7012. });
  7013. };
  7014. var isTabstop = function (tabbingConfig, element) {
  7015. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  7016. };
  7017. var focusIn = function (component, tabbingConfig, _tabbingState) {
  7018. findInitial(component, tabbingConfig).each(function (target) {
  7019. tabbingConfig.focusManager.set(component, target);
  7020. });
  7021. };
  7022. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  7023. return cycle(tabstops, stopIndex, function (elem) {
  7024. return isTabstop(tabbingConfig, elem);
  7025. }).fold(function () {
  7026. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  7027. }, function (target) {
  7028. tabbingConfig.focusManager.set(component, target);
  7029. return Optional.some(true);
  7030. });
  7031. };
  7032. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  7033. var tabstops = descendants(component.element, tabbingConfig.selector);
  7034. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  7035. var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  7036. return optStopIndex.bind(function (stopIndex) {
  7037. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  7038. });
  7039. });
  7040. };
  7041. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  7042. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  7043. return go(component, simulatedEvent, tabbingConfig, navigate);
  7044. };
  7045. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  7046. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  7047. return go(component, simulatedEvent, tabbingConfig, navigate);
  7048. };
  7049. var execute = function (component, simulatedEvent, tabbingConfig) {
  7050. return tabbingConfig.onEnter.bind(function (f) {
  7051. return f(component, simulatedEvent);
  7052. });
  7053. };
  7054. var exit = function (component, simulatedEvent, tabbingConfig) {
  7055. return tabbingConfig.onEscape.bind(function (f) {
  7056. return f(component, simulatedEvent);
  7057. });
  7058. };
  7059. var getKeydownRules = constant$1([
  7060. rule(and([
  7061. isShift,
  7062. inSet(TAB)
  7063. ]), goBackwards),
  7064. rule(inSet(TAB), goForwards),
  7065. rule(inSet(ESCAPE), exit),
  7066. rule(and([
  7067. isNotShift,
  7068. inSet(ENTER)
  7069. ]), execute)
  7070. ]);
  7071. var getKeyupRules = constant$1([]);
  7072. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  7073. return Optional.some(focusIn);
  7074. });
  7075. };
  7076. var AcyclicType = create$5(customField('cyclic', never));
  7077. var CyclicType = create$5(customField('cyclic', always));
  7078. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  7079. dispatch(component, focused, execute$5());
  7080. return Optional.some(true);
  7081. };
  7082. var defaultExecute = function (component, simulatedEvent, focused) {
  7083. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  7084. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  7085. };
  7086. var stopEventForFirefox = function (_component, _simulatedEvent) {
  7087. return Optional.some(true);
  7088. };
  7089. var schema$v = [
  7090. defaulted('execute', defaultExecute),
  7091. defaulted('useSpace', false),
  7092. defaulted('useEnter', true),
  7093. defaulted('useControlEnter', false),
  7094. defaulted('useDown', false)
  7095. ];
  7096. var execute$4 = function (component, simulatedEvent, executeConfig) {
  7097. return executeConfig.execute(component, simulatedEvent, component.element);
  7098. };
  7099. var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7100. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  7101. var enterExec = executeConfig.useEnter ? ENTER : [];
  7102. var downExec = executeConfig.useDown ? DOWN : [];
  7103. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  7104. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  7105. isControl,
  7106. inSet(ENTER)
  7107. ]), execute$4)] : []);
  7108. };
  7109. var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  7110. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7111. };
  7112. var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  7113. return Optional.none();
  7114. });
  7115. var flatgrid$1 = function () {
  7116. var dimensions = value$1();
  7117. var setGridSize = function (numRows, numColumns) {
  7118. dimensions.set({
  7119. numRows: numRows,
  7120. numColumns: numColumns
  7121. });
  7122. };
  7123. var getNumRows = function () {
  7124. return dimensions.get().map(function (d) {
  7125. return d.numRows;
  7126. });
  7127. };
  7128. var getNumColumns = function () {
  7129. return dimensions.get().map(function (d) {
  7130. return d.numColumns;
  7131. });
  7132. };
  7133. return nu$8({
  7134. readState: function () {
  7135. return dimensions.get().map(function (d) {
  7136. return {
  7137. numRows: String(d.numRows),
  7138. numColumns: String(d.numColumns)
  7139. };
  7140. }).getOr({
  7141. numRows: '?',
  7142. numColumns: '?'
  7143. });
  7144. },
  7145. setGridSize: setGridSize,
  7146. getNumRows: getNumRows,
  7147. getNumColumns: getNumColumns
  7148. });
  7149. };
  7150. var init$d = function (spec) {
  7151. return spec.state(spec);
  7152. };
  7153. var KeyingState = /*#__PURE__*/Object.freeze({
  7154. __proto__: null,
  7155. flatgrid: flatgrid$1,
  7156. init: init$d
  7157. });
  7158. var useH = function (movement) {
  7159. return function (component, simulatedEvent, config, state) {
  7160. var move = movement(component.element);
  7161. return use(move, component, simulatedEvent, config, state);
  7162. };
  7163. };
  7164. var west$1 = function (moveLeft, moveRight) {
  7165. var movement = onDirection(moveLeft, moveRight);
  7166. return useH(movement);
  7167. };
  7168. var east$1 = function (moveLeft, moveRight) {
  7169. var movement = onDirection(moveRight, moveLeft);
  7170. return useH(movement);
  7171. };
  7172. var useV = function (move) {
  7173. return function (component, simulatedEvent, config, state) {
  7174. return use(move, component, simulatedEvent, config, state);
  7175. };
  7176. };
  7177. var use = function (move, component, simulatedEvent, config, state) {
  7178. var outcome = config.focusManager.get(component).bind(function (focused) {
  7179. return move(component.element, focused, config, state);
  7180. });
  7181. return outcome.map(function (newFocus) {
  7182. config.focusManager.set(component, newFocus);
  7183. return true;
  7184. });
  7185. };
  7186. var north$1 = useV;
  7187. var south$1 = useV;
  7188. var move$1 = useV;
  7189. var isHidden$1 = function (dom) {
  7190. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  7191. };
  7192. var isVisible = function (element) {
  7193. return !isHidden$1(element.dom);
  7194. };
  7195. var locate = function (candidates, predicate) {
  7196. return findIndex$1(candidates, predicate).map(function (index) {
  7197. return {
  7198. index: index,
  7199. candidates: candidates
  7200. };
  7201. });
  7202. };
  7203. var locateVisible = function (container, current, selector) {
  7204. var predicate = function (x) {
  7205. return eq(x, current);
  7206. };
  7207. var candidates = descendants(container, selector);
  7208. var visible = filter$2(candidates, isVisible);
  7209. return locate(visible, predicate);
  7210. };
  7211. var findIndex = function (elements, target) {
  7212. return findIndex$1(elements, function (elem) {
  7213. return eq(target, elem);
  7214. });
  7215. };
  7216. var withGrid = function (values, index, numCols, f) {
  7217. var oldRow = Math.floor(index / numCols);
  7218. var oldColumn = index % numCols;
  7219. return f(oldRow, oldColumn).bind(function (address) {
  7220. var newIndex = address.row * numCols + address.column;
  7221. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  7222. });
  7223. };
  7224. var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  7225. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7226. var onLastRow = oldRow === numRows - 1;
  7227. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  7228. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  7229. return Optional.some({
  7230. row: oldRow,
  7231. column: newColumn
  7232. });
  7233. });
  7234. };
  7235. var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  7236. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  7237. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  7238. var onLastRow = newRow === numRows - 1;
  7239. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  7240. var newCol = clamp$1(oldColumn, 0, colsInRow - 1);
  7241. return Optional.some({
  7242. row: newRow,
  7243. column: newCol
  7244. });
  7245. });
  7246. };
  7247. var cycleRight$1 = function (values, index, numRows, numCols) {
  7248. return cycleHorizontal$1(values, index, numRows, numCols, +1);
  7249. };
  7250. var cycleLeft$1 = function (values, index, numRows, numCols) {
  7251. return cycleHorizontal$1(values, index, numRows, numCols, -1);
  7252. };
  7253. var cycleUp$1 = function (values, index, numRows, numCols) {
  7254. return cycleVertical$1(values, index, numRows, numCols, -1);
  7255. };
  7256. var cycleDown$1 = function (values, index, numRows, numCols) {
  7257. return cycleVertical$1(values, index, numRows, numCols, +1);
  7258. };
  7259. var schema$u = [
  7260. required$1('selector'),
  7261. defaulted('execute', defaultExecute),
  7262. onKeyboardHandler('onEscape'),
  7263. defaulted('captureTab', false),
  7264. initSize()
  7265. ];
  7266. var focusIn$3 = function (component, gridConfig, _gridState) {
  7267. descendant(component.element, gridConfig.selector).each(function (first) {
  7268. gridConfig.focusManager.set(component, first);
  7269. });
  7270. };
  7271. var findCurrent$1 = function (component, gridConfig) {
  7272. return gridConfig.focusManager.get(component).bind(function (elem) {
  7273. return closest$1(elem, gridConfig.selector);
  7274. });
  7275. };
  7276. var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  7277. return findCurrent$1(component, gridConfig).bind(function (focused) {
  7278. return gridConfig.execute(component, simulatedEvent, focused);
  7279. });
  7280. };
  7281. var doMove$2 = function (cycle) {
  7282. return function (element, focused, gridConfig, gridState) {
  7283. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  7284. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  7285. });
  7286. };
  7287. };
  7288. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  7289. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  7290. };
  7291. var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  7292. return gridConfig.onEscape(component, simulatedEvent);
  7293. };
  7294. var moveLeft$3 = doMove$2(cycleLeft$1);
  7295. var moveRight$3 = doMove$2(cycleRight$1);
  7296. var moveNorth$1 = doMove$2(cycleUp$1);
  7297. var moveSouth$1 = doMove$2(cycleDown$1);
  7298. var getKeydownRules$4 = constant$1([
  7299. rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)),
  7300. rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)),
  7301. rule(inSet(UP), north$1(moveNorth$1)),
  7302. rule(inSet(DOWN), south$1(moveSouth$1)),
  7303. rule(and([
  7304. isShift,
  7305. inSet(TAB)
  7306. ]), handleTab),
  7307. rule(and([
  7308. isNotShift,
  7309. inSet(TAB)
  7310. ]), handleTab),
  7311. rule(inSet(ESCAPE), doEscape$1),
  7312. rule(inSet(SPACE.concat(ENTER)), execute$3)
  7313. ]);
  7314. var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7315. var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  7316. return Optional.some(focusIn$3);
  7317. });
  7318. var horizontal = function (container, selector, current, delta) {
  7319. var isDisabledButton = function (candidate) {
  7320. return name$2(candidate) === 'button' && get$d(candidate, 'disabled') === 'disabled';
  7321. };
  7322. var tryCycle = function (initial, index, candidates) {
  7323. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  7324. if (newIndex === initial) {
  7325. return Optional.none();
  7326. } else {
  7327. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  7328. }
  7329. };
  7330. return locateVisible(container, current, selector).bind(function (identified) {
  7331. var index = identified.index;
  7332. var candidates = identified.candidates;
  7333. return tryCycle(index, index, candidates);
  7334. });
  7335. };
  7336. var schema$t = [
  7337. required$1('selector'),
  7338. defaulted('getInitial', Optional.none),
  7339. defaulted('execute', defaultExecute),
  7340. onKeyboardHandler('onEscape'),
  7341. defaulted('executeOnMove', false),
  7342. defaulted('allowVertical', true)
  7343. ];
  7344. var findCurrent = function (component, flowConfig) {
  7345. return flowConfig.focusManager.get(component).bind(function (elem) {
  7346. return closest$1(elem, flowConfig.selector);
  7347. });
  7348. };
  7349. var execute$2 = function (component, simulatedEvent, flowConfig) {
  7350. return findCurrent(component, flowConfig).bind(function (focused) {
  7351. return flowConfig.execute(component, simulatedEvent, focused);
  7352. });
  7353. };
  7354. var focusIn$2 = function (component, flowConfig, _state) {
  7355. flowConfig.getInitial(component).orThunk(function () {
  7356. return descendant(component.element, flowConfig.selector);
  7357. }).each(function (first) {
  7358. flowConfig.focusManager.set(component, first);
  7359. });
  7360. };
  7361. var moveLeft$2 = function (element, focused, info) {
  7362. return horizontal(element, info.selector, focused, -1);
  7363. };
  7364. var moveRight$2 = function (element, focused, info) {
  7365. return horizontal(element, info.selector, focused, +1);
  7366. };
  7367. var doMove$1 = function (movement) {
  7368. return function (component, simulatedEvent, flowConfig, flowState) {
  7369. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  7370. return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  7371. });
  7372. };
  7373. };
  7374. var doEscape = function (component, simulatedEvent, flowConfig) {
  7375. return flowConfig.onEscape(component, simulatedEvent);
  7376. };
  7377. var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  7378. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  7379. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  7380. return [
  7381. rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))),
  7382. rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))),
  7383. rule(inSet(ENTER), execute$2),
  7384. rule(inSet(SPACE), execute$2),
  7385. rule(inSet(ESCAPE), doEscape)
  7386. ];
  7387. };
  7388. var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7389. var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7390. return Optional.some(focusIn$2);
  7391. });
  7392. var toCell = function (matrix, rowIndex, columnIndex) {
  7393. return Optional.from(matrix[rowIndex]).bind(function (row) {
  7394. return Optional.from(row[columnIndex]).map(function (cell) {
  7395. return {
  7396. rowIndex: rowIndex,
  7397. columnIndex: columnIndex,
  7398. cell: cell
  7399. };
  7400. });
  7401. });
  7402. };
  7403. var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7404. var row = matrix[rowIndex];
  7405. var colsInRow = row.length;
  7406. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  7407. return toCell(matrix, rowIndex, newColIndex);
  7408. };
  7409. var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  7410. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  7411. var colsInNextRow = matrix[nextRowIndex].length;
  7412. var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7413. return toCell(matrix, nextRowIndex, nextColIndex);
  7414. };
  7415. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  7416. var row = matrix[rowIndex];
  7417. var colsInRow = row.length;
  7418. var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1);
  7419. return toCell(matrix, rowIndex, newColIndex);
  7420. };
  7421. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  7422. var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix.length - 1);
  7423. var colsInNextRow = matrix[nextRowIndex].length;
  7424. var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1);
  7425. return toCell(matrix, nextRowIndex, nextColIndex);
  7426. };
  7427. var cycleRight = function (matrix, startRow, startCol) {
  7428. return cycleHorizontal(matrix, startRow, startCol, +1);
  7429. };
  7430. var cycleLeft = function (matrix, startRow, startCol) {
  7431. return cycleHorizontal(matrix, startRow, startCol, -1);
  7432. };
  7433. var cycleUp = function (matrix, startRow, startCol) {
  7434. return cycleVertical(matrix, startCol, startRow, -1);
  7435. };
  7436. var cycleDown = function (matrix, startRow, startCol) {
  7437. return cycleVertical(matrix, startCol, startRow, +1);
  7438. };
  7439. var moveLeft$1 = function (matrix, startRow, startCol) {
  7440. return moveHorizontal(matrix, startRow, startCol, -1);
  7441. };
  7442. var moveRight$1 = function (matrix, startRow, startCol) {
  7443. return moveHorizontal(matrix, startRow, startCol, +1);
  7444. };
  7445. var moveUp$1 = function (matrix, startRow, startCol) {
  7446. return moveVertical(matrix, startCol, startRow, -1);
  7447. };
  7448. var moveDown$1 = function (matrix, startRow, startCol) {
  7449. return moveVertical(matrix, startCol, startRow, +1);
  7450. };
  7451. var schema$s = [
  7452. requiredObjOf('selectors', [
  7453. required$1('row'),
  7454. required$1('cell')
  7455. ]),
  7456. defaulted('cycles', true),
  7457. defaulted('previousSelector', Optional.none),
  7458. defaulted('execute', defaultExecute)
  7459. ];
  7460. var focusIn$1 = function (component, matrixConfig, _state) {
  7461. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  7462. var selectors = matrixConfig.selectors;
  7463. return descendant(component.element, selectors.cell);
  7464. });
  7465. focused.each(function (cell) {
  7466. matrixConfig.focusManager.set(component, cell);
  7467. });
  7468. };
  7469. var execute$1 = function (component, simulatedEvent, matrixConfig) {
  7470. return search(component.element).bind(function (focused) {
  7471. return matrixConfig.execute(component, simulatedEvent, focused);
  7472. });
  7473. };
  7474. var toMatrix = function (rows, matrixConfig) {
  7475. return map$2(rows, function (row) {
  7476. return descendants(row, matrixConfig.selectors.cell);
  7477. });
  7478. };
  7479. var doMove = function (ifCycle, ifMove) {
  7480. return function (element, focused, matrixConfig) {
  7481. var move = matrixConfig.cycles ? ifCycle : ifMove;
  7482. return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  7483. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  7484. return findIndex(cellsInRow, focused).bind(function (colIndex) {
  7485. var allRows = descendants(element, matrixConfig.selectors.row);
  7486. return findIndex(allRows, inRow).bind(function (rowIndex) {
  7487. var matrix = toMatrix(allRows, matrixConfig);
  7488. return move(matrix, rowIndex, colIndex).map(function (next) {
  7489. return next.cell;
  7490. });
  7491. });
  7492. });
  7493. });
  7494. };
  7495. };
  7496. var moveLeft = doMove(cycleLeft, moveLeft$1);
  7497. var moveRight = doMove(cycleRight, moveRight$1);
  7498. var moveNorth = doMove(cycleUp, moveUp$1);
  7499. var moveSouth = doMove(cycleDown, moveDown$1);
  7500. var getKeydownRules$2 = constant$1([
  7501. rule(inSet(LEFT), west$1(moveLeft, moveRight)),
  7502. rule(inSet(RIGHT), east$1(moveLeft, moveRight)),
  7503. rule(inSet(UP), north$1(moveNorth)),
  7504. rule(inSet(DOWN), south$1(moveSouth)),
  7505. rule(inSet(SPACE.concat(ENTER)), execute$1)
  7506. ]);
  7507. var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7508. var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  7509. return Optional.some(focusIn$1);
  7510. });
  7511. var schema$r = [
  7512. required$1('selector'),
  7513. defaulted('execute', defaultExecute),
  7514. defaulted('moveOnTab', false)
  7515. ];
  7516. var execute = function (component, simulatedEvent, menuConfig) {
  7517. return menuConfig.focusManager.get(component).bind(function (focused) {
  7518. return menuConfig.execute(component, simulatedEvent, focused);
  7519. });
  7520. };
  7521. var focusIn = function (component, menuConfig, _state) {
  7522. descendant(component.element, menuConfig.selector).each(function (first) {
  7523. menuConfig.focusManager.set(component, first);
  7524. });
  7525. };
  7526. var moveUp = function (element, focused, info) {
  7527. return horizontal(element, info.selector, focused, -1);
  7528. };
  7529. var moveDown = function (element, focused, info) {
  7530. return horizontal(element, info.selector, focused, +1);
  7531. };
  7532. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7533. return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7534. };
  7535. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7536. return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  7537. };
  7538. var getKeydownRules$1 = constant$1([
  7539. rule(inSet(UP), move$1(moveUp)),
  7540. rule(inSet(DOWN), move$1(moveDown)),
  7541. rule(and([
  7542. isShift,
  7543. inSet(TAB)
  7544. ]), fireShiftTab),
  7545. rule(and([
  7546. isNotShift,
  7547. inSet(TAB)
  7548. ]), fireTab),
  7549. rule(inSet(ENTER), execute),
  7550. rule(inSet(SPACE), execute)
  7551. ]);
  7552. var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  7553. var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  7554. return Optional.some(focusIn);
  7555. });
  7556. var schema$q = [
  7557. onKeyboardHandler('onSpace'),
  7558. onKeyboardHandler('onEnter'),
  7559. onKeyboardHandler('onShiftEnter'),
  7560. onKeyboardHandler('onLeft'),
  7561. onKeyboardHandler('onRight'),
  7562. onKeyboardHandler('onTab'),
  7563. onKeyboardHandler('onShiftTab'),
  7564. onKeyboardHandler('onUp'),
  7565. onKeyboardHandler('onDown'),
  7566. onKeyboardHandler('onEscape'),
  7567. defaulted('stopSpaceKeyup', false),
  7568. option('focusIn')
  7569. ];
  7570. var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  7571. return [
  7572. rule(inSet(SPACE), specialInfo.onSpace),
  7573. rule(and([
  7574. isNotShift,
  7575. inSet(ENTER)
  7576. ]), specialInfo.onEnter),
  7577. rule(and([
  7578. isShift,
  7579. inSet(ENTER)
  7580. ]), specialInfo.onShiftEnter),
  7581. rule(and([
  7582. isShift,
  7583. inSet(TAB)
  7584. ]), specialInfo.onShiftTab),
  7585. rule(and([
  7586. isNotShift,
  7587. inSet(TAB)
  7588. ]), specialInfo.onTab),
  7589. rule(inSet(UP), specialInfo.onUp),
  7590. rule(inSet(DOWN), specialInfo.onDown),
  7591. rule(inSet(LEFT), specialInfo.onLeft),
  7592. rule(inSet(RIGHT), specialInfo.onRight),
  7593. rule(inSet(SPACE), specialInfo.onSpace),
  7594. rule(inSet(ESCAPE), specialInfo.onEscape)
  7595. ];
  7596. };
  7597. var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  7598. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  7599. };
  7600. var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  7601. return specialInfo.focusIn;
  7602. });
  7603. var acyclic = AcyclicType.schema();
  7604. var cyclic = CyclicType.schema();
  7605. var flow = FlowType.schema();
  7606. var flatgrid = FlatgridType.schema();
  7607. var matrix = MatrixType.schema();
  7608. var execution = ExecutionType.schema();
  7609. var menu = MenuType.schema();
  7610. var special = SpecialType.schema();
  7611. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7612. __proto__: null,
  7613. acyclic: acyclic,
  7614. cyclic: cyclic,
  7615. flow: flow,
  7616. flatgrid: flatgrid,
  7617. matrix: matrix,
  7618. execution: execution,
  7619. menu: menu,
  7620. special: special
  7621. });
  7622. var isFlatgridState = function (keyState) {
  7623. return hasNonNullableKey(keyState, 'setGridSize');
  7624. };
  7625. var Keying = createModes({
  7626. branchKey: 'mode',
  7627. branches: KeyboardBranches,
  7628. name: 'keying',
  7629. active: {
  7630. events: function (keyingConfig, keyingState) {
  7631. var handler = keyingConfig.handler;
  7632. return handler.toEvents(keyingConfig, keyingState);
  7633. }
  7634. },
  7635. apis: {
  7636. focusIn: function (component, keyConfig, keyState) {
  7637. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7638. component.getSystem().triggerFocus(component.element, component.element);
  7639. }, function (sendFocusIn) {
  7640. sendFocusIn(component, keyConfig, keyState);
  7641. });
  7642. },
  7643. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7644. if (!isFlatgridState(keyState)) {
  7645. console.error('Layout does not support setGridSize');
  7646. } else {
  7647. keyState.setGridSize(numRows, numColumns);
  7648. }
  7649. }
  7650. },
  7651. state: KeyingState
  7652. });
  7653. var set$2 = function (component, replaceConfig, replaceState, data) {
  7654. preserve$1(function () {
  7655. var newChildren = map$2(data, component.getSystem().build);
  7656. replaceChildren(component, newChildren);
  7657. }, component.element);
  7658. };
  7659. var insert = function (component, replaceConfig, insertion, childSpec) {
  7660. var child = component.getSystem().build(childSpec);
  7661. attachWith(component, child, insertion);
  7662. };
  7663. var append = function (component, replaceConfig, replaceState, appendee) {
  7664. insert(component, replaceConfig, append$2, appendee);
  7665. };
  7666. var prepend = function (component, replaceConfig, replaceState, prependee) {
  7667. insert(component, replaceConfig, prepend$1, prependee);
  7668. };
  7669. var remove = function (component, replaceConfig, replaceState, removee) {
  7670. var children = contents(component);
  7671. var foundChild = find$5(children, function (child) {
  7672. return eq(removee.element, child.element);
  7673. });
  7674. foundChild.each(detach);
  7675. };
  7676. var contents = function (component, _replaceConfig) {
  7677. return component.components();
  7678. };
  7679. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7680. var children = contents(component);
  7681. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  7682. remove(component, replaceConfig, replaceState, replacee);
  7683. replacer.each(function (r) {
  7684. insert(component, replaceConfig, function (p, c) {
  7685. appendAt(p, c, replaceeIndex);
  7686. }, r);
  7687. });
  7688. return replacee;
  7689. });
  7690. };
  7691. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7692. var children = contents(component);
  7693. return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  7694. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7695. });
  7696. };
  7697. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7698. __proto__: null,
  7699. append: append,
  7700. prepend: prepend,
  7701. remove: remove,
  7702. replaceAt: replaceAt,
  7703. replaceBy: replaceBy,
  7704. set: set$2,
  7705. contents: contents
  7706. });
  7707. var Replacing = create$7({
  7708. fields: [],
  7709. name: 'replacing',
  7710. apis: ReplaceApis
  7711. });
  7712. var events$d = function (name, eventHandlers) {
  7713. var events = derive$2(eventHandlers);
  7714. return create$7({
  7715. fields: [required$1('enabled')],
  7716. name: name,
  7717. active: { events: constant$1(events) }
  7718. });
  7719. };
  7720. var config = function (name, eventHandlers) {
  7721. var me = events$d(name, eventHandlers);
  7722. return {
  7723. key: name,
  7724. value: {
  7725. config: {},
  7726. me: me,
  7727. configAsRaw: constant$1({}),
  7728. initialConfig: {},
  7729. state: NoState
  7730. }
  7731. };
  7732. };
  7733. var focus$2 = function (component, focusConfig) {
  7734. if (!focusConfig.ignore) {
  7735. focus$3(component.element);
  7736. focusConfig.onFocus(component);
  7737. }
  7738. };
  7739. var blur = function (component, focusConfig) {
  7740. if (!focusConfig.ignore) {
  7741. blur$1(component.element);
  7742. }
  7743. };
  7744. var isFocused = function (component) {
  7745. return hasFocus(component.element);
  7746. };
  7747. var FocusApis = /*#__PURE__*/Object.freeze({
  7748. __proto__: null,
  7749. focus: focus$2,
  7750. blur: blur,
  7751. isFocused: isFocused
  7752. });
  7753. var exhibit$4 = function (base, focusConfig) {
  7754. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7755. return nu$7(mod);
  7756. };
  7757. var events$c = function (focusConfig) {
  7758. return derive$2([run$1(focus$4(), function (component, simulatedEvent) {
  7759. focus$2(component, focusConfig);
  7760. simulatedEvent.stop();
  7761. })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function (_, simulatedEvent) {
  7762. simulatedEvent.event.prevent();
  7763. })] : []));
  7764. };
  7765. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7766. __proto__: null,
  7767. exhibit: exhibit$4,
  7768. events: events$c
  7769. });
  7770. var FocusSchema = [
  7771. onHandler('onFocus'),
  7772. defaulted('stopMousedown', false),
  7773. defaulted('ignore', false)
  7774. ];
  7775. var Focusing = create$7({
  7776. fields: FocusSchema,
  7777. name: 'focusing',
  7778. active: ActiveFocus,
  7779. apis: FocusApis
  7780. });
  7781. var SetupBehaviourCellState = function (initialState) {
  7782. var init = function () {
  7783. var cell = Cell(initialState);
  7784. var get = function () {
  7785. return cell.get();
  7786. };
  7787. var set = function (newState) {
  7788. return cell.set(newState);
  7789. };
  7790. var clear = function () {
  7791. return cell.set(initialState);
  7792. };
  7793. var readState = function () {
  7794. return cell.get();
  7795. };
  7796. return {
  7797. get: get,
  7798. set: set,
  7799. clear: clear,
  7800. readState: readState
  7801. };
  7802. };
  7803. return { init: init };
  7804. };
  7805. var updateAriaState = function (component, toggleConfig, toggleState) {
  7806. var ariaInfo = toggleConfig.aria;
  7807. ariaInfo.update(component, ariaInfo, toggleState.get());
  7808. };
  7809. var updateClass = function (component, toggleConfig, toggleState) {
  7810. toggleConfig.toggleClass.each(function (toggleClass) {
  7811. if (toggleState.get()) {
  7812. add$2(component.element, toggleClass);
  7813. } else {
  7814. remove$2(component.element, toggleClass);
  7815. }
  7816. });
  7817. };
  7818. var toggle$2 = function (component, toggleConfig, toggleState) {
  7819. set$1(component, toggleConfig, toggleState, !toggleState.get());
  7820. };
  7821. var on = function (component, toggleConfig, toggleState) {
  7822. toggleState.set(true);
  7823. updateClass(component, toggleConfig, toggleState);
  7824. updateAriaState(component, toggleConfig, toggleState);
  7825. };
  7826. var off = function (component, toggleConfig, toggleState) {
  7827. toggleState.set(false);
  7828. updateClass(component, toggleConfig, toggleState);
  7829. updateAriaState(component, toggleConfig, toggleState);
  7830. };
  7831. var set$1 = function (component, toggleConfig, toggleState, state) {
  7832. var action = state ? on : off;
  7833. action(component, toggleConfig, toggleState);
  7834. };
  7835. var isOn = function (component, toggleConfig, toggleState) {
  7836. return toggleState.get();
  7837. };
  7838. var onLoad = function (component, toggleConfig, toggleState) {
  7839. set$1(component, toggleConfig, toggleState, toggleConfig.selected);
  7840. };
  7841. var ToggleApis = /*#__PURE__*/Object.freeze({
  7842. __proto__: null,
  7843. onLoad: onLoad,
  7844. toggle: toggle$2,
  7845. isOn: isOn,
  7846. on: on,
  7847. off: off,
  7848. set: set$1
  7849. });
  7850. var exhibit$3 = function () {
  7851. return nu$7({});
  7852. };
  7853. var events$b = function (toggleConfig, toggleState) {
  7854. var execute = executeEvent(toggleConfig, toggleState, toggle$2);
  7855. var load = loadEvent(toggleConfig, toggleState, onLoad);
  7856. return derive$2(flatten([
  7857. toggleConfig.toggleOnExecute ? [execute] : [],
  7858. [load]
  7859. ]));
  7860. };
  7861. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7862. __proto__: null,
  7863. exhibit: exhibit$3,
  7864. events: events$b
  7865. });
  7866. var updatePressed = function (component, ariaInfo, status) {
  7867. set$8(component.element, 'aria-pressed', status);
  7868. if (ariaInfo.syncWithExpanded) {
  7869. updateExpanded(component, ariaInfo, status);
  7870. }
  7871. };
  7872. var updateSelected = function (component, ariaInfo, status) {
  7873. set$8(component.element, 'aria-selected', status);
  7874. };
  7875. var updateChecked = function (component, ariaInfo, status) {
  7876. set$8(component.element, 'aria-checked', status);
  7877. };
  7878. var updateExpanded = function (component, ariaInfo, status) {
  7879. set$8(component.element, 'aria-expanded', status);
  7880. };
  7881. var ToggleSchema = [
  7882. defaulted('selected', false),
  7883. option('toggleClass'),
  7884. defaulted('toggleOnExecute', true),
  7885. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7886. pressed: [
  7887. defaulted('syncWithExpanded', false),
  7888. output$1('update', updatePressed)
  7889. ],
  7890. checked: [output$1('update', updateChecked)],
  7891. expanded: [output$1('update', updateExpanded)],
  7892. selected: [output$1('update', updateSelected)],
  7893. none: [output$1('update', noop)]
  7894. }))
  7895. ];
  7896. var Toggling = create$7({
  7897. fields: ToggleSchema,
  7898. name: 'toggling',
  7899. active: ActiveToggle,
  7900. apis: ToggleApis,
  7901. state: SetupBehaviourCellState(false)
  7902. });
  7903. var pointerEvents = function () {
  7904. var onClick = function (component, simulatedEvent) {
  7905. simulatedEvent.stop();
  7906. emitExecute(component);
  7907. };
  7908. return [
  7909. run$1(click(), onClick),
  7910. run$1(tap(), onClick),
  7911. cutter(touchstart()),
  7912. cutter(mousedown())
  7913. ];
  7914. };
  7915. var events$a = function (optAction) {
  7916. var executeHandler = function (action) {
  7917. return runOnExecute$1(function (component, simulatedEvent) {
  7918. action(component);
  7919. simulatedEvent.stop();
  7920. });
  7921. };
  7922. return derive$2(flatten([
  7923. optAction.map(executeHandler).toArray(),
  7924. pointerEvents()
  7925. ]));
  7926. };
  7927. var hoverEvent = 'alloy.item-hover';
  7928. var focusEvent = 'alloy.item-focus';
  7929. var onHover = function (item) {
  7930. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7931. if (!Focusing.isFocused(item)) {
  7932. Focusing.focus(item);
  7933. }
  7934. emitWith(item, hoverEvent, { item: item });
  7935. }
  7936. };
  7937. var onFocus$1 = function (item) {
  7938. emitWith(item, focusEvent, { item: item });
  7939. };
  7940. var hover = constant$1(hoverEvent);
  7941. var focus$1 = constant$1(focusEvent);
  7942. var builder$2 = function (detail) {
  7943. return {
  7944. dom: detail.dom,
  7945. 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 } : {}) }),
  7946. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7947. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7948. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7949. }),
  7950. Focusing.config({
  7951. ignore: detail.ignoreFocus,
  7952. stopMousedown: detail.ignoreFocus,
  7953. onFocus: function (component) {
  7954. onFocus$1(component);
  7955. }
  7956. }),
  7957. Keying.config({ mode: 'execution' }),
  7958. Representing.config({
  7959. store: {
  7960. mode: 'memory',
  7961. initialValue: detail.data
  7962. }
  7963. }),
  7964. config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [
  7965. run$1(mouseover(), onHover),
  7966. run$1(focusItem(), Focusing.focus)
  7967. ], false))
  7968. ]),
  7969. components: detail.components,
  7970. eventOrder: detail.eventOrder
  7971. };
  7972. };
  7973. var schema$p = [
  7974. required$1('data'),
  7975. required$1('components'),
  7976. required$1('dom'),
  7977. defaulted('hasSubmenu', false),
  7978. option('toggling'),
  7979. SketchBehaviours.field('itemBehaviours', [
  7980. Toggling,
  7981. Focusing,
  7982. Keying,
  7983. Representing
  7984. ]),
  7985. defaulted('ignoreFocus', false),
  7986. defaulted('domModification', {}),
  7987. output$1('builder', builder$2),
  7988. defaulted('eventOrder', {})
  7989. ];
  7990. var builder$1 = function (detail) {
  7991. return {
  7992. dom: detail.dom,
  7993. components: detail.components,
  7994. events: derive$2([stopper(focusItem())])
  7995. };
  7996. };
  7997. var schema$o = [
  7998. required$1('dom'),
  7999. required$1('components'),
  8000. output$1('builder', builder$1)
  8001. ];
  8002. var owner$2 = constant$1('item-widget');
  8003. var parts$h = constant$1([required({
  8004. name: 'widget',
  8005. overrides: function (detail) {
  8006. return {
  8007. behaviours: derive$1([Representing.config({
  8008. store: {
  8009. mode: 'manual',
  8010. getValue: function (_component) {
  8011. return detail.data;
  8012. },
  8013. setValue: noop
  8014. }
  8015. })])
  8016. };
  8017. }
  8018. })]);
  8019. var builder = function (detail) {
  8020. var subs = substitutes(owner$2(), detail, parts$h());
  8021. var components = components$1(owner$2(), detail, subs.internals());
  8022. var focusWidget = function (component) {
  8023. return getPart(component, detail, 'widget').map(function (widget) {
  8024. Keying.focusIn(widget);
  8025. return widget;
  8026. });
  8027. };
  8028. var onHorizontalArrow = function (component, simulatedEvent) {
  8029. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  8030. if (detail.autofocus) {
  8031. simulatedEvent.setSource(component.element);
  8032. return Optional.none();
  8033. } else {
  8034. return Optional.none();
  8035. }
  8036. }();
  8037. };
  8038. return {
  8039. dom: detail.dom,
  8040. components: components,
  8041. domModification: detail.domModification,
  8042. events: derive$2([
  8043. runOnExecute$1(function (component, simulatedEvent) {
  8044. focusWidget(component).each(function (_widget) {
  8045. simulatedEvent.stop();
  8046. });
  8047. }),
  8048. run$1(mouseover(), onHover),
  8049. run$1(focusItem(), function (component, _simulatedEvent) {
  8050. if (detail.autofocus) {
  8051. focusWidget(component);
  8052. } else {
  8053. Focusing.focus(component);
  8054. }
  8055. })
  8056. ]),
  8057. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  8058. Representing.config({
  8059. store: {
  8060. mode: 'memory',
  8061. initialValue: detail.data
  8062. }
  8063. }),
  8064. Focusing.config({
  8065. ignore: detail.ignoreFocus,
  8066. onFocus: function (component) {
  8067. onFocus$1(component);
  8068. }
  8069. }),
  8070. Keying.config({
  8071. mode: 'special',
  8072. focusIn: detail.autofocus ? function (component) {
  8073. focusWidget(component);
  8074. } : revoke(),
  8075. onLeft: onHorizontalArrow,
  8076. onRight: onHorizontalArrow,
  8077. onEscape: function (component, simulatedEvent) {
  8078. if (!Focusing.isFocused(component) && !detail.autofocus) {
  8079. Focusing.focus(component);
  8080. return Optional.some(true);
  8081. } else if (detail.autofocus) {
  8082. simulatedEvent.setSource(component.element);
  8083. return Optional.none();
  8084. } else {
  8085. return Optional.none();
  8086. }
  8087. }
  8088. })
  8089. ])
  8090. };
  8091. };
  8092. var schema$n = [
  8093. required$1('uid'),
  8094. required$1('data'),
  8095. required$1('components'),
  8096. required$1('dom'),
  8097. defaulted('autofocus', false),
  8098. defaulted('ignoreFocus', false),
  8099. SketchBehaviours.field('widgetBehaviours', [
  8100. Representing,
  8101. Focusing,
  8102. Keying
  8103. ]),
  8104. defaulted('domModification', {}),
  8105. defaultUidsSchema(parts$h()),
  8106. output$1('builder', builder)
  8107. ];
  8108. var itemSchema$2 = choose$1('type', {
  8109. widget: schema$n,
  8110. item: schema$p,
  8111. separator: schema$o
  8112. });
  8113. var configureGrid = function (detail, movementInfo) {
  8114. return {
  8115. mode: 'flatgrid',
  8116. selector: '.' + detail.markers.item,
  8117. initSize: {
  8118. numColumns: movementInfo.initSize.numColumns,
  8119. numRows: movementInfo.initSize.numRows
  8120. },
  8121. focusManager: detail.focusManager
  8122. };
  8123. };
  8124. var configureMatrix = function (detail, movementInfo) {
  8125. return {
  8126. mode: 'matrix',
  8127. selectors: {
  8128. row: movementInfo.rowSelector,
  8129. cell: '.' + detail.markers.item
  8130. },
  8131. focusManager: detail.focusManager
  8132. };
  8133. };
  8134. var configureMenu = function (detail, movementInfo) {
  8135. return {
  8136. mode: 'menu',
  8137. selector: '.' + detail.markers.item,
  8138. moveOnTab: movementInfo.moveOnTab,
  8139. focusManager: detail.focusManager
  8140. };
  8141. };
  8142. var parts$g = constant$1([group({
  8143. factory: {
  8144. sketch: function (spec) {
  8145. var itemInfo = asRawOrDie$1('menu.spec item', itemSchema$2, spec);
  8146. return itemInfo.builder(itemInfo);
  8147. }
  8148. },
  8149. name: 'items',
  8150. unit: 'item',
  8151. defaults: function (detail, u) {
  8152. return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$5('item') });
  8153. },
  8154. overrides: function (detail, u) {
  8155. return {
  8156. type: u.type,
  8157. ignoreFocus: detail.fakeFocus,
  8158. domModification: { classes: [detail.markers.item] }
  8159. };
  8160. }
  8161. })]);
  8162. var schema$m = constant$1([
  8163. required$1('value'),
  8164. required$1('items'),
  8165. required$1('dom'),
  8166. required$1('components'),
  8167. defaulted('eventOrder', {}),
  8168. field('menuBehaviours', [
  8169. Highlighting,
  8170. Representing,
  8171. Composing,
  8172. Keying
  8173. ]),
  8174. defaultedOf('movement', {
  8175. mode: 'menu',
  8176. moveOnTab: true
  8177. }, choose$1('mode', {
  8178. grid: [
  8179. initSize(),
  8180. output$1('config', configureGrid)
  8181. ],
  8182. matrix: [
  8183. output$1('config', configureMatrix),
  8184. required$1('rowSelector')
  8185. ],
  8186. menu: [
  8187. defaulted('moveOnTab', true),
  8188. output$1('config', configureMenu)
  8189. ]
  8190. })),
  8191. itemMarkers(),
  8192. defaulted('fakeFocus', false),
  8193. defaulted('focusManager', dom$2()),
  8194. onHandler('onHighlight')
  8195. ]);
  8196. var focus = constant$1('alloy.menu-focus');
  8197. var make$7 = function (detail, components, _spec, _externals) {
  8198. return {
  8199. uid: detail.uid,
  8200. dom: detail.dom,
  8201. markers: detail.markers,
  8202. behaviours: augment(detail.menuBehaviours, [
  8203. Highlighting.config({
  8204. highlightClass: detail.markers.selectedItem,
  8205. itemClass: detail.markers.item,
  8206. onHighlight: detail.onHighlight
  8207. }),
  8208. Representing.config({
  8209. store: {
  8210. mode: 'memory',
  8211. initialValue: detail.value
  8212. }
  8213. }),
  8214. Composing.config({ find: Optional.some }),
  8215. Keying.config(detail.movement.config(detail, detail.movement))
  8216. ]),
  8217. events: derive$2([
  8218. run$1(focus$1(), function (menu, simulatedEvent) {
  8219. var event = simulatedEvent.event;
  8220. menu.getSystem().getByDom(event.target).each(function (item) {
  8221. Highlighting.highlight(menu, item);
  8222. simulatedEvent.stop();
  8223. emitWith(menu, focus(), {
  8224. menu: menu,
  8225. item: item
  8226. });
  8227. });
  8228. }),
  8229. run$1(hover(), function (menu, simulatedEvent) {
  8230. var item = simulatedEvent.event.item;
  8231. Highlighting.highlight(menu, item);
  8232. })
  8233. ]),
  8234. components: components,
  8235. eventOrder: detail.eventOrder,
  8236. domModification: { attributes: { role: 'menu' } }
  8237. };
  8238. };
  8239. var Menu = composite({
  8240. name: 'Menu',
  8241. configFields: schema$m(),
  8242. partFields: parts$g(),
  8243. factory: make$7
  8244. });
  8245. var transpose$1 = function (obj) {
  8246. return tupleMap(obj, function (v, k) {
  8247. return {
  8248. k: v,
  8249. v: k
  8250. };
  8251. });
  8252. };
  8253. var trace = function (items, byItem, byMenu, finish) {
  8254. return get$e(byMenu, finish).bind(function (triggerItem) {
  8255. return get$e(items, triggerItem).bind(function (triggerMenu) {
  8256. var rest = trace(items, byItem, byMenu, triggerMenu);
  8257. return Optional.some([triggerMenu].concat(rest));
  8258. });
  8259. }).getOr([]);
  8260. };
  8261. var generate$2 = function (menus, expansions) {
  8262. var items = {};
  8263. each(menus, function (menuItems, menu) {
  8264. each$1(menuItems, function (item) {
  8265. items[item] = menu;
  8266. });
  8267. });
  8268. var byItem = expansions;
  8269. var byMenu = transpose$1(expansions);
  8270. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8271. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8272. });
  8273. return map$1(items, function (menu) {
  8274. return get$e(menuPaths, menu).getOr([menu]);
  8275. });
  8276. };
  8277. var init$c = function () {
  8278. var expansions = Cell({});
  8279. var menus = Cell({});
  8280. var paths = Cell({});
  8281. var primary = value$1();
  8282. var directory = Cell({});
  8283. var clear = function () {
  8284. expansions.set({});
  8285. menus.set({});
  8286. paths.set({});
  8287. primary.clear();
  8288. };
  8289. var isClear = function () {
  8290. return primary.get().isNone();
  8291. };
  8292. var setMenuBuilt = function (menuName, built) {
  8293. var _a;
  8294. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8295. type: 'prepared',
  8296. menu: built
  8297. }, _a)));
  8298. };
  8299. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8300. primary.set(sPrimary);
  8301. expansions.set(sExpansions);
  8302. menus.set(sMenus);
  8303. directory.set(dir);
  8304. var sPaths = generate$2(dir, sExpansions);
  8305. paths.set(sPaths);
  8306. };
  8307. var getTriggeringItem = function (menuValue) {
  8308. return find$4(expansions.get(), function (v, _k) {
  8309. return v === menuValue;
  8310. });
  8311. };
  8312. var getTriggerData = function (menuValue, getItemByValue, path) {
  8313. return getPreparedMenu(menuValue).bind(function (menu) {
  8314. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8315. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8316. return {
  8317. triggeredMenu: menu,
  8318. triggeringItem: triggeredItem,
  8319. triggeringPath: path
  8320. };
  8321. });
  8322. });
  8323. });
  8324. };
  8325. var getTriggeringPath = function (itemValue, getItemByValue) {
  8326. var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8327. return getPreparedMenu(menuValue).isSome();
  8328. });
  8329. return get$e(paths.get(), itemValue).bind(function (path) {
  8330. var revPath = reverse(extraPath.concat(path));
  8331. var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8332. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8333. return is$1(primary.get(), menuValue) ? [] : [Optional.none()];
  8334. }, function (data) {
  8335. return [Optional.some(data)];
  8336. });
  8337. });
  8338. return sequence(triggers);
  8339. });
  8340. };
  8341. var expand = function (itemValue) {
  8342. return get$e(expansions.get(), itemValue).map(function (menu) {
  8343. var current = get$e(paths.get(), itemValue).getOr([]);
  8344. return [menu].concat(current);
  8345. });
  8346. };
  8347. var collapse = function (itemValue) {
  8348. return get$e(paths.get(), itemValue).bind(function (path) {
  8349. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8350. });
  8351. };
  8352. var refresh = function (itemValue) {
  8353. return get$e(paths.get(), itemValue);
  8354. };
  8355. var getPreparedMenu = function (menuValue) {
  8356. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8357. };
  8358. var lookupMenu = function (menuValue) {
  8359. return get$e(menus.get(), menuValue);
  8360. };
  8361. var lookupItem = function (itemValue) {
  8362. return get$e(expansions.get(), itemValue);
  8363. };
  8364. var otherMenus = function (path) {
  8365. var menuValues = directory.get();
  8366. return difference(keys(menuValues), path);
  8367. };
  8368. var getPrimary = function () {
  8369. return primary.get().bind(getPreparedMenu);
  8370. };
  8371. var getMenus = function () {
  8372. return menus.get();
  8373. };
  8374. return {
  8375. setMenuBuilt: setMenuBuilt,
  8376. setContents: setContents,
  8377. expand: expand,
  8378. refresh: refresh,
  8379. collapse: collapse,
  8380. lookupMenu: lookupMenu,
  8381. lookupItem: lookupItem,
  8382. otherMenus: otherMenus,
  8383. getPrimary: getPrimary,
  8384. getMenus: getMenus,
  8385. clear: clear,
  8386. isClear: isClear,
  8387. getTriggeringPath: getTriggeringPath
  8388. };
  8389. };
  8390. var extractPreparedMenu = function (prep) {
  8391. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8392. };
  8393. var LayeredState = {
  8394. init: init$c,
  8395. extractPreparedMenu: extractPreparedMenu
  8396. };
  8397. var make$6 = function (detail, _rawUiSpec) {
  8398. var submenuParentItems = value$1();
  8399. var buildMenus = function (container, primaryName, menus) {
  8400. return map$1(menus, function (spec, name) {
  8401. var makeSketch = function () {
  8402. return Menu.sketch(__assign(__assign({}, spec), {
  8403. value: name,
  8404. markers: detail.markers,
  8405. fakeFocus: detail.fakeFocus,
  8406. onHighlight: detail.onHighlight,
  8407. focusManager: detail.fakeFocus ? highlights() : dom$2()
  8408. }));
  8409. };
  8410. return name === primaryName ? {
  8411. type: 'prepared',
  8412. menu: container.getSystem().build(makeSketch())
  8413. } : {
  8414. type: 'notbuilt',
  8415. nbMenu: makeSketch
  8416. };
  8417. });
  8418. };
  8419. var layeredState = LayeredState.init();
  8420. var setup = function (container) {
  8421. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8422. var directory = toDirectory();
  8423. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8424. return layeredState.getPrimary();
  8425. };
  8426. var getItemValue = function (item) {
  8427. return Representing.getValue(item).value;
  8428. };
  8429. var getItemByValue = function (_container, menus, itemValue) {
  8430. return findMap(menus, function (menu) {
  8431. if (!menu.getSystem().isConnected()) {
  8432. return Optional.none();
  8433. }
  8434. var candidates = Highlighting.getCandidates(menu);
  8435. return find$5(candidates, function (c) {
  8436. return getItemValue(c) === itemValue;
  8437. });
  8438. });
  8439. };
  8440. var toDirectory = function (_container) {
  8441. return map$1(detail.data.menus, function (data, _menuName) {
  8442. return bind$3(data.items, function (item) {
  8443. return item.type === 'separator' ? [] : [item.data.value];
  8444. });
  8445. });
  8446. };
  8447. var setActiveMenu = function (container, menu) {
  8448. Highlighting.highlight(container, menu);
  8449. Highlighting.getHighlighted(menu).orThunk(function () {
  8450. return Highlighting.getFirst(menu);
  8451. }).each(function (item) {
  8452. dispatch(container, item.element, focusItem());
  8453. });
  8454. };
  8455. var getMenus = function (state, menuValues) {
  8456. return cat(map$2(menuValues, function (mv) {
  8457. return state.lookupMenu(mv).bind(function (prep) {
  8458. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8459. });
  8460. }));
  8461. };
  8462. var closeOthers = function (container, state, path) {
  8463. var others = getMenus(state, state.otherMenus(path));
  8464. each$1(others, function (o) {
  8465. remove$1(o.element, [detail.markers.backgroundMenu]);
  8466. if (!detail.stayInDom) {
  8467. Replacing.remove(container, o);
  8468. }
  8469. });
  8470. };
  8471. var getSubmenuParents = function (container) {
  8472. return submenuParentItems.get().getOrThunk(function () {
  8473. var r = {};
  8474. var items = descendants(container.element, '.' + detail.markers.item);
  8475. var parentItems = filter$2(items, function (i) {
  8476. return get$d(i, 'aria-haspopup') === 'true';
  8477. });
  8478. each$1(parentItems, function (i) {
  8479. container.getSystem().getByDom(i).each(function (itemComp) {
  8480. var key = getItemValue(itemComp);
  8481. r[key] = itemComp;
  8482. });
  8483. });
  8484. submenuParentItems.set(r);
  8485. return r;
  8486. });
  8487. };
  8488. var updateAriaExpansions = function (container, path) {
  8489. var parentItems = getSubmenuParents(container);
  8490. each(parentItems, function (v, k) {
  8491. var expanded = contains$2(path, k);
  8492. set$8(v.element, 'aria-expanded', expanded);
  8493. });
  8494. };
  8495. var updateMenuPath = function (container, state, path) {
  8496. return Optional.from(path[0]).bind(function (latestMenuName) {
  8497. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8498. if (menuPrep.type === 'notbuilt') {
  8499. return Optional.none();
  8500. } else {
  8501. var activeMenu = menuPrep.menu;
  8502. var rest = getMenus(state, path.slice(1));
  8503. each$1(rest, function (r) {
  8504. add$2(r.element, detail.markers.backgroundMenu);
  8505. });
  8506. if (!inBody(activeMenu.element)) {
  8507. Replacing.append(container, premade(activeMenu));
  8508. }
  8509. remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  8510. setActiveMenu(container, activeMenu);
  8511. closeOthers(container, state, path);
  8512. return Optional.some(activeMenu);
  8513. }
  8514. });
  8515. });
  8516. };
  8517. var ExpandHighlightDecision;
  8518. (function (ExpandHighlightDecision) {
  8519. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8520. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8521. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8522. var buildIfRequired = function (container, menuName, menuPrep) {
  8523. if (menuPrep.type === 'notbuilt') {
  8524. var menu = container.getSystem().build(menuPrep.nbMenu());
  8525. layeredState.setMenuBuilt(menuName, menu);
  8526. return menu;
  8527. } else {
  8528. return menuPrep.menu;
  8529. }
  8530. };
  8531. var expandRight = function (container, item, decision) {
  8532. if (decision === void 0) {
  8533. decision = ExpandHighlightDecision.HighlightSubmenu;
  8534. }
  8535. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8536. return Optional.some(item);
  8537. } else {
  8538. var value = getItemValue(item);
  8539. return layeredState.expand(value).bind(function (path) {
  8540. updateAriaExpansions(container, path);
  8541. return Optional.from(path[0]).bind(function (menuName) {
  8542. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8543. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8544. if (!inBody(activeMenu.element)) {
  8545. Replacing.append(container, premade(activeMenu));
  8546. }
  8547. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8548. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8549. Highlighting.highlightFirst(activeMenu);
  8550. return updateMenuPath(container, layeredState, path);
  8551. } else {
  8552. Highlighting.dehighlightAll(activeMenu);
  8553. return Optional.some(item);
  8554. }
  8555. });
  8556. });
  8557. });
  8558. }
  8559. };
  8560. var collapseLeft = function (container, item) {
  8561. var value = getItemValue(item);
  8562. return layeredState.collapse(value).bind(function (path) {
  8563. updateAriaExpansions(container, path);
  8564. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8565. detail.onCollapseMenu(container, item, activeMenu);
  8566. return activeMenu;
  8567. });
  8568. });
  8569. };
  8570. var updateView = function (container, item) {
  8571. var value = getItemValue(item);
  8572. return layeredState.refresh(value).bind(function (path) {
  8573. updateAriaExpansions(container, path);
  8574. return updateMenuPath(container, layeredState, path);
  8575. });
  8576. };
  8577. var onRight = function (container, item) {
  8578. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8579. };
  8580. var onLeft = function (container, item) {
  8581. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8582. };
  8583. var onEscape = function (container, item) {
  8584. return collapseLeft(container, item).orThunk(function () {
  8585. return detail.onEscape(container, item).map(function () {
  8586. return container;
  8587. });
  8588. });
  8589. };
  8590. var keyOnItem = function (f) {
  8591. return function (container, simulatedEvent) {
  8592. return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8593. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8594. return f(container, item).map(always);
  8595. });
  8596. });
  8597. };
  8598. };
  8599. var events = derive$2([
  8600. run$1(focus(), function (sandbox, simulatedEvent) {
  8601. var item = simulatedEvent.event.item;
  8602. layeredState.lookupItem(getItemValue(item)).each(function () {
  8603. var menu = simulatedEvent.event.menu;
  8604. Highlighting.highlight(sandbox, menu);
  8605. var value = getItemValue(simulatedEvent.event.item);
  8606. layeredState.refresh(value).each(function (path) {
  8607. return closeOthers(sandbox, layeredState, path);
  8608. });
  8609. });
  8610. }),
  8611. runOnExecute$1(function (component, simulatedEvent) {
  8612. var target = simulatedEvent.event.target;
  8613. component.getSystem().getByDom(target).each(function (item) {
  8614. var itemValue = getItemValue(item);
  8615. if (itemValue.indexOf('collapse-item') === 0) {
  8616. collapseLeft(component, item);
  8617. }
  8618. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8619. detail.onExecute(component, item);
  8620. }, noop);
  8621. });
  8622. }),
  8623. runOnAttached(function (container, _simulatedEvent) {
  8624. setup(container).each(function (primary) {
  8625. Replacing.append(container, premade(primary));
  8626. detail.onOpenMenu(container, primary);
  8627. if (detail.highlightImmediately) {
  8628. setActiveMenu(container, primary);
  8629. }
  8630. });
  8631. })
  8632. ].concat(detail.navigateOnHover ? [run$1(hover(), function (sandbox, simulatedEvent) {
  8633. var item = simulatedEvent.event.item;
  8634. updateView(sandbox, item);
  8635. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8636. detail.onHover(sandbox, item);
  8637. })] : []));
  8638. var getActiveItem = function (container) {
  8639. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8640. };
  8641. var collapseMenuApi = function (container) {
  8642. getActiveItem(container).each(function (currentItem) {
  8643. collapseLeft(container, currentItem);
  8644. });
  8645. };
  8646. var highlightPrimary = function (container) {
  8647. layeredState.getPrimary().each(function (primary) {
  8648. setActiveMenu(container, primary);
  8649. });
  8650. };
  8651. var extractMenuFromContainer = function (container) {
  8652. return Optional.from(container.components()[0]).filter(function (comp) {
  8653. return get$d(comp.element, 'role') === 'menu';
  8654. });
  8655. };
  8656. var repositionMenus = function (container) {
  8657. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8658. return getActiveItem(container).bind(function (currentItem) {
  8659. var itemValue = getItemValue(currentItem);
  8660. var allMenus = values(layeredState.getMenus());
  8661. var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8662. return layeredState.getTriggeringPath(itemValue, function (v) {
  8663. return getItemByValue(container, preparedMenus, v);
  8664. });
  8665. }).map(function (triggeringPath) {
  8666. return {
  8667. primary: primary,
  8668. triggeringPath: triggeringPath
  8669. };
  8670. });
  8671. });
  8672. maybeActivePrimary.fold(function () {
  8673. extractMenuFromContainer(container).each(function (primaryMenu) {
  8674. detail.onRepositionMenu(container, primaryMenu, []);
  8675. });
  8676. }, function (_a) {
  8677. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8678. detail.onRepositionMenu(container, primary, triggeringPath);
  8679. });
  8680. };
  8681. var apis = {
  8682. collapseMenu: collapseMenuApi,
  8683. highlightPrimary: highlightPrimary,
  8684. repositionMenus: repositionMenus
  8685. };
  8686. return {
  8687. uid: detail.uid,
  8688. dom: detail.dom,
  8689. markers: detail.markers,
  8690. behaviours: augment(detail.tmenuBehaviours, [
  8691. Keying.config({
  8692. mode: 'special',
  8693. onRight: keyOnItem(onRight),
  8694. onLeft: keyOnItem(onLeft),
  8695. onEscape: keyOnItem(onEscape),
  8696. focusIn: function (container, _keyInfo) {
  8697. layeredState.getPrimary().each(function (primary) {
  8698. dispatch(container, primary.element, focusItem());
  8699. });
  8700. }
  8701. }),
  8702. Highlighting.config({
  8703. highlightClass: detail.markers.selectedMenu,
  8704. itemClass: detail.markers.menu
  8705. }),
  8706. Composing.config({
  8707. find: function (container) {
  8708. return Highlighting.getHighlighted(container);
  8709. }
  8710. }),
  8711. Replacing.config({})
  8712. ]),
  8713. eventOrder: detail.eventOrder,
  8714. apis: apis,
  8715. events: events
  8716. };
  8717. };
  8718. var collapseItem$1 = constant$1('collapse-item');
  8719. var tieredData = function (primary, menus, expansions) {
  8720. return {
  8721. primary: primary,
  8722. menus: menus,
  8723. expansions: expansions
  8724. };
  8725. };
  8726. var singleData = function (name, menu) {
  8727. return {
  8728. primary: name,
  8729. menus: wrap$1(name, menu),
  8730. expansions: {}
  8731. };
  8732. };
  8733. var collapseItem = function (text) {
  8734. return {
  8735. value: generate$6(collapseItem$1()),
  8736. meta: { text: text }
  8737. };
  8738. };
  8739. var tieredMenu = single({
  8740. name: 'TieredMenu',
  8741. configFields: [
  8742. onStrictKeyboardHandler('onExecute'),
  8743. onStrictKeyboardHandler('onEscape'),
  8744. onStrictHandler('onOpenMenu'),
  8745. onStrictHandler('onOpenSubmenu'),
  8746. onHandler('onRepositionMenu'),
  8747. onHandler('onCollapseMenu'),
  8748. defaulted('highlightImmediately', true),
  8749. requiredObjOf('data', [
  8750. required$1('primary'),
  8751. required$1('menus'),
  8752. required$1('expansions')
  8753. ]),
  8754. defaulted('fakeFocus', false),
  8755. onHandler('onHighlight'),
  8756. onHandler('onHover'),
  8757. tieredMenuMarkers(),
  8758. required$1('dom'),
  8759. defaulted('navigateOnHover', true),
  8760. defaulted('stayInDom', false),
  8761. field('tmenuBehaviours', [
  8762. Keying,
  8763. Highlighting,
  8764. Composing,
  8765. Replacing
  8766. ]),
  8767. defaulted('eventOrder', {})
  8768. ],
  8769. apis: {
  8770. collapseMenu: function (apis, tmenu) {
  8771. apis.collapseMenu(tmenu);
  8772. },
  8773. highlightPrimary: function (apis, tmenu) {
  8774. apis.highlightPrimary(tmenu);
  8775. },
  8776. repositionMenus: function (apis, tmenu) {
  8777. apis.repositionMenus(tmenu);
  8778. }
  8779. },
  8780. factory: make$6,
  8781. extraApis: {
  8782. tieredData: tieredData,
  8783. singleData: singleData,
  8784. collapseItem: collapseItem
  8785. }
  8786. });
  8787. var makeMenu = function (detail, menuSandbox, placementSpec, menuSpec, getBounds) {
  8788. var lazySink = function () {
  8789. return detail.lazySink(menuSandbox);
  8790. };
  8791. var layouts = menuSpec.type === 'horizontal' ? {
  8792. layouts: {
  8793. onLtr: function () {
  8794. return belowOrAbove();
  8795. },
  8796. onRtl: function () {
  8797. return belowOrAboveRtl();
  8798. }
  8799. }
  8800. } : {};
  8801. var isFirstTierSubmenu = function (triggeringPaths) {
  8802. return triggeringPaths.length === 2;
  8803. };
  8804. var getSubmenuLayouts = function (triggeringPaths) {
  8805. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8806. };
  8807. return tieredMenu.sketch({
  8808. dom: { tag: 'div' },
  8809. data: menuSpec.data,
  8810. markers: menuSpec.menu.markers,
  8811. highlightImmediately: menuSpec.menu.highlightImmediately,
  8812. onEscape: function () {
  8813. Sandboxing.close(menuSandbox);
  8814. detail.onEscape.map(function (handler) {
  8815. return handler(menuSandbox);
  8816. });
  8817. return Optional.some(true);
  8818. },
  8819. onExecute: function () {
  8820. return Optional.some(true);
  8821. },
  8822. onOpenMenu: function (tmenu, menu) {
  8823. Positioning.positionWithinBounds(lazySink().getOrDie(), menu, placementSpec, getBounds());
  8824. },
  8825. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8826. var sink = lazySink().getOrDie();
  8827. Positioning.position(sink, submenu, {
  8828. anchor: __assign({
  8829. type: 'submenu',
  8830. item: item
  8831. }, getSubmenuLayouts(triggeringPaths))
  8832. });
  8833. },
  8834. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8835. var sink = lazySink().getOrDie();
  8836. Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds());
  8837. each$1(submenuTriggers, function (st) {
  8838. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8839. Positioning.position(sink, st.triggeredMenu, {
  8840. anchor: __assign({
  8841. type: 'submenu',
  8842. item: st.triggeringItem
  8843. }, submenuLayouts)
  8844. });
  8845. });
  8846. }
  8847. });
  8848. };
  8849. var factory$m = function (detail, spec) {
  8850. var isPartOfRelated = function (sandbox, queryElem) {
  8851. var related = detail.getRelated(sandbox);
  8852. return related.exists(function (rel) {
  8853. return isPartOf$1(rel, queryElem);
  8854. });
  8855. };
  8856. var setContent = function (sandbox, thing) {
  8857. Sandboxing.setContent(sandbox, thing);
  8858. };
  8859. var showAt = function (sandbox, thing, placementSpec) {
  8860. showWithin(sandbox, thing, placementSpec, Optional.none());
  8861. };
  8862. var showWithin = function (sandbox, thing, placementSpec, boxElement) {
  8863. showWithinBounds(sandbox, thing, placementSpec, function () {
  8864. return boxElement.map(function (elem) {
  8865. return box$1(elem);
  8866. });
  8867. });
  8868. };
  8869. var showWithinBounds = function (sandbox, thing, placementSpec, getBounds) {
  8870. var sink = detail.lazySink(sandbox).getOrDie();
  8871. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8872. return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds());
  8873. });
  8874. Representing.setValue(sandbox, Optional.some({
  8875. mode: 'position',
  8876. config: placementSpec,
  8877. getBounds: getBounds
  8878. }));
  8879. };
  8880. var showMenuAt = function (sandbox, placementSpec, menuSpec) {
  8881. showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none);
  8882. };
  8883. var showMenuWithinBounds = function (sandbox, placementSpec, menuSpec, getBounds) {
  8884. var menu = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds);
  8885. Sandboxing.open(sandbox, menu);
  8886. Representing.setValue(sandbox, Optional.some({
  8887. mode: 'menu',
  8888. menu: menu
  8889. }));
  8890. };
  8891. var hide = function (sandbox) {
  8892. if (Sandboxing.isOpen(sandbox)) {
  8893. Representing.setValue(sandbox, Optional.none());
  8894. Sandboxing.close(sandbox);
  8895. }
  8896. };
  8897. var getContent = function (sandbox) {
  8898. return Sandboxing.getState(sandbox);
  8899. };
  8900. var reposition = function (sandbox) {
  8901. if (Sandboxing.isOpen(sandbox)) {
  8902. Representing.getValue(sandbox).each(function (state) {
  8903. switch (state.mode) {
  8904. case 'menu':
  8905. Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus);
  8906. break;
  8907. case 'position':
  8908. var sink = detail.lazySink(sandbox).getOrDie();
  8909. Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds());
  8910. break;
  8911. }
  8912. });
  8913. }
  8914. };
  8915. var apis = {
  8916. setContent: setContent,
  8917. showAt: showAt,
  8918. showWithin: showWithin,
  8919. showWithinBounds: showWithinBounds,
  8920. showMenuAt: showMenuAt,
  8921. showMenuWithinBounds: showMenuWithinBounds,
  8922. hide: hide,
  8923. getContent: getContent,
  8924. reposition: reposition,
  8925. isOpen: Sandboxing.isOpen
  8926. };
  8927. return {
  8928. uid: detail.uid,
  8929. dom: detail.dom,
  8930. behaviours: augment(detail.inlineBehaviours, [
  8931. Sandboxing.config({
  8932. isPartOf: function (sandbox, data, queryElem) {
  8933. return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8934. },
  8935. getAttachPoint: function (sandbox) {
  8936. return detail.lazySink(sandbox).getOrDie();
  8937. },
  8938. onOpen: function (sandbox) {
  8939. detail.onShow(sandbox);
  8940. },
  8941. onClose: function (sandbox) {
  8942. detail.onHide(sandbox);
  8943. }
  8944. }),
  8945. Representing.config({
  8946. store: {
  8947. mode: 'memory',
  8948. initialValue: Optional.none()
  8949. }
  8950. }),
  8951. Receiving.config({
  8952. channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) {
  8953. return { fireEventInstead: { event: fe.event } };
  8954. }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) {
  8955. return { fireEventInstead: { event: fe.event } };
  8956. }).getOr({})), { doReposition: reposition })))
  8957. })
  8958. ]),
  8959. eventOrder: detail.eventOrder,
  8960. apis: apis
  8961. };
  8962. };
  8963. var InlineView = single({
  8964. name: 'InlineView',
  8965. configFields: [
  8966. required$1('lazySink'),
  8967. onHandler('onShow'),
  8968. onHandler('onHide'),
  8969. optionFunction('onEscape'),
  8970. field('inlineBehaviours', [
  8971. Sandboxing,
  8972. Representing,
  8973. Receiving
  8974. ]),
  8975. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  8976. optionObjOf('fireRepositionEventInstead', [defaulted('event', repositionRequested())]),
  8977. defaulted('getRelated', Optional.none),
  8978. defaulted('isExtraPart', never),
  8979. defaulted('eventOrder', Optional.none)
  8980. ],
  8981. factory: factory$m,
  8982. apis: {
  8983. showAt: function (apis, component, anchor, thing) {
  8984. apis.showAt(component, anchor, thing);
  8985. },
  8986. showWithin: function (apis, component, anchor, thing, boxElement) {
  8987. apis.showWithin(component, anchor, thing, boxElement);
  8988. },
  8989. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8990. apis.showWithinBounds(component, anchor, thing, bounds);
  8991. },
  8992. showMenuAt: function (apis, component, anchor, menuSpec) {
  8993. apis.showMenuAt(component, anchor, menuSpec);
  8994. },
  8995. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8996. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8997. },
  8998. hide: function (apis, component) {
  8999. apis.hide(component);
  9000. },
  9001. isOpen: function (apis, component) {
  9002. return apis.isOpen(component);
  9003. },
  9004. getContent: function (apis, component) {
  9005. return apis.getContent(component);
  9006. },
  9007. setContent: function (apis, component, thing) {
  9008. apis.setContent(component, thing);
  9009. },
  9010. reposition: function (apis, component) {
  9011. apis.reposition(component);
  9012. }
  9013. }
  9014. });
  9015. var labelPrefix = 'layout-inset';
  9016. var westEdgeX = function (anchor) {
  9017. return anchor.x;
  9018. };
  9019. var middleX = function (anchor, element) {
  9020. return anchor.x + anchor.width / 2 - element.width / 2;
  9021. };
  9022. var eastEdgeX = function (anchor, element) {
  9023. return anchor.x + anchor.width - element.width;
  9024. };
  9025. var northY = function (anchor) {
  9026. return anchor.y;
  9027. };
  9028. var southY = function (anchor, element) {
  9029. return anchor.y + anchor.height - element.height;
  9030. };
  9031. var centreY = function (anchor, element) {
  9032. return anchor.y + anchor.height / 2 - element.height / 2;
  9033. };
  9034. var southwest = function (anchor, element, bubbles) {
  9035. return nu$6(eastEdgeX(anchor, element), southY(anchor, element), bubbles.insetSouthwest(), northwest$3(), 'southwest', boundsRestriction(anchor, {
  9036. right: 0,
  9037. bottom: 3
  9038. }), labelPrefix);
  9039. };
  9040. var southeast = function (anchor, element, bubbles) {
  9041. return nu$6(westEdgeX(anchor), southY(anchor, element), bubbles.insetSoutheast(), northeast$3(), 'southeast', boundsRestriction(anchor, {
  9042. left: 1,
  9043. bottom: 3
  9044. }), labelPrefix);
  9045. };
  9046. var northwest = function (anchor, element, bubbles) {
  9047. return nu$6(eastEdgeX(anchor, element), northY(anchor), bubbles.insetNorthwest(), southwest$3(), 'northwest', boundsRestriction(anchor, {
  9048. right: 0,
  9049. top: 2
  9050. }), labelPrefix);
  9051. };
  9052. var northeast = function (anchor, element, bubbles) {
  9053. return nu$6(westEdgeX(anchor), northY(anchor), bubbles.insetNortheast(), southeast$3(), 'northeast', boundsRestriction(anchor, {
  9054. left: 1,
  9055. top: 2
  9056. }), labelPrefix);
  9057. };
  9058. var north = function (anchor, element, bubbles) {
  9059. return nu$6(middleX(anchor, element), northY(anchor), bubbles.insetNorth(), south$3(), 'north', boundsRestriction(anchor, { top: 2 }), labelPrefix);
  9060. };
  9061. var south = function (anchor, element, bubbles) {
  9062. return nu$6(middleX(anchor, element), southY(anchor, element), bubbles.insetSouth(), north$3(), 'south', boundsRestriction(anchor, { bottom: 3 }), labelPrefix);
  9063. };
  9064. var east = function (anchor, element, bubbles) {
  9065. return nu$6(eastEdgeX(anchor, element), centreY(anchor, element), bubbles.insetEast(), west$3(), 'east', boundsRestriction(anchor, { right: 0 }), labelPrefix);
  9066. };
  9067. var west = function (anchor, element, bubbles) {
  9068. return nu$6(westEdgeX(anchor), centreY(anchor, element), bubbles.insetWest(), east$3(), 'west', boundsRestriction(anchor, { left: 1 }), labelPrefix);
  9069. };
  9070. var lookupPreserveLayout = function (lastPlacement) {
  9071. switch (lastPlacement) {
  9072. case 'north':
  9073. return north;
  9074. case 'northeast':
  9075. return northeast;
  9076. case 'northwest':
  9077. return northwest;
  9078. case 'south':
  9079. return south;
  9080. case 'southeast':
  9081. return southeast;
  9082. case 'southwest':
  9083. return southwest;
  9084. case 'east':
  9085. return east;
  9086. case 'west':
  9087. return west;
  9088. }
  9089. };
  9090. var preserve = function (anchor, element, bubbles, placee, bounds) {
  9091. var layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north);
  9092. return layout(anchor, element, bubbles, placee, bounds);
  9093. };
  9094. var lookupFlippedLayout = function (lastPlacement) {
  9095. switch (lastPlacement) {
  9096. case 'north':
  9097. return south;
  9098. case 'northeast':
  9099. return southeast;
  9100. case 'northwest':
  9101. return southwest;
  9102. case 'south':
  9103. return north;
  9104. case 'southeast':
  9105. return northeast;
  9106. case 'southwest':
  9107. return northwest;
  9108. case 'east':
  9109. return west;
  9110. case 'west':
  9111. return east;
  9112. }
  9113. };
  9114. var flip$2 = function (anchor, element, bubbles, placee, bounds) {
  9115. var layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north);
  9116. return layout(anchor, element, bubbles, placee, bounds);
  9117. };
  9118. var global$f = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9119. var factory$l = function (detail) {
  9120. var events = events$a(detail.action);
  9121. var tag = detail.dom.tag;
  9122. var lookupAttr = function (attr) {
  9123. return get$e(detail.dom, 'attributes').bind(function (attrs) {
  9124. return get$e(attrs, attr);
  9125. });
  9126. };
  9127. var getModAttributes = function () {
  9128. if (tag === 'button') {
  9129. var type = lookupAttr('type').getOr('button');
  9130. var roleAttrs = lookupAttr('role').map(function (role) {
  9131. return { role: role };
  9132. }).getOr({});
  9133. return __assign({ type: type }, roleAttrs);
  9134. } else {
  9135. var role = lookupAttr('role').getOr('button');
  9136. return { role: role };
  9137. }
  9138. };
  9139. return {
  9140. uid: detail.uid,
  9141. dom: detail.dom,
  9142. components: detail.components,
  9143. events: events,
  9144. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  9145. Focusing.config({}),
  9146. Keying.config({
  9147. mode: 'execution',
  9148. useSpace: true,
  9149. useEnter: true
  9150. })
  9151. ]),
  9152. domModification: { attributes: getModAttributes() },
  9153. eventOrder: detail.eventOrder
  9154. };
  9155. };
  9156. var Button = single({
  9157. name: 'Button',
  9158. factory: factory$l,
  9159. configFields: [
  9160. defaulted('uid', undefined),
  9161. required$1('dom'),
  9162. defaulted('components', []),
  9163. SketchBehaviours.field('buttonBehaviours', [
  9164. Focusing,
  9165. Keying
  9166. ]),
  9167. option('action'),
  9168. option('role'),
  9169. defaulted('eventOrder', {})
  9170. ]
  9171. });
  9172. var record = function (spec) {
  9173. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$5('memento');
  9174. var get = function (anyInSystem) {
  9175. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  9176. };
  9177. var getOpt = function (anyInSystem) {
  9178. return anyInSystem.getSystem().getByUid(uid).toOptional();
  9179. };
  9180. var asSpec = function () {
  9181. return __assign(__assign({}, spec), { uid: uid });
  9182. };
  9183. return {
  9184. get: get,
  9185. getOpt: getOpt,
  9186. asSpec: asSpec
  9187. };
  9188. };
  9189. var global$e = tinymce.util.Tools.resolve('tinymce.util.I18n');
  9190. var rtlTransform = {
  9191. 'indent': true,
  9192. 'outdent': true,
  9193. 'table-insert-column-after': true,
  9194. 'table-insert-column-before': true,
  9195. 'paste-column-after': true,
  9196. 'paste-column-before': true,
  9197. 'unordered-list': true,
  9198. 'list-bull-circle': true,
  9199. 'list-bull-default': true,
  9200. 'list-bull-square': true
  9201. };
  9202. var defaultIconName = 'temporary-placeholder';
  9203. var defaultIcon = function (icons) {
  9204. return function () {
  9205. return get$e(icons, defaultIconName).getOr('!not found!');
  9206. };
  9207. };
  9208. var getIconName = function (name, icons) {
  9209. var lcName = name.toLowerCase();
  9210. if (global$e.isRtl()) {
  9211. var rtlName = ensureTrailing(lcName, '-rtl');
  9212. return has$2(icons, rtlName) ? rtlName : lcName;
  9213. } else {
  9214. return lcName;
  9215. }
  9216. };
  9217. var lookupIcon = function (name, icons) {
  9218. return get$e(icons, getIconName(name, icons));
  9219. };
  9220. var get$1 = function (name, iconProvider) {
  9221. var icons = iconProvider();
  9222. return lookupIcon(name, icons).getOrThunk(defaultIcon(icons));
  9223. };
  9224. var getOr = function (name, iconProvider, fallbackIcon) {
  9225. var icons = iconProvider();
  9226. return lookupIcon(name, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  9227. };
  9228. var needsRtlTransform = function (iconName) {
  9229. return global$e.isRtl() ? has$2(rtlTransform, iconName) : false;
  9230. };
  9231. var addFocusableBehaviour = function () {
  9232. return config('add-focusable', [runOnAttached(function (comp) {
  9233. child(comp.element, 'svg').each(function (svg) {
  9234. return set$8(svg, 'focusable', 'false');
  9235. });
  9236. })]);
  9237. };
  9238. var renderIcon$2 = function (spec, iconName, icons, fallbackIcon) {
  9239. var _a, _b;
  9240. var rtlIconClasses = needsRtlTransform(iconName) ? ['tox-icon--flip'] : [];
  9241. var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons));
  9242. return {
  9243. dom: {
  9244. tag: spec.tag,
  9245. attributes: (_a = spec.attributes) !== null && _a !== void 0 ? _a : {},
  9246. classes: spec.classes.concat(rtlIconClasses),
  9247. innerHtml: iconHtml
  9248. },
  9249. behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : [], true), [addFocusableBehaviour()], false))
  9250. };
  9251. };
  9252. var render$3 = function (iconName, spec, iconProvider, fallbackIcon) {
  9253. if (fallbackIcon === void 0) {
  9254. fallbackIcon = Optional.none();
  9255. }
  9256. return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon);
  9257. };
  9258. var renderFirst = function (iconNames, spec, iconProvider) {
  9259. var icons = iconProvider();
  9260. var iconName = find$5(iconNames, function (name) {
  9261. return has$2(icons, getIconName(name, icons));
  9262. });
  9263. return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none());
  9264. };
  9265. var notificationIconMap = {
  9266. success: 'checkmark',
  9267. error: 'warning',
  9268. err: 'error',
  9269. warning: 'warning',
  9270. warn: 'warning',
  9271. info: 'info'
  9272. };
  9273. var factory$k = function (detail) {
  9274. var memBannerText = record({
  9275. dom: {
  9276. tag: 'p',
  9277. innerHtml: detail.translationProvider(detail.text)
  9278. },
  9279. behaviours: derive$1([Replacing.config({})])
  9280. });
  9281. var renderPercentBar = function (percent) {
  9282. return {
  9283. dom: {
  9284. tag: 'div',
  9285. classes: ['tox-bar'],
  9286. attributes: { style: 'width: ' + percent + '%' }
  9287. }
  9288. };
  9289. };
  9290. var renderPercentText = function (percent) {
  9291. return {
  9292. dom: {
  9293. tag: 'div',
  9294. classes: ['tox-text'],
  9295. innerHtml: percent + '%'
  9296. }
  9297. };
  9298. };
  9299. var memBannerProgress = record({
  9300. dom: {
  9301. tag: 'div',
  9302. classes: detail.progress ? [
  9303. 'tox-progress-bar',
  9304. 'tox-progress-indicator'
  9305. ] : ['tox-progress-bar']
  9306. },
  9307. components: [
  9308. {
  9309. dom: {
  9310. tag: 'div',
  9311. classes: ['tox-bar-container']
  9312. },
  9313. components: [renderPercentBar(0)]
  9314. },
  9315. renderPercentText(0)
  9316. ],
  9317. behaviours: derive$1([Replacing.config({})])
  9318. });
  9319. var updateProgress = function (comp, percent) {
  9320. if (comp.getSystem().isConnected()) {
  9321. memBannerProgress.getOpt(comp).each(function (progress) {
  9322. Replacing.set(progress, [
  9323. {
  9324. dom: {
  9325. tag: 'div',
  9326. classes: ['tox-bar-container']
  9327. },
  9328. components: [renderPercentBar(percent)]
  9329. },
  9330. renderPercentText(percent)
  9331. ]);
  9332. });
  9333. }
  9334. };
  9335. var updateText = function (comp, text$1) {
  9336. if (comp.getSystem().isConnected()) {
  9337. var banner = memBannerText.get(comp);
  9338. Replacing.set(banner, [text(text$1)]);
  9339. }
  9340. };
  9341. var apis = {
  9342. updateProgress: updateProgress,
  9343. updateText: updateText
  9344. };
  9345. var iconChoices = flatten([
  9346. detail.icon.toArray(),
  9347. detail.level.toArray(),
  9348. detail.level.bind(function (level) {
  9349. return Optional.from(notificationIconMap[level]);
  9350. }).toArray()
  9351. ]);
  9352. var memButton = record(Button.sketch({
  9353. dom: {
  9354. tag: 'button',
  9355. classes: [
  9356. 'tox-notification__dismiss',
  9357. 'tox-button',
  9358. 'tox-button--naked',
  9359. 'tox-button--icon'
  9360. ]
  9361. },
  9362. components: [render$3('close', {
  9363. tag: 'div',
  9364. classes: ['tox-icon'],
  9365. attributes: { 'aria-label': detail.translationProvider('Close') }
  9366. }, detail.iconProvider)],
  9367. action: function (comp) {
  9368. detail.onAction(comp);
  9369. }
  9370. }));
  9371. var notificationIconSpec = renderFirst(iconChoices, {
  9372. tag: 'div',
  9373. classes: ['tox-notification__icon']
  9374. }, detail.iconProvider);
  9375. var notificationBodySpec = {
  9376. dom: {
  9377. tag: 'div',
  9378. classes: ['tox-notification__body']
  9379. },
  9380. components: [memBannerText.asSpec()],
  9381. behaviours: derive$1([Replacing.config({})])
  9382. };
  9383. var components = [
  9384. notificationIconSpec,
  9385. notificationBodySpec
  9386. ];
  9387. return {
  9388. uid: detail.uid,
  9389. dom: {
  9390. tag: 'div',
  9391. attributes: { role: 'alert' },
  9392. classes: detail.level.map(function (level) {
  9393. return [
  9394. 'tox-notification',
  9395. 'tox-notification--in',
  9396. 'tox-notification--' + level
  9397. ];
  9398. }).getOr([
  9399. 'tox-notification',
  9400. 'tox-notification--in'
  9401. ])
  9402. },
  9403. behaviours: derive$1([
  9404. Focusing.config({}),
  9405. config('notification-events', [run$1(focusin(), function (comp) {
  9406. memButton.getOpt(comp).each(Focusing.focus);
  9407. })])
  9408. ]),
  9409. components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]),
  9410. apis: apis
  9411. };
  9412. };
  9413. var Notification = single({
  9414. name: 'Notification',
  9415. factory: factory$k,
  9416. configFields: [
  9417. option('level'),
  9418. required$1('progress'),
  9419. required$1('icon'),
  9420. required$1('onAction'),
  9421. required$1('text'),
  9422. required$1('iconProvider'),
  9423. required$1('translationProvider'),
  9424. defaultedBoolean('closeButton', true)
  9425. ],
  9426. apis: {
  9427. updateProgress: function (apis, comp, percent) {
  9428. apis.updateProgress(comp, percent);
  9429. },
  9430. updateText: function (apis, comp, text) {
  9431. apis.updateText(comp, text);
  9432. }
  9433. }
  9434. });
  9435. function NotificationManagerImpl (editor, extras, uiMothership) {
  9436. var sharedBackstage = extras.backstage.shared;
  9437. var getLayoutDirection = function (rel) {
  9438. switch (rel) {
  9439. case 'bc-bc':
  9440. return south;
  9441. case 'tc-tc':
  9442. return north;
  9443. case 'tc-bc':
  9444. return north$2;
  9445. case 'bc-tc':
  9446. default:
  9447. return south$2;
  9448. }
  9449. };
  9450. var reposition = function (notifications) {
  9451. if (notifications.length > 0) {
  9452. each$1(notifications, function (notification, index) {
  9453. if (index === 0) {
  9454. notification.moveRel(null, 'banner');
  9455. } else {
  9456. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  9457. }
  9458. });
  9459. }
  9460. };
  9461. var open = function (settings, closeCallback) {
  9462. var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  9463. var close = function () {
  9464. closeCallback();
  9465. InlineView.hide(notificationWrapper);
  9466. };
  9467. var notification = build$1(Notification.sketch({
  9468. text: settings.text,
  9469. level: contains$2([
  9470. 'success',
  9471. 'error',
  9472. 'warning',
  9473. 'warn',
  9474. 'info'
  9475. ], settings.type) ? settings.type : undefined,
  9476. progress: settings.progressBar === true,
  9477. icon: Optional.from(settings.icon),
  9478. closeButton: !hideCloseButton,
  9479. onAction: close,
  9480. iconProvider: sharedBackstage.providers.icons,
  9481. translationProvider: sharedBackstage.providers.translate
  9482. }));
  9483. var notificationWrapper = build$1(InlineView.sketch(__assign({
  9484. dom: {
  9485. tag: 'div',
  9486. classes: ['tox-notifications-container']
  9487. },
  9488. lazySink: sharedBackstage.getSink,
  9489. fireDismissalEventInstead: {}
  9490. }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
  9491. uiMothership.add(notificationWrapper);
  9492. if (settings.timeout > 0) {
  9493. global$f.setTimeout(function () {
  9494. close();
  9495. }, settings.timeout);
  9496. }
  9497. var getBounds = function () {
  9498. var contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  9499. var win$1 = win();
  9500. var x = clamp$1(win$1.x, contentArea.x, contentArea.right);
  9501. var y = clamp$1(win$1.y, contentArea.y, contentArea.bottom);
  9502. var right = Math.max(contentArea.right, win$1.right);
  9503. var bottom = Math.max(contentArea.bottom, win$1.bottom);
  9504. return Optional.some(bounds(x, y, right - x, bottom - y));
  9505. };
  9506. return {
  9507. close: close,
  9508. moveTo: function (x, y) {
  9509. InlineView.showAt(notificationWrapper, premade(notification), {
  9510. anchor: {
  9511. type: 'makeshift',
  9512. x: x,
  9513. y: y
  9514. }
  9515. });
  9516. },
  9517. moveRel: function (element, rel) {
  9518. var notificationSpec = premade(notification);
  9519. var anchorOverrides = { maxHeightFunction: expandable$1() };
  9520. if (rel !== 'banner' && isNonNullable(element)) {
  9521. var layoutDirection_1 = getLayoutDirection(rel);
  9522. var nodeAnchor = {
  9523. type: 'node',
  9524. root: body(),
  9525. node: Optional.some(SugarElement.fromDom(element)),
  9526. overrides: anchorOverrides,
  9527. layouts: {
  9528. onRtl: function () {
  9529. return [layoutDirection_1];
  9530. },
  9531. onLtr: function () {
  9532. return [layoutDirection_1];
  9533. }
  9534. }
  9535. };
  9536. InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds);
  9537. } else {
  9538. var anchor = __assign(__assign({}, sharedBackstage.anchors.banner()), { overrides: anchorOverrides });
  9539. InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: anchor }, getBounds);
  9540. }
  9541. },
  9542. text: function (nuText) {
  9543. Notification.updateText(notification, nuText);
  9544. },
  9545. settings: settings,
  9546. getEl: function () {
  9547. return notification.element.dom;
  9548. },
  9549. progressBar: {
  9550. value: function (percent) {
  9551. Notification.updateProgress(notification, percent);
  9552. }
  9553. }
  9554. };
  9555. };
  9556. var close = function (notification) {
  9557. notification.close();
  9558. };
  9559. var getArgs = function (notification) {
  9560. return notification.settings;
  9561. };
  9562. return {
  9563. open: open,
  9564. close: close,
  9565. reposition: reposition,
  9566. getArgs: getArgs
  9567. };
  9568. }
  9569. var first = function (fn, rate) {
  9570. var timer = null;
  9571. var cancel = function () {
  9572. if (!isNull(timer)) {
  9573. clearTimeout(timer);
  9574. timer = null;
  9575. }
  9576. };
  9577. var throttle = function () {
  9578. var args = [];
  9579. for (var _i = 0; _i < arguments.length; _i++) {
  9580. args[_i] = arguments[_i];
  9581. }
  9582. if (isNull(timer)) {
  9583. timer = setTimeout(function () {
  9584. timer = null;
  9585. fn.apply(null, args);
  9586. }, rate);
  9587. }
  9588. };
  9589. return {
  9590. cancel: cancel,
  9591. throttle: throttle
  9592. };
  9593. };
  9594. var last = function (fn, rate) {
  9595. var timer = null;
  9596. var cancel = function () {
  9597. if (!isNull(timer)) {
  9598. clearTimeout(timer);
  9599. timer = null;
  9600. }
  9601. };
  9602. var throttle = function () {
  9603. var args = [];
  9604. for (var _i = 0; _i < arguments.length; _i++) {
  9605. args[_i] = arguments[_i];
  9606. }
  9607. cancel();
  9608. timer = setTimeout(function () {
  9609. timer = null;
  9610. fn.apply(null, args);
  9611. }, rate);
  9612. };
  9613. return {
  9614. cancel: cancel,
  9615. throttle: throttle
  9616. };
  9617. };
  9618. var global$d = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  9619. var isBoundary = function (dom, node) {
  9620. return dom.isBlock(node) || contains$2([
  9621. 'BR',
  9622. 'IMG',
  9623. 'HR',
  9624. 'INPUT'
  9625. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9626. };
  9627. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9628. var search = global$d(dom, function (node) {
  9629. return isBoundary(dom, node);
  9630. });
  9631. return Optional.from(search.backwards(node, offset, process, rootNode));
  9632. };
  9633. var autocompleteSelector = '[data-mce-autocompleter]';
  9634. var create$4 = function (editor, range) {
  9635. return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9636. var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9637. append$2(wrapper, SugarElement.fromDom(range.extractContents()));
  9638. range.insertNode(wrapper.dom);
  9639. parent(wrapper).each(function (elm) {
  9640. return elm.dom.normalize();
  9641. });
  9642. last$1(wrapper).map(function (last) {
  9643. editor.selection.setCursorLocation(last.dom, getEnd(last));
  9644. });
  9645. return wrapper;
  9646. });
  9647. };
  9648. var detect = function (elm) {
  9649. return closest$1(elm, autocompleteSelector);
  9650. };
  9651. var isValidTextRange = function (rng) {
  9652. return rng.collapsed && rng.startContainer.nodeType === 3;
  9653. };
  9654. var getText = function (rng) {
  9655. return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9656. };
  9657. var isWhitespace = function (chr) {
  9658. return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  9659. };
  9660. var stripTriggerChar = function (text, triggerCh) {
  9661. return text.substring(triggerCh.length);
  9662. };
  9663. var findChar = function (text, index, ch) {
  9664. var i;
  9665. for (i = index - 1; i >= 0; i--) {
  9666. var char = text.charAt(i);
  9667. if (isWhitespace(char)) {
  9668. return Optional.none();
  9669. }
  9670. if (char === ch) {
  9671. break;
  9672. }
  9673. }
  9674. return Optional.some(i);
  9675. };
  9676. var findStart = function (dom, initRange, ch, minChars) {
  9677. if (minChars === void 0) {
  9678. minChars = 0;
  9679. }
  9680. if (!isValidTextRange(initRange)) {
  9681. return Optional.none();
  9682. }
  9683. var findTriggerChIndex = function (element, offset, text) {
  9684. return findChar(text, offset, ch).getOr(offset);
  9685. };
  9686. var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  9687. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  9688. var range = initRange.cloneRange();
  9689. range.setStart(spot.container, spot.offset);
  9690. range.setEnd(initRange.endContainer, initRange.endOffset);
  9691. if (range.collapsed) {
  9692. return Optional.none();
  9693. }
  9694. var text = getText(range);
  9695. var triggerCharIndex = text.lastIndexOf(ch);
  9696. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  9697. return Optional.none();
  9698. } else {
  9699. return Optional.some({
  9700. text: stripTriggerChar(text, ch),
  9701. range: range,
  9702. triggerChar: ch
  9703. });
  9704. }
  9705. });
  9706. };
  9707. var getContext = function (dom, initRange, ch, minChars) {
  9708. if (minChars === void 0) {
  9709. minChars = 0;
  9710. }
  9711. return detect(SugarElement.fromDom(initRange.startContainer)).fold(function () {
  9712. return findStart(dom, initRange, ch, minChars);
  9713. }, function (elm) {
  9714. var range = dom.createRng();
  9715. range.selectNode(elm.dom);
  9716. var text = getText(range);
  9717. return Optional.some({
  9718. range: range,
  9719. text: stripTriggerChar(text, ch),
  9720. triggerChar: ch
  9721. });
  9722. });
  9723. };
  9724. var setup$e = function (api, editor) {
  9725. editor.on('keypress compositionend', api.onKeypress.throttle);
  9726. editor.on('remove', api.onKeypress.cancel);
  9727. var redirectKeyToItem = function (item, e) {
  9728. emitWith(item, keydown(), { raw: e });
  9729. };
  9730. editor.on('keydown', function (e) {
  9731. var getItem = function () {
  9732. return api.getView().bind(Highlighting.getHighlighted);
  9733. };
  9734. if (e.which === 8) {
  9735. api.onKeypress.throttle(e);
  9736. }
  9737. if (api.isActive()) {
  9738. if (e.which === 27) {
  9739. api.cancelIfNecessary();
  9740. }
  9741. if (api.isMenuOpen()) {
  9742. if (e.which === 13) {
  9743. getItem().each(emitExecute);
  9744. e.preventDefault();
  9745. } else if (e.which === 40) {
  9746. getItem().fold(function () {
  9747. api.getView().each(Highlighting.highlightFirst);
  9748. }, function (item) {
  9749. redirectKeyToItem(item, e);
  9750. });
  9751. e.preventDefault();
  9752. e.stopImmediatePropagation();
  9753. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9754. getItem().each(function (item) {
  9755. redirectKeyToItem(item, e);
  9756. e.preventDefault();
  9757. e.stopImmediatePropagation();
  9758. });
  9759. }
  9760. } else {
  9761. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9762. api.cancelIfNecessary();
  9763. }
  9764. }
  9765. }
  9766. });
  9767. editor.on('NodeChange', function (e) {
  9768. if (api.isActive() && !api.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) {
  9769. api.cancelIfNecessary();
  9770. }
  9771. });
  9772. };
  9773. var AutocompleterEditorEvents = { setup: setup$e };
  9774. var global$c = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9775. var point = function (container, offset) {
  9776. return {
  9777. container: container,
  9778. offset: offset
  9779. };
  9780. };
  9781. var isText = function (node) {
  9782. return node.nodeType === TEXT;
  9783. };
  9784. var isElement$1 = function (node) {
  9785. return node.nodeType === ELEMENT;
  9786. };
  9787. var toLast = function (node) {
  9788. if (isText(node)) {
  9789. return point(node, node.data.length);
  9790. } else {
  9791. var children = node.childNodes;
  9792. return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length);
  9793. }
  9794. };
  9795. var toLeaf = function (node, offset) {
  9796. var children = node.childNodes;
  9797. if (children.length > 0 && offset < children.length) {
  9798. return toLeaf(children[offset], 0);
  9799. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9800. return toLast(children[children.length - 1]);
  9801. } else {
  9802. return point(node, offset);
  9803. }
  9804. };
  9805. var isPreviousCharContent = function (dom, leaf) {
  9806. return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  9807. return offset === 0 ? -1 : offset;
  9808. }, dom.getRoot()).filter(function (spot) {
  9809. var char = spot.container.data.charAt(spot.offset - 1);
  9810. return !isWhitespace(char);
  9811. }).isSome();
  9812. };
  9813. var isStartOfWord = function (dom) {
  9814. return function (rng) {
  9815. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9816. return !isPreviousCharContent(dom, leaf);
  9817. };
  9818. };
  9819. var getTriggerContext = function (dom, initRange, database) {
  9820. return findMap(database.triggerChars, function (ch) {
  9821. return getContext(dom, initRange, ch);
  9822. });
  9823. };
  9824. var lookup$2 = function (editor, getDatabase) {
  9825. var database = getDatabase();
  9826. var rng = editor.selection.getRng();
  9827. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9828. return lookupWithContext(editor, getDatabase, context);
  9829. });
  9830. };
  9831. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9832. if (fetchOptions === void 0) {
  9833. fetchOptions = {};
  9834. }
  9835. var database = getDatabase();
  9836. var rng = editor.selection.getRng();
  9837. var startText = rng.startContainer.nodeValue;
  9838. var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9839. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9840. return isStartOfWord(editor.dom);
  9841. })(context.range, startText, context.text);
  9842. });
  9843. if (autocompleters.length === 0) {
  9844. return Optional.none();
  9845. }
  9846. var lookupData = global$c.all(map$2(autocompleters, function (ac) {
  9847. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9848. return fetchResult.then(function (results) {
  9849. return {
  9850. matchText: context.text,
  9851. items: results,
  9852. columns: ac.columns,
  9853. onAction: ac.onAction,
  9854. highlightOn: ac.highlightOn
  9855. };
  9856. });
  9857. }));
  9858. return Optional.some({
  9859. lookupData: lookupData,
  9860. context: context
  9861. });
  9862. };
  9863. var separatorMenuItemSchema = objOf([
  9864. requiredString('type'),
  9865. optionString('text')
  9866. ]);
  9867. var createSeparatorMenuItem = function (spec) {
  9868. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9869. };
  9870. var autocompleterItemSchema = objOf([
  9871. defaulted('type', 'autocompleteitem'),
  9872. defaulted('active', false),
  9873. defaulted('disabled', false),
  9874. defaulted('meta', {}),
  9875. requiredString('value'),
  9876. optionString('text'),
  9877. optionString('icon')
  9878. ]);
  9879. var autocompleterSchema = objOf([
  9880. requiredString('type'),
  9881. requiredString('ch'),
  9882. defaultedNumber('minChars', 1),
  9883. defaulted('columns', 1),
  9884. defaultedNumber('maxResults', 10),
  9885. optionFunction('matches'),
  9886. requiredFunction('fetch'),
  9887. requiredFunction('onAction'),
  9888. defaultedArrayOf('highlightOn', [], string)
  9889. ]);
  9890. var createSeparatorItem = function (spec) {
  9891. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9892. };
  9893. var createAutocompleterItem = function (spec) {
  9894. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9895. };
  9896. var createAutocompleter = function (spec) {
  9897. return asRaw('Autocompleter', autocompleterSchema, spec);
  9898. };
  9899. var baseToolbarButtonFields = [
  9900. defaultedBoolean('disabled', false),
  9901. optionString('tooltip'),
  9902. optionString('icon'),
  9903. optionString('text'),
  9904. defaultedFunction('onSetup', function () {
  9905. return noop;
  9906. })
  9907. ];
  9908. var toolbarButtonSchema = objOf([
  9909. requiredString('type'),
  9910. requiredFunction('onAction')
  9911. ].concat(baseToolbarButtonFields));
  9912. var createToolbarButton = function (spec) {
  9913. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  9914. };
  9915. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  9916. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  9917. requiredString('type'),
  9918. requiredFunction('onAction')
  9919. ]));
  9920. var createToggleButton = function (spec) {
  9921. return asRaw('ToggleButton', toggleButtonSchema, spec);
  9922. };
  9923. var contextBarFields = [
  9924. defaultedFunction('predicate', never),
  9925. defaultedStringEnum('scope', 'node', [
  9926. 'node',
  9927. 'editor'
  9928. ]),
  9929. defaultedStringEnum('position', 'selection', [
  9930. 'node',
  9931. 'selection',
  9932. 'line'
  9933. ])
  9934. ];
  9935. var contextButtonFields = baseToolbarButtonFields.concat([
  9936. defaulted('type', 'contextformbutton'),
  9937. defaulted('primary', false),
  9938. requiredFunction('onAction'),
  9939. customField('original', identity$1)
  9940. ]);
  9941. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  9942. defaulted('type', 'contextformbutton'),
  9943. defaulted('primary', false),
  9944. requiredFunction('onAction'),
  9945. customField('original', identity$1)
  9946. ]);
  9947. var launchButtonFields = baseToolbarButtonFields.concat([defaulted('type', 'contextformbutton')]);
  9948. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted('type', 'contextformtogglebutton')]);
  9949. var toggleOrNormal = choose$1('type', {
  9950. contextformbutton: contextButtonFields,
  9951. contextformtogglebutton: contextToggleButtonFields
  9952. });
  9953. var contextFormSchema = objOf([
  9954. defaulted('type', 'contextform'),
  9955. defaultedFunction('initValue', constant$1('')),
  9956. optionString('label'),
  9957. requiredArrayOf('commands', toggleOrNormal),
  9958. optionOf('launch', choose$1('type', {
  9959. contextformbutton: launchButtonFields,
  9960. contextformtogglebutton: launchToggleButtonFields
  9961. }))
  9962. ].concat(contextBarFields));
  9963. var createContextForm = function (spec) {
  9964. return asRaw('ContextForm', contextFormSchema, spec);
  9965. };
  9966. var contextToolbarSchema = objOf([
  9967. defaulted('type', 'contexttoolbar'),
  9968. requiredString('items')
  9969. ].concat(contextBarFields));
  9970. var createContextToolbar = function (spec) {
  9971. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  9972. };
  9973. var stringArray = function (a) {
  9974. var all = {};
  9975. each$1(a, function (key) {
  9976. all[key] = {};
  9977. });
  9978. return keys(all);
  9979. };
  9980. var register$b = function (editor) {
  9981. var popups = editor.ui.registry.getAll().popups;
  9982. var dataset = map$1(popups, function (popup) {
  9983. return createAutocompleter(popup).fold(function (err) {
  9984. throw new Error(formatError(err));
  9985. }, identity$1);
  9986. });
  9987. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9988. return v.ch;
  9989. }));
  9990. var datasetValues = values(dataset);
  9991. var lookupByChar = function (ch) {
  9992. return filter$2(datasetValues, function (dv) {
  9993. return dv.ch === ch;
  9994. });
  9995. };
  9996. return {
  9997. dataset: dataset,
  9998. triggerChars: triggerChars,
  9999. lookupByChar: lookupByChar
  10000. };
  10001. };
  10002. var ItemResponse;
  10003. (function (ItemResponse) {
  10004. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  10005. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  10006. }(ItemResponse || (ItemResponse = {})));
  10007. var ItemResponse$1 = ItemResponse;
  10008. var navClass = 'tox-menu-nav__js';
  10009. var selectableClass = 'tox-collection__item';
  10010. var colorClass = 'tox-swatch';
  10011. var presetClasses = {
  10012. normal: navClass,
  10013. color: colorClass
  10014. };
  10015. var tickedClass = 'tox-collection__item--enabled';
  10016. var groupHeadingClass = 'tox-collection__group-heading';
  10017. var iconClass = 'tox-collection__item-icon';
  10018. var textClass = 'tox-collection__item-label';
  10019. var accessoryClass = 'tox-collection__item-accessory';
  10020. var caretClass = 'tox-collection__item-caret';
  10021. var checkmarkClass = 'tox-collection__item-checkmark';
  10022. var activeClass = 'tox-collection__item--active';
  10023. var containerClass = 'tox-collection__item-container';
  10024. var containerColumnClass = 'tox-collection__item-container--column';
  10025. var containerRowClass = 'tox-collection__item-container--row';
  10026. var containerAlignRightClass = 'tox-collection__item-container--align-right';
  10027. var containerAlignLeftClass = 'tox-collection__item-container--align-left';
  10028. var containerValignTopClass = 'tox-collection__item-container--valign-top';
  10029. var containerValignMiddleClass = 'tox-collection__item-container--valign-middle';
  10030. var containerValignBottomClass = 'tox-collection__item-container--valign-bottom';
  10031. var classForPreset = function (presets) {
  10032. return get$e(presetClasses, presets).getOr(navClass);
  10033. };
  10034. var forMenu = function (presets) {
  10035. if (presets === 'color') {
  10036. return 'tox-swatches';
  10037. } else {
  10038. return 'tox-menu';
  10039. }
  10040. };
  10041. var classes = function (presets) {
  10042. return {
  10043. backgroundMenu: 'tox-background-menu',
  10044. selectedMenu: 'tox-selected-menu',
  10045. selectedItem: 'tox-collection__item--active',
  10046. hasIcons: 'tox-menu--has-icons',
  10047. menu: forMenu(presets),
  10048. tieredMenu: 'tox-tiered-menu'
  10049. };
  10050. };
  10051. var markers = function (presets) {
  10052. var menuClasses = classes(presets);
  10053. return {
  10054. backgroundMenu: menuClasses.backgroundMenu,
  10055. selectedMenu: menuClasses.selectedMenu,
  10056. menu: menuClasses.menu,
  10057. selectedItem: menuClasses.selectedItem,
  10058. item: classForPreset(presets)
  10059. };
  10060. };
  10061. var dom$1 = function (hasIcons, columns, presets) {
  10062. var menuClasses = classes(presets);
  10063. return {
  10064. tag: 'div',
  10065. classes: flatten([
  10066. [
  10067. menuClasses.menu,
  10068. 'tox-menu-' + columns + '-column'
  10069. ],
  10070. hasIcons ? [menuClasses.hasIcons] : []
  10071. ])
  10072. };
  10073. };
  10074. var components = [Menu.parts.items({})];
  10075. var part = function (hasIcons, columns, presets) {
  10076. var menuClasses = classes(presets);
  10077. var d = {
  10078. tag: 'div',
  10079. classes: flatten([[menuClasses.tieredMenu]])
  10080. };
  10081. return {
  10082. dom: d,
  10083. markers: markers(presets)
  10084. };
  10085. };
  10086. var chunk = function (rowDom, numColumns) {
  10087. return function (items) {
  10088. var chunks = chunk$1(items, numColumns);
  10089. return map$2(chunks, function (c) {
  10090. return {
  10091. dom: rowDom,
  10092. components: c
  10093. };
  10094. });
  10095. };
  10096. };
  10097. var forSwatch = function (columns) {
  10098. return {
  10099. dom: {
  10100. tag: 'div',
  10101. classes: [
  10102. 'tox-menu',
  10103. 'tox-swatches-menu'
  10104. ]
  10105. },
  10106. components: [{
  10107. dom: {
  10108. tag: 'div',
  10109. classes: ['tox-swatches']
  10110. },
  10111. components: [Menu.parts.items({
  10112. preprocess: columns !== 'auto' ? chunk({
  10113. tag: 'div',
  10114. classes: ['tox-swatches__row']
  10115. }, columns) : identity$1
  10116. })]
  10117. }]
  10118. };
  10119. };
  10120. var forToolbar = function (columns) {
  10121. return {
  10122. dom: {
  10123. tag: 'div',
  10124. classes: [
  10125. 'tox-menu',
  10126. 'tox-collection',
  10127. 'tox-collection--toolbar',
  10128. 'tox-collection--toolbar-lg'
  10129. ]
  10130. },
  10131. components: [Menu.parts.items({
  10132. preprocess: chunk({
  10133. tag: 'div',
  10134. classes: ['tox-collection__group']
  10135. }, columns)
  10136. })]
  10137. };
  10138. };
  10139. var preprocessCollection = function (items, isSeparator) {
  10140. var allSplits = [];
  10141. var currentSplit = [];
  10142. each$1(items, function (item, i) {
  10143. if (isSeparator(item, i)) {
  10144. if (currentSplit.length > 0) {
  10145. allSplits.push(currentSplit);
  10146. }
  10147. currentSplit = [];
  10148. if (has$2(item.dom, 'innerHtml')) {
  10149. currentSplit.push(item);
  10150. }
  10151. } else {
  10152. currentSplit.push(item);
  10153. }
  10154. });
  10155. if (currentSplit.length > 0) {
  10156. allSplits.push(currentSplit);
  10157. }
  10158. return map$2(allSplits, function (s) {
  10159. return {
  10160. dom: {
  10161. tag: 'div',
  10162. classes: ['tox-collection__group']
  10163. },
  10164. components: s
  10165. };
  10166. });
  10167. };
  10168. var forCollection = function (columns, initItems, _hasIcons) {
  10169. return {
  10170. dom: {
  10171. tag: 'div',
  10172. classes: [
  10173. 'tox-menu',
  10174. 'tox-collection'
  10175. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  10176. },
  10177. components: [Menu.parts.items({
  10178. preprocess: function (items) {
  10179. if (columns !== 'auto' && columns > 1) {
  10180. return chunk({
  10181. tag: 'div',
  10182. classes: ['tox-collection__group']
  10183. }, columns)(items);
  10184. } else {
  10185. return preprocessCollection(items, function (_item, i) {
  10186. return initItems[i].type === 'separator';
  10187. });
  10188. }
  10189. }
  10190. })]
  10191. };
  10192. };
  10193. var forHorizontalCollection = function (initItems, _hasIcons) {
  10194. return {
  10195. dom: {
  10196. tag: 'div',
  10197. classes: [
  10198. 'tox-collection',
  10199. 'tox-collection--horizontal'
  10200. ]
  10201. },
  10202. components: [Menu.parts.items({
  10203. preprocess: function (items) {
  10204. return preprocessCollection(items, function (_item, i) {
  10205. return initItems[i].type === 'separator';
  10206. });
  10207. }
  10208. })]
  10209. };
  10210. };
  10211. var menuHasIcons = function (xs) {
  10212. return exists(xs, function (item) {
  10213. return 'icon' in item && item.icon !== undefined;
  10214. });
  10215. };
  10216. var handleError = function (error) {
  10217. console.error(formatError(error));
  10218. console.log(error);
  10219. return Optional.none();
  10220. };
  10221. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  10222. var structure = forHorizontalCollection(items);
  10223. return {
  10224. value: value,
  10225. dom: structure.dom,
  10226. components: structure.components,
  10227. items: items
  10228. };
  10229. };
  10230. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  10231. if (presets === 'color') {
  10232. var structure = forSwatch(columns);
  10233. return {
  10234. value: value,
  10235. dom: structure.dom,
  10236. components: structure.components,
  10237. items: items
  10238. };
  10239. }
  10240. if (presets === 'normal' && columns === 'auto') {
  10241. var structure = forCollection(columns, items);
  10242. return {
  10243. value: value,
  10244. dom: structure.dom,
  10245. components: structure.components,
  10246. items: items
  10247. };
  10248. }
  10249. if (presets === 'normal' && columns === 1) {
  10250. var structure = forCollection(1, items);
  10251. return {
  10252. value: value,
  10253. dom: structure.dom,
  10254. components: structure.components,
  10255. items: items
  10256. };
  10257. }
  10258. if (presets === 'normal') {
  10259. var structure = forCollection(columns, items);
  10260. return {
  10261. value: value,
  10262. dom: structure.dom,
  10263. components: structure.components,
  10264. items: items
  10265. };
  10266. }
  10267. if (presets === 'listpreview' && columns !== 'auto') {
  10268. var structure = forToolbar(columns);
  10269. return {
  10270. value: value,
  10271. dom: structure.dom,
  10272. components: structure.components,
  10273. items: items
  10274. };
  10275. }
  10276. return {
  10277. value: value,
  10278. dom: dom$1(hasIcons, columns, presets),
  10279. components: components,
  10280. items: items
  10281. };
  10282. };
  10283. var cardImageFields = [
  10284. requiredString('type'),
  10285. requiredString('src'),
  10286. optionString('alt'),
  10287. defaultedArrayOf('classes', [], string)
  10288. ];
  10289. var cardImageSchema = objOf(cardImageFields);
  10290. var cardTextFields = [
  10291. requiredString('type'),
  10292. requiredString('text'),
  10293. optionString('name'),
  10294. defaultedArrayOf('classes', ['tox-collection__item-label'], string)
  10295. ];
  10296. var cardTextSchema = objOf(cardTextFields);
  10297. var itemSchema$1 = valueThunk(function () {
  10298. return choose$2('type', {
  10299. cardimage: cardImageSchema,
  10300. cardtext: cardTextSchema,
  10301. cardcontainer: cardContainerSchema
  10302. });
  10303. });
  10304. var cardContainerSchema = objOf([
  10305. requiredString('type'),
  10306. defaultedString('direction', 'horizontal'),
  10307. defaultedString('align', 'left'),
  10308. defaultedString('valign', 'middle'),
  10309. requiredArrayOf('items', itemSchema$1)
  10310. ]);
  10311. var commonMenuItemFields = [
  10312. defaultedBoolean('disabled', false),
  10313. optionString('text'),
  10314. optionString('shortcut'),
  10315. field$1('value', 'value', defaultedThunk(function () {
  10316. return generate$6('menuitem-value');
  10317. }), anyValue()),
  10318. defaulted('meta', {})
  10319. ];
  10320. var cardMenuItemSchema = objOf([
  10321. requiredString('type'),
  10322. optionString('label'),
  10323. requiredArrayOf('items', itemSchema$1),
  10324. defaultedFunction('onSetup', function () {
  10325. return noop;
  10326. }),
  10327. defaultedFunction('onAction', noop)
  10328. ].concat(commonMenuItemFields));
  10329. var createCardMenuItem = function (spec) {
  10330. return asRaw('cardmenuitem', cardMenuItemSchema, spec);
  10331. };
  10332. var choiceMenuItemSchema = objOf([
  10333. requiredString('type'),
  10334. defaultedBoolean('active', false),
  10335. optionString('icon')
  10336. ].concat(commonMenuItemFields));
  10337. var createChoiceMenuItem = function (spec) {
  10338. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  10339. };
  10340. var baseFields = [
  10341. requiredString('type'),
  10342. requiredString('fancytype'),
  10343. defaultedFunction('onAction', noop)
  10344. ];
  10345. var insertTableFields = [defaulted('initData', {})].concat(baseFields);
  10346. var colorSwatchFields = [defaultedObjOf('initData', {}, [
  10347. defaultedBoolean('allowCustomColors', true),
  10348. optionArrayOf('colors', anyValue())
  10349. ])].concat(baseFields);
  10350. var fancyMenuItemSchema = choose$1('fancytype', {
  10351. inserttable: insertTableFields,
  10352. colorswatch: colorSwatchFields
  10353. });
  10354. var createFancyMenuItem = function (spec) {
  10355. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  10356. };
  10357. var menuItemSchema = objOf([
  10358. requiredString('type'),
  10359. defaultedFunction('onSetup', function () {
  10360. return noop;
  10361. }),
  10362. defaultedFunction('onAction', noop),
  10363. optionString('icon')
  10364. ].concat(commonMenuItemFields));
  10365. var createMenuItem = function (spec) {
  10366. return asRaw('menuitem', menuItemSchema, spec);
  10367. };
  10368. var nestedMenuItemSchema = objOf([
  10369. requiredString('type'),
  10370. requiredFunction('getSubmenuItems'),
  10371. defaultedFunction('onSetup', function () {
  10372. return noop;
  10373. }),
  10374. optionString('icon')
  10375. ].concat(commonMenuItemFields));
  10376. var createNestedMenuItem = function (spec) {
  10377. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  10378. };
  10379. var toggleMenuItemSchema = objOf([
  10380. requiredString('type'),
  10381. optionString('icon'),
  10382. defaultedBoolean('active', false),
  10383. defaultedFunction('onSetup', function () {
  10384. return noop;
  10385. }),
  10386. requiredFunction('onAction')
  10387. ].concat(commonMenuItemFields));
  10388. var createToggleMenuItem = function (spec) {
  10389. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  10390. };
  10391. var detectSize = function (comp, margin, selectorClass) {
  10392. var descendants$1 = descendants(comp.element, '.' + selectorClass);
  10393. if (descendants$1.length > 0) {
  10394. var columnLength = findIndex$1(descendants$1, function (c) {
  10395. var thisTop = c.dom.getBoundingClientRect().top;
  10396. var cTop = descendants$1[0].dom.getBoundingClientRect().top;
  10397. return Math.abs(thisTop - cTop) > margin;
  10398. }).getOr(descendants$1.length);
  10399. return Optional.some({
  10400. numColumns: columnLength,
  10401. numRows: Math.ceil(descendants$1.length / columnLength)
  10402. });
  10403. } else {
  10404. return Optional.none();
  10405. }
  10406. };
  10407. var namedEvents = function (name, handlers) {
  10408. return derive$1([config(name, handlers)]);
  10409. };
  10410. var unnamedEvents = function (handlers) {
  10411. return namedEvents(generate$6('unnamed-events'), handlers);
  10412. };
  10413. var SimpleBehaviours = {
  10414. namedEvents: namedEvents,
  10415. unnamedEvents: unnamedEvents
  10416. };
  10417. var ExclusivityChannel = generate$6('tooltip.exclusive');
  10418. var ShowTooltipEvent = generate$6('tooltip.show');
  10419. var HideTooltipEvent = generate$6('tooltip.hide');
  10420. var hideAllExclusive = function (component, _tConfig, _tState) {
  10421. component.getSystem().broadcastOn([ExclusivityChannel], {});
  10422. };
  10423. var setComponents = function (component, tConfig, tState, specs) {
  10424. tState.getTooltip().each(function (tooltip) {
  10425. if (tooltip.getSystem().isConnected()) {
  10426. Replacing.set(tooltip, specs);
  10427. }
  10428. });
  10429. };
  10430. var TooltippingApis = /*#__PURE__*/Object.freeze({
  10431. __proto__: null,
  10432. hideAllExclusive: hideAllExclusive,
  10433. setComponents: setComponents
  10434. });
  10435. var events$9 = function (tooltipConfig, state) {
  10436. var hide = function (comp) {
  10437. state.getTooltip().each(function (p) {
  10438. detach(p);
  10439. tooltipConfig.onHide(comp, p);
  10440. state.clearTooltip();
  10441. });
  10442. state.clearTimer();
  10443. };
  10444. var show = function (comp) {
  10445. if (!state.isShowing()) {
  10446. hideAllExclusive(comp);
  10447. var sink = tooltipConfig.lazySink(comp).getOrDie();
  10448. var popup = comp.getSystem().build({
  10449. dom: tooltipConfig.tooltipDom,
  10450. components: tooltipConfig.tooltipComponents,
  10451. events: derive$2(tooltipConfig.mode === 'normal' ? [
  10452. run$1(mouseover(), function (_) {
  10453. emit(comp, ShowTooltipEvent);
  10454. }),
  10455. run$1(mouseout(), function (_) {
  10456. emit(comp, HideTooltipEvent);
  10457. })
  10458. ] : []),
  10459. behaviours: derive$1([Replacing.config({})])
  10460. });
  10461. state.setTooltip(popup);
  10462. attach(sink, popup);
  10463. tooltipConfig.onShow(comp, popup);
  10464. Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) });
  10465. }
  10466. };
  10467. return derive$2(flatten([
  10468. [
  10469. run$1(ShowTooltipEvent, function (comp) {
  10470. state.resetTimer(function () {
  10471. show(comp);
  10472. }, tooltipConfig.delay);
  10473. }),
  10474. run$1(HideTooltipEvent, function (comp) {
  10475. state.resetTimer(function () {
  10476. hide(comp);
  10477. }, tooltipConfig.delay);
  10478. }),
  10479. run$1(receive(), function (comp, message) {
  10480. var receivingData = message;
  10481. if (!receivingData.universal) {
  10482. if (contains$2(receivingData.channels, ExclusivityChannel)) {
  10483. hide(comp);
  10484. }
  10485. }
  10486. }),
  10487. runOnDetached(function (comp) {
  10488. hide(comp);
  10489. })
  10490. ],
  10491. tooltipConfig.mode === 'normal' ? [
  10492. run$1(focusin(), function (comp) {
  10493. emit(comp, ShowTooltipEvent);
  10494. }),
  10495. run$1(postBlur(), function (comp) {
  10496. emit(comp, HideTooltipEvent);
  10497. }),
  10498. run$1(mouseover(), function (comp) {
  10499. emit(comp, ShowTooltipEvent);
  10500. }),
  10501. run$1(mouseout(), function (comp) {
  10502. emit(comp, HideTooltipEvent);
  10503. })
  10504. ] : [
  10505. run$1(highlight$1(), function (comp, _se) {
  10506. emit(comp, ShowTooltipEvent);
  10507. }),
  10508. run$1(dehighlight$1(), function (comp) {
  10509. emit(comp, HideTooltipEvent);
  10510. })
  10511. ]
  10512. ]));
  10513. };
  10514. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  10515. __proto__: null,
  10516. events: events$9
  10517. });
  10518. var TooltippingSchema = [
  10519. required$1('lazySink'),
  10520. required$1('tooltipDom'),
  10521. defaulted('exclusive', true),
  10522. defaulted('tooltipComponents', []),
  10523. defaulted('delay', 300),
  10524. defaultedStringEnum('mode', 'normal', [
  10525. 'normal',
  10526. 'follow-highlight'
  10527. ]),
  10528. defaulted('anchor', function (comp) {
  10529. return {
  10530. type: 'hotspot',
  10531. hotspot: comp,
  10532. layouts: {
  10533. onLtr: constant$1([
  10534. south$2,
  10535. north$2,
  10536. southeast$2,
  10537. northeast$2,
  10538. southwest$2,
  10539. northwest$2
  10540. ]),
  10541. onRtl: constant$1([
  10542. south$2,
  10543. north$2,
  10544. southeast$2,
  10545. northeast$2,
  10546. southwest$2,
  10547. northwest$2
  10548. ])
  10549. }
  10550. };
  10551. }),
  10552. onHandler('onHide'),
  10553. onHandler('onShow')
  10554. ];
  10555. var init$b = function () {
  10556. var timer = value$1();
  10557. var popup = value$1();
  10558. var clearTimer = function () {
  10559. timer.on(clearTimeout);
  10560. };
  10561. var resetTimer = function (f, delay) {
  10562. clearTimer();
  10563. timer.set(setTimeout(f, delay));
  10564. };
  10565. var readState = constant$1('not-implemented');
  10566. return nu$8({
  10567. getTooltip: popup.get,
  10568. isShowing: popup.isSet,
  10569. setTooltip: popup.set,
  10570. clearTooltip: popup.clear,
  10571. clearTimer: clearTimer,
  10572. resetTimer: resetTimer,
  10573. readState: readState
  10574. });
  10575. };
  10576. var TooltippingState = /*#__PURE__*/Object.freeze({
  10577. __proto__: null,
  10578. init: init$b
  10579. });
  10580. var Tooltipping = create$7({
  10581. fields: TooltippingSchema,
  10582. name: 'tooltipping',
  10583. active: ActiveTooltipping,
  10584. state: TooltippingState,
  10585. apis: TooltippingApis
  10586. });
  10587. var escape = function (text) {
  10588. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10589. };
  10590. var global$b = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  10591. var global$a = tinymce.util.Tools.resolve('tinymce.EditorManager');
  10592. var getSkinUrl = function (editor) {
  10593. var skin = editor.getParam('skin');
  10594. var skinUrl = editor.getParam('skin_url');
  10595. if (skin !== false) {
  10596. var skinName = skin ? skin : 'oxide';
  10597. if (skinUrl) {
  10598. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  10599. } else {
  10600. skinUrl = global$a.baseURL + '/skins/ui/' + skinName;
  10601. }
  10602. }
  10603. return skinUrl;
  10604. };
  10605. var isReadOnly = function (editor) {
  10606. return editor.getParam('readonly', false, 'boolean');
  10607. };
  10608. var isSkinDisabled = function (editor) {
  10609. return editor.getParam('skin') === false;
  10610. };
  10611. var getHeightSetting = function (editor) {
  10612. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  10613. };
  10614. var getWidthSetting = function (editor) {
  10615. return editor.getParam('width', global$b.DOM.getStyle(editor.getElement(), 'width'));
  10616. };
  10617. var getMinWidthSetting = function (editor) {
  10618. return Optional.from(editor.getParam('min_width')).filter(isNumber);
  10619. };
  10620. var getMinHeightSetting = function (editor) {
  10621. return Optional.from(editor.getParam('min_height')).filter(isNumber);
  10622. };
  10623. var getMaxWidthSetting = function (editor) {
  10624. return Optional.from(editor.getParam('max_width')).filter(isNumber);
  10625. };
  10626. var getMaxHeightSetting = function (editor) {
  10627. return Optional.from(editor.getParam('max_height')).filter(isNumber);
  10628. };
  10629. var getUserStyleFormats = function (editor) {
  10630. return Optional.from(editor.getParam('style_formats')).filter(isArray);
  10631. };
  10632. var isMergeStyleFormats = function (editor) {
  10633. return editor.getParam('style_formats_merge', false, 'boolean');
  10634. };
  10635. var getLineHeightFormats = function (editor) {
  10636. return editor.getParam('lineheight_formats', '1 1.1 1.2 1.3 1.4 1.5 2', 'string').split(' ');
  10637. };
  10638. var getContentLanguages = function (editor) {
  10639. return editor.getParam('content_langs', undefined, 'array');
  10640. };
  10641. var getRemovedMenuItems = function (editor) {
  10642. return editor.getParam('removed_menuitems', '');
  10643. };
  10644. var isMenubarEnabled = function (editor) {
  10645. return editor.getParam('menubar', true, 'boolean') !== false;
  10646. };
  10647. var isToolbarEnabled = function (editor) {
  10648. var toolbar = editor.getParam('toolbar', true);
  10649. var isToolbarTrue = toolbar === true;
  10650. var isToolbarString = isString(toolbar);
  10651. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  10652. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  10653. };
  10654. var getMultipleToolbarsSetting = function (editor) {
  10655. var toolbars = range$2(9, function (num) {
  10656. return editor.getParam('toolbar' + (num + 1), false, 'string');
  10657. });
  10658. var toolbarArray = filter$2(toolbars, function (toolbar) {
  10659. return typeof toolbar === 'string';
  10660. });
  10661. return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none();
  10662. };
  10663. var isMultipleToolbars = function (editor) {
  10664. return getMultipleToolbarsSetting(editor).fold(function () {
  10665. var toolbar = editor.getParam('toolbar', [], 'string[]');
  10666. return toolbar.length > 0;
  10667. }, always);
  10668. };
  10669. var ToolbarMode;
  10670. (function (ToolbarMode) {
  10671. ToolbarMode['default'] = 'wrap';
  10672. ToolbarMode['floating'] = 'floating';
  10673. ToolbarMode['sliding'] = 'sliding';
  10674. ToolbarMode['scrolling'] = 'scrolling';
  10675. }(ToolbarMode || (ToolbarMode = {})));
  10676. var getToolbarMode = function (editor) {
  10677. return editor.getParam('toolbar_mode', '', 'string');
  10678. };
  10679. var ToolbarLocation;
  10680. (function (ToolbarLocation) {
  10681. ToolbarLocation['auto'] = 'auto';
  10682. ToolbarLocation['top'] = 'top';
  10683. ToolbarLocation['bottom'] = 'bottom';
  10684. }(ToolbarLocation || (ToolbarLocation = {})));
  10685. var getToolbarGroups = function (editor) {
  10686. return editor.getParam('toolbar_groups', {}, 'object');
  10687. };
  10688. var getToolbarLocation = function (editor) {
  10689. return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string');
  10690. };
  10691. var isToolbarLocationBottom = function (editor) {
  10692. return getToolbarLocation(editor) === ToolbarLocation.bottom;
  10693. };
  10694. var fixedContainerSelector = function (editor) {
  10695. return editor.getParam('fixed_toolbar_container', '', 'string');
  10696. };
  10697. var fixedToolbarContainerTarget = function (editor) {
  10698. return editor.getParam('fixed_toolbar_container_target');
  10699. };
  10700. var isToolbarPersist = function (editor) {
  10701. return editor.getParam('toolbar_persist', false, 'boolean');
  10702. };
  10703. var fixedContainerTarget = function (editor) {
  10704. if (!editor.inline) {
  10705. return Optional.none();
  10706. }
  10707. var selector = fixedContainerSelector(editor);
  10708. if (selector.length > 0) {
  10709. return descendant(body(), selector);
  10710. }
  10711. var element = fixedToolbarContainerTarget(editor);
  10712. if (isNonNullable(element)) {
  10713. return Optional.some(SugarElement.fromDom(element));
  10714. }
  10715. return Optional.none();
  10716. };
  10717. var useFixedContainer = function (editor) {
  10718. return editor.inline && fixedContainerTarget(editor).isSome();
  10719. };
  10720. var getUiContainer = function (editor) {
  10721. var fixedContainer = fixedContainerTarget(editor);
  10722. return fixedContainer.getOrThunk(function () {
  10723. return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement())));
  10724. });
  10725. };
  10726. var isDistractionFree = function (editor) {
  10727. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  10728. };
  10729. var isStickyToolbar = function (editor) {
  10730. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  10731. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  10732. };
  10733. var getStickyToolbarOffset = function (editor) {
  10734. return editor.getParam('toolbar_sticky_offset', 0, 'number');
  10735. };
  10736. var isDraggableModal$1 = function (editor) {
  10737. return editor.getParam('draggable_modal', false, 'boolean');
  10738. };
  10739. var getMenus = function (editor) {
  10740. var menu = editor.getParam('menu');
  10741. if (menu) {
  10742. return map$1(menu, function (menu) {
  10743. return __assign(__assign({}, menu), { items: menu.items });
  10744. });
  10745. } else {
  10746. return {};
  10747. }
  10748. };
  10749. var getMenubar = function (editor) {
  10750. return editor.getParam('menubar');
  10751. };
  10752. var getToolbar = function (editor) {
  10753. return editor.getParam('toolbar', true);
  10754. };
  10755. var getFilePickerCallback = function (editor) {
  10756. return editor.getParam('file_picker_callback');
  10757. };
  10758. var getFilePickerTypes = function (editor) {
  10759. return editor.getParam('file_picker_types');
  10760. };
  10761. var getFileBrowserCallbackTypes = function (editor) {
  10762. return editor.getParam('file_browser_callback_types');
  10763. };
  10764. var noTypeaheadUrls = function (editor) {
  10765. return editor.getParam('typeahead_urls') === false;
  10766. };
  10767. var getAnchorTop = function (editor) {
  10768. return editor.getParam('anchor_top', '#top');
  10769. };
  10770. var getAnchorBottom = function (editor) {
  10771. return editor.getParam('anchor_bottom', '#bottom');
  10772. };
  10773. var getFilePickerValidatorHandler = function (editor) {
  10774. var handler = editor.getParam('file_picker_validator_handler', undefined, 'function');
  10775. if (handler === undefined) {
  10776. return editor.getParam('filepicker_validator_handler', undefined, 'function');
  10777. } else {
  10778. return handler;
  10779. }
  10780. };
  10781. var ReadOnlyChannel = 'silver.readonly';
  10782. var ReadOnlyDataSchema = objOf([requiredBoolean('readonly')]);
  10783. var broadcastReadonly = function (uiComponents, readonly) {
  10784. var outerContainer = uiComponents.outerContainer;
  10785. var target = outerContainer.element;
  10786. if (readonly) {
  10787. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  10788. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  10789. }
  10790. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10791. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10792. };
  10793. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  10794. editor.on('init', function () {
  10795. if (editor.mode.isReadOnly()) {
  10796. broadcastReadonly(uiComponents, true);
  10797. }
  10798. });
  10799. editor.on('SwitchMode', function () {
  10800. return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
  10801. });
  10802. if (isReadOnly(editor)) {
  10803. editor.setMode('readonly');
  10804. }
  10805. };
  10806. var receivingConfig = function () {
  10807. var _a;
  10808. return Receiving.config({
  10809. channels: (_a = {}, _a[ReadOnlyChannel] = {
  10810. schema: ReadOnlyDataSchema,
  10811. onReceive: function (comp, data) {
  10812. Disabling.set(comp, data.readonly);
  10813. }
  10814. }, _a)
  10815. });
  10816. };
  10817. var item = function (disabled) {
  10818. return Disabling.config({
  10819. disabled: disabled,
  10820. disableClass: 'tox-collection__item--state-disabled'
  10821. });
  10822. };
  10823. var button = function (disabled) {
  10824. return Disabling.config({ disabled: disabled });
  10825. };
  10826. var splitButton = function (disabled) {
  10827. return Disabling.config({
  10828. disabled: disabled,
  10829. disableClass: 'tox-tbtn--disabled'
  10830. });
  10831. };
  10832. var toolbarButton = function (disabled) {
  10833. return Disabling.config({
  10834. disabled: disabled,
  10835. disableClass: 'tox-tbtn--disabled',
  10836. useNative: false
  10837. });
  10838. };
  10839. var DisablingConfigs = {
  10840. item: item,
  10841. button: button,
  10842. splitButton: splitButton,
  10843. toolbarButton: toolbarButton
  10844. };
  10845. var runWithApi = function (info, comp) {
  10846. var api = info.getApi(comp);
  10847. return function (f) {
  10848. f(api);
  10849. };
  10850. };
  10851. var onControlAttached = function (info, editorOffCell) {
  10852. return runOnAttached(function (comp) {
  10853. var run = runWithApi(info, comp);
  10854. run(function (api) {
  10855. var onDestroy = info.onSetup(api);
  10856. if (isFunction(onDestroy)) {
  10857. editorOffCell.set(onDestroy);
  10858. }
  10859. });
  10860. });
  10861. };
  10862. var onControlDetached = function (getApi, editorOffCell) {
  10863. return runOnDetached(function (comp) {
  10864. return runWithApi(getApi, comp)(editorOffCell.get());
  10865. });
  10866. };
  10867. var _a$1;
  10868. var onMenuItemExecute = function (info, itemResponse) {
  10869. return runOnExecute$1(function (comp, simulatedEvent) {
  10870. runWithApi(info, comp)(info.onAction);
  10871. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10872. emit(comp, sandboxClose());
  10873. simulatedEvent.stop();
  10874. }
  10875. });
  10876. };
  10877. var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [
  10878. 'disabling',
  10879. 'alloy.base.behaviour',
  10880. 'toggling',
  10881. 'item-events'
  10882. ], _a$1);
  10883. var componentRenderPipeline = cat;
  10884. var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) {
  10885. var editorOffCell = Cell(noop);
  10886. return {
  10887. type: 'item',
  10888. dom: structure.dom,
  10889. components: componentRenderPipeline(structure.optComponents),
  10890. data: spec.data,
  10891. eventOrder: menuItemEventOrder,
  10892. hasSubmenu: spec.triggersSubmenu,
  10893. itemBehaviours: derive$1([
  10894. config('item-events', [
  10895. onMenuItemExecute(spec, itemResponse),
  10896. onControlAttached(spec, editorOffCell),
  10897. onControlDetached(spec, editorOffCell)
  10898. ]),
  10899. DisablingConfigs.item(function () {
  10900. return spec.disabled || providersbackstage.isDisabled();
  10901. }),
  10902. receivingConfig(),
  10903. Replacing.config({})
  10904. ].concat(spec.itemBehaviours))
  10905. };
  10906. };
  10907. var buildData = function (source) {
  10908. return {
  10909. value: source.value,
  10910. meta: __assign({ text: source.text.getOr('') }, source.meta)
  10911. };
  10912. };
  10913. var global$9 = tinymce.util.Tools.resolve('tinymce.Env');
  10914. var convertText = function (source) {
  10915. var mac = {
  10916. alt: '&#x2325;',
  10917. ctrl: '&#x2303;',
  10918. shift: '&#x21E7;',
  10919. meta: '&#x2318;',
  10920. access: '&#x2303;&#x2325;'
  10921. };
  10922. var other = {
  10923. meta: 'Ctrl',
  10924. access: 'Shift+Alt'
  10925. };
  10926. var replace = global$9.mac ? mac : other;
  10927. var shortcut = source.split('+');
  10928. var updated = map$2(shortcut, function (segment) {
  10929. var search = segment.toLowerCase().trim();
  10930. return has$2(replace, search) ? replace[search] : segment;
  10931. });
  10932. return global$9.mac ? updated.join('') : updated.join('+');
  10933. };
  10934. var renderIcon$1 = function (name, icons, classes) {
  10935. if (classes === void 0) {
  10936. classes = [iconClass];
  10937. }
  10938. return render$3(name, {
  10939. tag: 'div',
  10940. classes: classes
  10941. }, icons);
  10942. };
  10943. var renderText = function (text$1) {
  10944. return {
  10945. dom: {
  10946. tag: 'div',
  10947. classes: [textClass]
  10948. },
  10949. components: [text(global$e.translate(text$1))]
  10950. };
  10951. };
  10952. var renderHtml = function (html, classes) {
  10953. return {
  10954. dom: {
  10955. tag: 'div',
  10956. classes: classes,
  10957. innerHtml: html
  10958. }
  10959. };
  10960. };
  10961. var renderStyledText = function (style, text$1) {
  10962. return {
  10963. dom: {
  10964. tag: 'div',
  10965. classes: [textClass]
  10966. },
  10967. components: [{
  10968. dom: {
  10969. tag: style.tag,
  10970. styles: style.styles
  10971. },
  10972. components: [text(global$e.translate(text$1))]
  10973. }]
  10974. };
  10975. };
  10976. var renderShortcut = function (shortcut) {
  10977. return {
  10978. dom: {
  10979. tag: 'div',
  10980. classes: [accessoryClass],
  10981. innerHtml: convertText(shortcut)
  10982. }
  10983. };
  10984. };
  10985. var renderCheckmark = function (icons) {
  10986. return renderIcon$1('checkmark', icons, [checkmarkClass]);
  10987. };
  10988. var renderSubmenuCaret = function (icons) {
  10989. return renderIcon$1('chevron-right', icons, [caretClass]);
  10990. };
  10991. var renderDownwardsCaret = function (icons) {
  10992. return renderIcon$1('chevron-down', icons, [caretClass]);
  10993. };
  10994. var renderContainer = function (container, components) {
  10995. var directionClass = container.direction === 'vertical' ? containerColumnClass : containerRowClass;
  10996. var alignClass = container.align === 'left' ? containerAlignLeftClass : containerAlignRightClass;
  10997. var getValignClass = function () {
  10998. switch (container.valign) {
  10999. case 'top':
  11000. return containerValignTopClass;
  11001. case 'middle':
  11002. return containerValignMiddleClass;
  11003. case 'bottom':
  11004. return containerValignBottomClass;
  11005. }
  11006. };
  11007. return {
  11008. dom: {
  11009. tag: 'div',
  11010. classes: [
  11011. containerClass,
  11012. directionClass,
  11013. alignClass,
  11014. getValignClass()
  11015. ]
  11016. },
  11017. components: components
  11018. };
  11019. };
  11020. var renderImage = function (src, classes, alt) {
  11021. return {
  11022. dom: {
  11023. tag: 'img',
  11024. classes: classes,
  11025. attributes: {
  11026. src: src,
  11027. alt: alt.getOr('')
  11028. }
  11029. }
  11030. };
  11031. };
  11032. var renderColorStructure = function (item, providerBackstage, fallbackIcon) {
  11033. var colorPickerCommand = 'custom';
  11034. var removeColorCommand = 'remove';
  11035. var itemText = item.ariaLabel;
  11036. var itemValue = item.value;
  11037. var iconSvg = item.iconContent.map(function (name) {
  11038. return getOr(name, providerBackstage.icons, fallbackIcon);
  11039. });
  11040. var getDom = function () {
  11041. var common = colorClass;
  11042. var icon = iconSvg.getOr('');
  11043. var attributes = itemText.map(function (text) {
  11044. return { title: providerBackstage.translate(text) };
  11045. }).getOr({});
  11046. var baseDom = {
  11047. tag: 'div',
  11048. attributes: attributes,
  11049. classes: [common]
  11050. };
  11051. if (itemValue === colorPickerCommand) {
  11052. return __assign(__assign({}, baseDom), {
  11053. tag: 'button',
  11054. classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatches__picker-btn'], false),
  11055. innerHtml: icon
  11056. });
  11057. } else if (itemValue === removeColorCommand) {
  11058. return __assign(__assign({}, baseDom), {
  11059. classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatch--remove'], false),
  11060. innerHtml: icon
  11061. });
  11062. } else {
  11063. return __assign(__assign({}, baseDom), {
  11064. attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  11065. styles: { 'background-color': itemValue }
  11066. });
  11067. }
  11068. };
  11069. return {
  11070. dom: getDom(),
  11071. optComponents: []
  11072. };
  11073. };
  11074. var renderItemDomStructure = function (ariaLabel) {
  11075. var domTitle = ariaLabel.map(function (label) {
  11076. return { attributes: { title: global$e.translate(label) } };
  11077. }).getOr({});
  11078. return __assign({
  11079. tag: 'div',
  11080. classes: [
  11081. navClass,
  11082. selectableClass
  11083. ]
  11084. }, domTitle);
  11085. };
  11086. var renderNormalItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  11087. var iconSpec = {
  11088. tag: 'div',
  11089. classes: [iconClass]
  11090. };
  11091. var renderIcon = function (iconName) {
  11092. return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon);
  11093. };
  11094. var renderEmptyIcon = function () {
  11095. return Optional.some({ dom: iconSpec });
  11096. };
  11097. var leftIcon = renderIcons ? info.iconContent.map(renderIcon).orThunk(renderEmptyIcon) : Optional.none();
  11098. var checkmark = info.checkMark;
  11099. var textRender = Optional.from(info.meta).fold(function () {
  11100. return renderText;
  11101. }, function (meta) {
  11102. return has$2(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  11103. });
  11104. var content = info.htmlContent.fold(function () {
  11105. return info.textContent.map(textRender);
  11106. }, function (html) {
  11107. return Optional.some(renderHtml(html, [textClass]));
  11108. });
  11109. var menuItem = {
  11110. dom: renderItemDomStructure(info.ariaLabel),
  11111. optComponents: [
  11112. leftIcon,
  11113. content,
  11114. info.shortcutContent.map(renderShortcut),
  11115. checkmark,
  11116. info.caret
  11117. ]
  11118. };
  11119. return menuItem;
  11120. };
  11121. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  11122. if (fallbackIcon === void 0) {
  11123. fallbackIcon = Optional.none();
  11124. }
  11125. if (info.presets === 'color') {
  11126. return renderColorStructure(info, providersBackstage, fallbackIcon);
  11127. } else {
  11128. return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon);
  11129. }
  11130. };
  11131. var tooltipBehaviour = function (meta, sharedBackstage) {
  11132. return get$e(meta, 'tooltipWorker').map(function (tooltipWorker) {
  11133. return [Tooltipping.config({
  11134. lazySink: sharedBackstage.getSink,
  11135. tooltipDom: {
  11136. tag: 'div',
  11137. classes: ['tox-tooltip-worker-container']
  11138. },
  11139. tooltipComponents: [],
  11140. anchor: function (comp) {
  11141. return {
  11142. type: 'submenu',
  11143. item: comp,
  11144. overrides: { maxHeightFunction: expandable$1 }
  11145. };
  11146. },
  11147. mode: 'follow-highlight',
  11148. onShow: function (component, _tooltip) {
  11149. tooltipWorker(function (elm) {
  11150. Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]);
  11151. });
  11152. }
  11153. })];
  11154. }).getOr([]);
  11155. };
  11156. var encodeText = function (text) {
  11157. return global$b.DOM.encode(text);
  11158. };
  11159. var replaceText = function (text, matchText) {
  11160. var translated = global$e.translate(text);
  11161. var encoded = encodeText(translated);
  11162. if (matchText.length > 0) {
  11163. var escapedMatchRegex = new RegExp(escape(matchText), 'gi');
  11164. return encoded.replace(escapedMatchRegex, function (match) {
  11165. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  11166. });
  11167. } else {
  11168. return encoded;
  11169. }
  11170. };
  11171. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  11172. if (renderIcons === void 0) {
  11173. renderIcons = true;
  11174. }
  11175. var structure = renderItemStructure({
  11176. presets: presets,
  11177. textContent: Optional.none(),
  11178. htmlContent: useText ? spec.text.map(function (text) {
  11179. return replaceText(text, matchText);
  11180. }) : Optional.none(),
  11181. ariaLabel: spec.text,
  11182. iconContent: spec.icon,
  11183. shortcutContent: Optional.none(),
  11184. checkMark: Optional.none(),
  11185. caret: Optional.none(),
  11186. value: spec.value
  11187. }, sharedBackstage.providers, renderIcons, spec.icon);
  11188. return renderCommonItem({
  11189. data: buildData(spec),
  11190. disabled: spec.disabled,
  11191. getApi: constant$1({}),
  11192. onAction: function (_api) {
  11193. return onItemValueHandler(spec.value, spec.meta);
  11194. },
  11195. onSetup: constant$1(noop),
  11196. triggersSubmenu: false,
  11197. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  11198. }, structure, itemResponse, sharedBackstage.providers);
  11199. };
  11200. var render$2 = function (items, extras) {
  11201. return map$2(items, function (item) {
  11202. switch (item.type) {
  11203. case 'cardcontainer':
  11204. return renderContainer(item, render$2(item.items, extras));
  11205. case 'cardimage':
  11206. return renderImage(item.src, item.classes, item.alt);
  11207. case 'cardtext':
  11208. var shouldHighlight = item.name.exists(function (name) {
  11209. return contains$2(extras.cardText.highlightOn, name);
  11210. });
  11211. var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr('') : '';
  11212. return renderHtml(replaceText(item.text, matchText), item.classes);
  11213. }
  11214. });
  11215. };
  11216. var renderCardMenuItem = function (spec, itemResponse, sharedBackstage, extras) {
  11217. var getApi = function (component) {
  11218. return {
  11219. isDisabled: function () {
  11220. return Disabling.isDisabled(component);
  11221. },
  11222. setDisabled: function (state) {
  11223. Disabling.set(component, state);
  11224. each$1(descendants(component.element, '*'), function (elm) {
  11225. component.getSystem().getByDom(elm).each(function (comp) {
  11226. if (comp.hasConfigured(Disabling)) {
  11227. Disabling.set(comp, state);
  11228. }
  11229. });
  11230. });
  11231. }
  11232. };
  11233. };
  11234. var structure = {
  11235. dom: renderItemDomStructure(spec.label),
  11236. optComponents: [Optional.some({
  11237. dom: {
  11238. tag: 'div',
  11239. classes: [
  11240. containerClass,
  11241. containerRowClass
  11242. ]
  11243. },
  11244. components: render$2(spec.items, extras)
  11245. })]
  11246. };
  11247. return renderCommonItem({
  11248. data: buildData(__assign({ text: Optional.none() }, spec)),
  11249. disabled: spec.disabled,
  11250. getApi: getApi,
  11251. onAction: spec.onAction,
  11252. onSetup: spec.onSetup,
  11253. triggersSubmenu: false,
  11254. itemBehaviours: Optional.from(extras.itemBehaviours).getOr([])
  11255. }, structure, itemResponse, sharedBackstage.providers);
  11256. };
  11257. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
  11258. if (renderIcons === void 0) {
  11259. renderIcons = true;
  11260. }
  11261. var getApi = function (component) {
  11262. return {
  11263. setActive: function (state) {
  11264. Toggling.set(component, state);
  11265. },
  11266. isActive: function () {
  11267. return Toggling.isOn(component);
  11268. },
  11269. isDisabled: function () {
  11270. return Disabling.isDisabled(component);
  11271. },
  11272. setDisabled: function (state) {
  11273. return Disabling.set(component, state);
  11274. }
  11275. };
  11276. };
  11277. var structure = renderItemStructure({
  11278. presets: presets,
  11279. textContent: useText ? spec.text : Optional.none(),
  11280. htmlContent: Optional.none(),
  11281. ariaLabel: spec.text,
  11282. iconContent: spec.icon,
  11283. shortcutContent: useText ? spec.shortcut : Optional.none(),
  11284. checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(),
  11285. caret: Optional.none(),
  11286. value: spec.value
  11287. }, providersBackstage, renderIcons);
  11288. return deepMerge(renderCommonItem({
  11289. data: buildData(spec),
  11290. disabled: spec.disabled,
  11291. getApi: getApi,
  11292. onAction: function (_api) {
  11293. return onItemValueHandler(spec.value);
  11294. },
  11295. onSetup: function (api) {
  11296. api.setActive(isSelected);
  11297. return noop;
  11298. },
  11299. triggersSubmenu: false,
  11300. itemBehaviours: []
  11301. }, structure, itemResponse, providersBackstage), {
  11302. toggling: {
  11303. toggleClass: tickedClass,
  11304. toggleOnExecute: false,
  11305. selected: spec.active
  11306. }
  11307. });
  11308. };
  11309. var parts$f = generate$3(owner$2(), parts$h());
  11310. var hexColour = function (value) {
  11311. return { value: value };
  11312. };
  11313. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  11314. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  11315. var isHexString = function (hex) {
  11316. return shorthandRegex.test(hex) || longformRegex.test(hex);
  11317. };
  11318. var normalizeHex = function (hex) {
  11319. return removeLeading(hex, '#').toUpperCase();
  11320. };
  11321. var fromString$1 = function (hex) {
  11322. return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none();
  11323. };
  11324. var getLongForm = function (hex) {
  11325. var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) {
  11326. return r + r + g + g + b + b;
  11327. });
  11328. return { value: hexString };
  11329. };
  11330. var extractValues = function (hex) {
  11331. var longForm = getLongForm(hex);
  11332. var splitForm = longformRegex.exec(longForm.value);
  11333. return splitForm === null ? [
  11334. 'FFFFFF',
  11335. 'FF',
  11336. 'FF',
  11337. 'FF'
  11338. ] : splitForm;
  11339. };
  11340. var toHex = function (component) {
  11341. var hex = component.toString(16);
  11342. return (hex.length === 1 ? '0' + hex : hex).toUpperCase();
  11343. };
  11344. var fromRgba = function (rgbaColour) {
  11345. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  11346. return hexColour(value);
  11347. };
  11348. var min = Math.min;
  11349. var max = Math.max;
  11350. var round$1 = Math.round;
  11351. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  11352. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  11353. var rgbaColour = function (red, green, blue, alpha) {
  11354. return {
  11355. red: red,
  11356. green: green,
  11357. blue: blue,
  11358. alpha: alpha
  11359. };
  11360. };
  11361. var isRgbaComponent = function (value) {
  11362. var num = parseInt(value, 10);
  11363. return num.toString() === value && num >= 0 && num <= 255;
  11364. };
  11365. var fromHsv = function (hsv) {
  11366. var r;
  11367. var g;
  11368. var b;
  11369. var hue = (hsv.hue || 0) % 360;
  11370. var saturation = hsv.saturation / 100;
  11371. var brightness = hsv.value / 100;
  11372. saturation = max(0, min(saturation, 1));
  11373. brightness = max(0, min(brightness, 1));
  11374. if (saturation === 0) {
  11375. r = g = b = round$1(255 * brightness);
  11376. return rgbaColour(r, g, b, 1);
  11377. }
  11378. var side = hue / 60;
  11379. var chroma = brightness * saturation;
  11380. var x = chroma * (1 - Math.abs(side % 2 - 1));
  11381. var match = brightness - chroma;
  11382. switch (Math.floor(side)) {
  11383. case 0:
  11384. r = chroma;
  11385. g = x;
  11386. b = 0;
  11387. break;
  11388. case 1:
  11389. r = x;
  11390. g = chroma;
  11391. b = 0;
  11392. break;
  11393. case 2:
  11394. r = 0;
  11395. g = chroma;
  11396. b = x;
  11397. break;
  11398. case 3:
  11399. r = 0;
  11400. g = x;
  11401. b = chroma;
  11402. break;
  11403. case 4:
  11404. r = x;
  11405. g = 0;
  11406. b = chroma;
  11407. break;
  11408. case 5:
  11409. r = chroma;
  11410. g = 0;
  11411. b = x;
  11412. break;
  11413. default:
  11414. r = g = b = 0;
  11415. }
  11416. r = round$1(255 * (r + match));
  11417. g = round$1(255 * (g + match));
  11418. b = round$1(255 * (b + match));
  11419. return rgbaColour(r, g, b, 1);
  11420. };
  11421. var fromHex = function (hexColour) {
  11422. var result = extractValues(hexColour);
  11423. var red = parseInt(result[1], 16);
  11424. var green = parseInt(result[2], 16);
  11425. var blue = parseInt(result[3], 16);
  11426. return rgbaColour(red, green, blue, 1);
  11427. };
  11428. var fromStringValues = function (red, green, blue, alpha) {
  11429. var r = parseInt(red, 10);
  11430. var g = parseInt(green, 10);
  11431. var b = parseInt(blue, 10);
  11432. var a = parseFloat(alpha);
  11433. return rgbaColour(r, g, b, a);
  11434. };
  11435. var fromString = function (rgbaString) {
  11436. if (rgbaString === 'transparent') {
  11437. return Optional.some(rgbaColour(0, 0, 0, 0));
  11438. }
  11439. var rgbMatch = rgbRegex.exec(rgbaString);
  11440. if (rgbMatch !== null) {
  11441. return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  11442. }
  11443. var rgbaMatch = rgbaRegex.exec(rgbaString);
  11444. if (rgbaMatch !== null) {
  11445. return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  11446. }
  11447. return Optional.none();
  11448. };
  11449. var toString = function (rgba) {
  11450. return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')';
  11451. };
  11452. var red = rgbaColour(255, 0, 0, 1);
  11453. var fireSkinLoaded$1 = function (editor) {
  11454. return editor.fire('SkinLoaded');
  11455. };
  11456. var fireSkinLoadError$1 = function (editor, error) {
  11457. return editor.fire('SkinLoadError', error);
  11458. };
  11459. var fireResizeEditor = function (editor) {
  11460. return editor.fire('ResizeEditor');
  11461. };
  11462. var fireResizeContent = function (editor, e) {
  11463. return editor.fire('ResizeContent', e);
  11464. };
  11465. var fireScrollContent = function (editor, e) {
  11466. return editor.fire('ScrollContent', e);
  11467. };
  11468. var fireTextColorChange = function (editor, data) {
  11469. return editor.fire('TextColorChange', data);
  11470. };
  11471. var hsvColour = function (hue, saturation, value) {
  11472. return {
  11473. hue: hue,
  11474. saturation: saturation,
  11475. value: value
  11476. };
  11477. };
  11478. var fromRgb = function (rgbaColour) {
  11479. var h = 0;
  11480. var s = 0;
  11481. var v = 0;
  11482. var r = rgbaColour.red / 255;
  11483. var g = rgbaColour.green / 255;
  11484. var b = rgbaColour.blue / 255;
  11485. var minRGB = Math.min(r, Math.min(g, b));
  11486. var maxRGB = Math.max(r, Math.max(g, b));
  11487. if (minRGB === maxRGB) {
  11488. v = minRGB;
  11489. return hsvColour(0, 0, v * 100);
  11490. }
  11491. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  11492. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  11493. h = 60 * (h - d / (maxRGB - minRGB));
  11494. s = (maxRGB - minRGB) / maxRGB;
  11495. v = maxRGB;
  11496. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  11497. };
  11498. var hexToHsv = function (hex) {
  11499. return fromRgb(fromHex(hex));
  11500. };
  11501. var hsvToHex = function (hsv) {
  11502. return fromRgba(fromHsv(hsv));
  11503. };
  11504. var anyToHex = function (color) {
  11505. return fromString$1(color).orThunk(function () {
  11506. return fromString(color).map(fromRgba);
  11507. }).getOrThunk(function () {
  11508. var canvas = document.createElement('canvas');
  11509. canvas.height = 1;
  11510. canvas.width = 1;
  11511. var canvasContext = canvas.getContext('2d');
  11512. canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  11513. canvasContext.fillStyle = '#FFFFFF';
  11514. canvasContext.fillStyle = color;
  11515. canvasContext.fillRect(0, 0, 1, 1);
  11516. var rgba = canvasContext.getImageData(0, 0, 1, 1).data;
  11517. var r = rgba[0];
  11518. var g = rgba[1];
  11519. var b = rgba[2];
  11520. var a = rgba[3];
  11521. return fromRgba(rgbaColour(r, g, b, a));
  11522. });
  11523. };
  11524. var global$8 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  11525. var storageName = 'tinymce-custom-colors';
  11526. function ColorCache (max) {
  11527. if (max === void 0) {
  11528. max = 10;
  11529. }
  11530. var storageString = global$8.getItem(storageName);
  11531. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  11532. var prune = function (list) {
  11533. var diff = max - list.length;
  11534. return diff < 0 ? list.slice(0, max) : list;
  11535. };
  11536. var cache = prune(localstorage);
  11537. var add = function (key) {
  11538. indexOf(cache, key).each(remove);
  11539. cache.unshift(key);
  11540. if (cache.length > max) {
  11541. cache.pop();
  11542. }
  11543. global$8.setItem(storageName, JSON.stringify(cache));
  11544. };
  11545. var remove = function (idx) {
  11546. cache.splice(idx, 1);
  11547. };
  11548. var state = function () {
  11549. return cache.slice(0);
  11550. };
  11551. return {
  11552. add: add,
  11553. state: state
  11554. };
  11555. }
  11556. var choiceItem = 'choiceitem';
  11557. var defaultColors = [
  11558. {
  11559. type: choiceItem,
  11560. text: 'Light Green',
  11561. value: '#BFEDD2'
  11562. },
  11563. {
  11564. type: choiceItem,
  11565. text: 'Light Yellow',
  11566. value: '#FBEEB8'
  11567. },
  11568. {
  11569. type: choiceItem,
  11570. text: 'Light Red',
  11571. value: '#F8CAC6'
  11572. },
  11573. {
  11574. type: choiceItem,
  11575. text: 'Light Purple',
  11576. value: '#ECCAFA'
  11577. },
  11578. {
  11579. type: choiceItem,
  11580. text: 'Light Blue',
  11581. value: '#C2E0F4'
  11582. },
  11583. {
  11584. type: choiceItem,
  11585. text: 'Green',
  11586. value: '#2DC26B'
  11587. },
  11588. {
  11589. type: choiceItem,
  11590. text: 'Yellow',
  11591. value: '#F1C40F'
  11592. },
  11593. {
  11594. type: choiceItem,
  11595. text: 'Red',
  11596. value: '#E03E2D'
  11597. },
  11598. {
  11599. type: choiceItem,
  11600. text: 'Purple',
  11601. value: '#B96AD9'
  11602. },
  11603. {
  11604. type: choiceItem,
  11605. text: 'Blue',
  11606. value: '#3598DB'
  11607. },
  11608. {
  11609. type: choiceItem,
  11610. text: 'Dark Turquoise',
  11611. value: '#169179'
  11612. },
  11613. {
  11614. type: choiceItem,
  11615. text: 'Orange',
  11616. value: '#E67E23'
  11617. },
  11618. {
  11619. type: choiceItem,
  11620. text: 'Dark Red',
  11621. value: '#BA372A'
  11622. },
  11623. {
  11624. type: choiceItem,
  11625. text: 'Dark Purple',
  11626. value: '#843FA1'
  11627. },
  11628. {
  11629. type: choiceItem,
  11630. text: 'Dark Blue',
  11631. value: '#236FA1'
  11632. },
  11633. {
  11634. type: choiceItem,
  11635. text: 'Light Gray',
  11636. value: '#ECF0F1'
  11637. },
  11638. {
  11639. type: choiceItem,
  11640. text: 'Medium Gray',
  11641. value: '#CED4D9'
  11642. },
  11643. {
  11644. type: choiceItem,
  11645. text: 'Gray',
  11646. value: '#95A5A6'
  11647. },
  11648. {
  11649. type: choiceItem,
  11650. text: 'Dark Gray',
  11651. value: '#7E8C8D'
  11652. },
  11653. {
  11654. type: choiceItem,
  11655. text: 'Navy Blue',
  11656. value: '#34495E'
  11657. },
  11658. {
  11659. type: choiceItem,
  11660. text: 'Black',
  11661. value: '#000000'
  11662. },
  11663. {
  11664. type: choiceItem,
  11665. text: 'White',
  11666. value: '#ffffff'
  11667. }
  11668. ];
  11669. var colorCache = ColorCache(10);
  11670. var mapColors = function (colorMap) {
  11671. var colors = [];
  11672. for (var i = 0; i < colorMap.length; i += 2) {
  11673. colors.push({
  11674. text: colorMap[i + 1],
  11675. value: '#' + anyToHex(colorMap[i]).value,
  11676. type: 'choiceitem'
  11677. });
  11678. }
  11679. return colors;
  11680. };
  11681. var getColorCols$2 = function (editor, defaultCols) {
  11682. return editor.getParam('color_cols', defaultCols, 'number');
  11683. };
  11684. var hasCustomColors$1 = function (editor) {
  11685. return editor.getParam('custom_colors') !== false;
  11686. };
  11687. var getColorMap = function (editor) {
  11688. return editor.getParam('color_map');
  11689. };
  11690. var getColors$2 = function (editor) {
  11691. var unmapped = getColorMap(editor);
  11692. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  11693. };
  11694. var getCurrentColors = function () {
  11695. return map$2(colorCache.state(), function (color) {
  11696. return {
  11697. type: choiceItem,
  11698. text: color,
  11699. value: color
  11700. };
  11701. });
  11702. };
  11703. var addColor = function (color) {
  11704. colorCache.add(color);
  11705. };
  11706. var fallbackColor = '#000000';
  11707. var getCurrentColor = function (editor, format) {
  11708. var color;
  11709. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  11710. var value;
  11711. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  11712. color = color ? color : value;
  11713. }
  11714. });
  11715. return Optional.from(color);
  11716. };
  11717. var applyFormat = function (editor, format, value) {
  11718. editor.undoManager.transact(function () {
  11719. editor.focus();
  11720. editor.formatter.apply(format, { value: value });
  11721. editor.nodeChanged();
  11722. });
  11723. };
  11724. var removeFormat = function (editor, format) {
  11725. editor.undoManager.transact(function () {
  11726. editor.focus();
  11727. editor.formatter.remove(format, { value: null }, null, true);
  11728. editor.nodeChanged();
  11729. });
  11730. };
  11731. var registerCommands = function (editor) {
  11732. editor.addCommand('mceApplyTextcolor', function (format, value) {
  11733. applyFormat(editor, format, value);
  11734. });
  11735. editor.addCommand('mceRemoveTextcolor', function (format) {
  11736. removeFormat(editor, format);
  11737. });
  11738. };
  11739. var calcCols = function (colors) {
  11740. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  11741. };
  11742. var getColorCols$1 = function (editor) {
  11743. var colors = getColors$2(editor);
  11744. var defaultCols = calcCols(colors.length);
  11745. return getColorCols$2(editor, defaultCols);
  11746. };
  11747. var getAdditionalColors = function (hasCustom) {
  11748. var type = 'choiceitem';
  11749. var remove = {
  11750. type: type,
  11751. text: 'Remove color',
  11752. icon: 'color-swatch-remove-color',
  11753. value: 'remove'
  11754. };
  11755. var custom = {
  11756. type: type,
  11757. text: 'Custom color',
  11758. icon: 'color-picker',
  11759. value: 'custom'
  11760. };
  11761. return hasCustom ? [
  11762. remove,
  11763. custom
  11764. ] : [remove];
  11765. };
  11766. var applyColor = function (editor, format, value, onChoice) {
  11767. if (value === 'custom') {
  11768. var dialog = colorPickerDialog(editor);
  11769. dialog(function (colorOpt) {
  11770. colorOpt.each(function (color) {
  11771. addColor(color);
  11772. editor.execCommand('mceApplyTextcolor', format, color);
  11773. onChoice(color);
  11774. });
  11775. }, fallbackColor);
  11776. } else if (value === 'remove') {
  11777. onChoice('');
  11778. editor.execCommand('mceRemoveTextcolor', format);
  11779. } else {
  11780. onChoice(value);
  11781. editor.execCommand('mceApplyTextcolor', format, value);
  11782. }
  11783. };
  11784. var getColors$1 = function (colors, hasCustom) {
  11785. return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  11786. };
  11787. var getFetch$1 = function (colors, hasCustom) {
  11788. return function (callback) {
  11789. callback(getColors$1(colors, hasCustom));
  11790. };
  11791. };
  11792. var setIconColor = function (splitButtonApi, name, newColor) {
  11793. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  11794. splitButtonApi.setIconFill(id, newColor);
  11795. };
  11796. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  11797. editor.ui.registry.addSplitButton(name, {
  11798. tooltip: tooltip,
  11799. presets: 'color',
  11800. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11801. select: function (value) {
  11802. var optCurrentRgb = getCurrentColor(editor, format);
  11803. return optCurrentRgb.bind(function (currentRgb) {
  11804. return fromString(currentRgb).map(function (rgba) {
  11805. var currentHex = fromRgba(rgba).value;
  11806. return contains$1(value.toLowerCase(), currentHex);
  11807. });
  11808. }).getOr(false);
  11809. },
  11810. columns: getColorCols$1(editor),
  11811. fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)),
  11812. onAction: function (_splitButtonApi) {
  11813. applyColor(editor, format, lastColor.get(), noop);
  11814. },
  11815. onItemAction: function (_splitButtonApi, value) {
  11816. applyColor(editor, format, value, function (newColor) {
  11817. lastColor.set(newColor);
  11818. fireTextColorChange(editor, {
  11819. name: name,
  11820. color: newColor
  11821. });
  11822. });
  11823. },
  11824. onSetup: function (splitButtonApi) {
  11825. setIconColor(splitButtonApi, name, lastColor.get());
  11826. var handler = function (e) {
  11827. if (e.name === name) {
  11828. setIconColor(splitButtonApi, e.name, e.color);
  11829. }
  11830. };
  11831. editor.on('TextColorChange', handler);
  11832. return function () {
  11833. editor.off('TextColorChange', handler);
  11834. };
  11835. }
  11836. });
  11837. };
  11838. var registerTextColorMenuItem = function (editor, name, format, text) {
  11839. editor.ui.registry.addNestedMenuItem(name, {
  11840. text: text,
  11841. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  11842. getSubmenuItems: function () {
  11843. return [{
  11844. type: 'fancymenuitem',
  11845. fancytype: 'colorswatch',
  11846. onAction: function (data) {
  11847. applyColor(editor, format, data.value, noop);
  11848. }
  11849. }];
  11850. }
  11851. });
  11852. };
  11853. var colorPickerDialog = function (editor) {
  11854. return function (callback, value) {
  11855. var isValid = false;
  11856. var onSubmit = function (api) {
  11857. var data = api.getData();
  11858. var hex = data.colorpicker;
  11859. if (isValid) {
  11860. callback(Optional.from(hex));
  11861. api.close();
  11862. } else {
  11863. editor.windowManager.alert(editor.translate([
  11864. 'Invalid hex color code: {0}',
  11865. hex
  11866. ]));
  11867. }
  11868. };
  11869. var onAction = function (_api, details) {
  11870. if (details.name === 'hex-valid') {
  11871. isValid = details.value;
  11872. }
  11873. };
  11874. var initialData = { colorpicker: value };
  11875. editor.windowManager.open({
  11876. title: 'Color Picker',
  11877. size: 'normal',
  11878. body: {
  11879. type: 'panel',
  11880. items: [{
  11881. type: 'colorpicker',
  11882. name: 'colorpicker',
  11883. label: 'Color'
  11884. }]
  11885. },
  11886. buttons: [
  11887. {
  11888. type: 'cancel',
  11889. name: 'cancel',
  11890. text: 'Cancel'
  11891. },
  11892. {
  11893. type: 'submit',
  11894. name: 'save',
  11895. text: 'Save',
  11896. primary: true
  11897. }
  11898. ],
  11899. initialData: initialData,
  11900. onAction: onAction,
  11901. onSubmit: onSubmit,
  11902. onClose: noop,
  11903. onCancel: function () {
  11904. callback(Optional.none());
  11905. }
  11906. });
  11907. };
  11908. };
  11909. var register$a = function (editor) {
  11910. registerCommands(editor);
  11911. var lastForeColor = Cell(fallbackColor);
  11912. var lastBackColor = Cell(fallbackColor);
  11913. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  11914. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  11915. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  11916. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  11917. };
  11918. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11919. var hasIcons = menuHasIcons(items);
  11920. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11921. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11922. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11923. };
  11924. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11925. return cat(map$2(items, function (item) {
  11926. if (item.type === 'choiceitem') {
  11927. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11928. return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items)));
  11929. });
  11930. } else {
  11931. return Optional.none();
  11932. }
  11933. }));
  11934. };
  11935. var deriveMenuMovement = function (columns, presets) {
  11936. var menuMarkers = markers(presets);
  11937. if (columns === 1) {
  11938. return {
  11939. mode: 'menu',
  11940. moveOnTab: true
  11941. };
  11942. } else if (columns === 'auto') {
  11943. return {
  11944. mode: 'grid',
  11945. selector: '.' + menuMarkers.item,
  11946. initSize: {
  11947. numColumns: 1,
  11948. numRows: 1
  11949. }
  11950. };
  11951. } else {
  11952. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11953. return {
  11954. mode: 'matrix',
  11955. rowSelector: '.' + rowClass
  11956. };
  11957. }
  11958. };
  11959. var deriveCollectionMovement = function (columns, presets) {
  11960. if (columns === 1) {
  11961. return {
  11962. mode: 'menu',
  11963. moveOnTab: false,
  11964. selector: '.tox-collection__item'
  11965. };
  11966. } else if (columns === 'auto') {
  11967. return {
  11968. mode: 'flatgrid',
  11969. selector: '.' + 'tox-collection__item',
  11970. initSize: {
  11971. numColumns: 1,
  11972. numRows: 1
  11973. }
  11974. };
  11975. } else {
  11976. return {
  11977. mode: 'matrix',
  11978. selectors: {
  11979. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11980. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11981. }
  11982. };
  11983. }
  11984. };
  11985. var renderColorSwatchItem = function (spec, backstage) {
  11986. var items = getColorItems(spec, backstage);
  11987. var columns = backstage.colorinput.getColorCols();
  11988. var presets = 'color';
  11989. var menuSpec = createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  11990. spec.onAction({ value: value });
  11991. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers);
  11992. var widgetSpec = __assign(__assign({}, menuSpec), {
  11993. markers: markers(presets),
  11994. movement: deriveMenuMovement(columns, presets)
  11995. });
  11996. return {
  11997. type: 'widget',
  11998. data: { value: generate$6('widget-id') },
  11999. dom: {
  12000. tag: 'div',
  12001. classes: ['tox-fancymenuitem']
  12002. },
  12003. autofocus: true,
  12004. components: [parts$f.widget(Menu.sketch(widgetSpec))]
  12005. };
  12006. };
  12007. var getColorItems = function (spec, backstage) {
  12008. var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors();
  12009. return spec.initData.colors.fold(function () {
  12010. return getColors$1(backstage.colorinput.getColors(), useCustomColors);
  12011. }, function (colors) {
  12012. return colors.concat(getAdditionalColors(useCustomColors));
  12013. });
  12014. };
  12015. var cellOverEvent = generate$6('cell-over');
  12016. var cellExecuteEvent = generate$6('cell-execute');
  12017. var makeCell = function (row, col, labelId) {
  12018. var _a;
  12019. var emitCellOver = function (c) {
  12020. return emitWith(c, cellOverEvent, {
  12021. row: row,
  12022. col: col
  12023. });
  12024. };
  12025. var emitExecute = function (c) {
  12026. return emitWith(c, cellExecuteEvent, {
  12027. row: row,
  12028. col: col
  12029. });
  12030. };
  12031. var onClick = function (c, se) {
  12032. se.stop();
  12033. emitExecute(c);
  12034. };
  12035. return build$1({
  12036. dom: {
  12037. tag: 'div',
  12038. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  12039. },
  12040. behaviours: derive$1([
  12041. config('insert-table-picker-cell', [
  12042. run$1(mouseover(), Focusing.focus),
  12043. run$1(execute$5(), emitExecute),
  12044. run$1(click(), onClick),
  12045. run$1(tap(), onClick)
  12046. ]),
  12047. Toggling.config({
  12048. toggleClass: 'tox-insert-table-picker__selected',
  12049. toggleOnExecute: false
  12050. }),
  12051. Focusing.config({ onFocus: emitCellOver })
  12052. ])
  12053. });
  12054. };
  12055. var makeCells = function (labelId, numRows, numCols) {
  12056. var cells = [];
  12057. for (var i = 0; i < numRows; i++) {
  12058. var row = [];
  12059. for (var j = 0; j < numCols; j++) {
  12060. row.push(makeCell(i, j, labelId));
  12061. }
  12062. cells.push(row);
  12063. }
  12064. return cells;
  12065. };
  12066. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  12067. for (var i = 0; i < numRows; i++) {
  12068. for (var j = 0; j < numColumns; j++) {
  12069. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  12070. }
  12071. }
  12072. };
  12073. var makeComponents = function (cells) {
  12074. return bind$3(cells, function (cellRow) {
  12075. return map$2(cellRow, premade);
  12076. });
  12077. };
  12078. var makeLabelText = function (row, col) {
  12079. return text(col + 'x' + row);
  12080. };
  12081. var renderInsertTableMenuItem = function (spec) {
  12082. var numRows = 10;
  12083. var numColumns = 10;
  12084. var sizeLabelId = generate$6('size-label');
  12085. var cells = makeCells(sizeLabelId, numRows, numColumns);
  12086. var emptyLabelText = makeLabelText(0, 0);
  12087. var memLabel = record({
  12088. dom: {
  12089. tag: 'span',
  12090. classes: ['tox-insert-table-picker__label'],
  12091. attributes: { id: sizeLabelId }
  12092. },
  12093. components: [emptyLabelText],
  12094. behaviours: derive$1([Replacing.config({})])
  12095. });
  12096. return {
  12097. type: 'widget',
  12098. data: { value: generate$6('widget-id') },
  12099. dom: {
  12100. tag: 'div',
  12101. classes: ['tox-fancymenuitem']
  12102. },
  12103. autofocus: true,
  12104. components: [parts$f.widget({
  12105. dom: {
  12106. tag: 'div',
  12107. classes: ['tox-insert-table-picker']
  12108. },
  12109. components: makeComponents(cells).concat(memLabel.asSpec()),
  12110. behaviours: derive$1([
  12111. config('insert-table-picker', [
  12112. runOnAttached(function (c) {
  12113. Replacing.set(memLabel.get(c), [emptyLabelText]);
  12114. }),
  12115. runWithTarget(cellOverEvent, function (c, t, e) {
  12116. var _a = e.event, row = _a.row, col = _a.col;
  12117. selectCells(cells, row, col, numRows, numColumns);
  12118. Replacing.set(memLabel.get(c), [makeLabelText(row + 1, col + 1)]);
  12119. }),
  12120. runWithTarget(cellExecuteEvent, function (c, _, e) {
  12121. var _a = e.event, row = _a.row, col = _a.col;
  12122. spec.onAction({
  12123. numRows: row + 1,
  12124. numColumns: col + 1
  12125. });
  12126. emit(c, sandboxClose());
  12127. })
  12128. ]),
  12129. Keying.config({
  12130. initSize: {
  12131. numRows: numRows,
  12132. numColumns: numColumns
  12133. },
  12134. mode: 'flatgrid',
  12135. selector: '[role="button"]'
  12136. })
  12137. ])
  12138. })]
  12139. };
  12140. };
  12141. var fancyMenuItems = {
  12142. inserttable: renderInsertTableMenuItem,
  12143. colorswatch: renderColorSwatchItem
  12144. };
  12145. var renderFancyMenuItem = function (spec, backstage) {
  12146. return get$e(fancyMenuItems, spec.fancytype).map(function (render) {
  12147. return render(spec, backstage);
  12148. });
  12149. };
  12150. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  12151. if (renderIcons === void 0) {
  12152. renderIcons = true;
  12153. }
  12154. if (downwardsCaret === void 0) {
  12155. downwardsCaret = false;
  12156. }
  12157. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  12158. var getApi = function (component) {
  12159. return {
  12160. isDisabled: function () {
  12161. return Disabling.isDisabled(component);
  12162. },
  12163. setDisabled: function (state) {
  12164. return Disabling.set(component, state);
  12165. }
  12166. };
  12167. };
  12168. var structure = renderItemStructure({
  12169. presets: 'normal',
  12170. iconContent: spec.icon,
  12171. textContent: spec.text,
  12172. htmlContent: Optional.none(),
  12173. ariaLabel: spec.text,
  12174. caret: Optional.some(caret),
  12175. checkMark: Optional.none(),
  12176. shortcutContent: spec.shortcut
  12177. }, providersBackstage, renderIcons);
  12178. return renderCommonItem({
  12179. data: buildData(spec),
  12180. getApi: getApi,
  12181. disabled: spec.disabled,
  12182. onAction: noop,
  12183. onSetup: spec.onSetup,
  12184. triggersSubmenu: true,
  12185. itemBehaviours: []
  12186. }, structure, itemResponse, providersBackstage);
  12187. };
  12188. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  12189. if (renderIcons === void 0) {
  12190. renderIcons = true;
  12191. }
  12192. var getApi = function (component) {
  12193. return {
  12194. isDisabled: function () {
  12195. return Disabling.isDisabled(component);
  12196. },
  12197. setDisabled: function (state) {
  12198. return Disabling.set(component, state);
  12199. }
  12200. };
  12201. };
  12202. var structure = renderItemStructure({
  12203. presets: 'normal',
  12204. iconContent: spec.icon,
  12205. textContent: spec.text,
  12206. htmlContent: Optional.none(),
  12207. ariaLabel: spec.text,
  12208. caret: Optional.none(),
  12209. checkMark: Optional.none(),
  12210. shortcutContent: spec.shortcut
  12211. }, providersBackstage, renderIcons);
  12212. return renderCommonItem({
  12213. data: buildData(spec),
  12214. getApi: getApi,
  12215. disabled: spec.disabled,
  12216. onAction: spec.onAction,
  12217. onSetup: spec.onSetup,
  12218. triggersSubmenu: false,
  12219. itemBehaviours: []
  12220. }, structure, itemResponse, providersBackstage);
  12221. };
  12222. var renderSeparatorItem = function (spec) {
  12223. var innerHtml = spec.text.fold(function () {
  12224. return {};
  12225. }, function (text) {
  12226. return { innerHtml: text };
  12227. });
  12228. return {
  12229. type: 'separator',
  12230. dom: __assign({
  12231. tag: 'div',
  12232. classes: [
  12233. selectableClass,
  12234. groupHeadingClass
  12235. ]
  12236. }, innerHtml),
  12237. components: []
  12238. };
  12239. };
  12240. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  12241. if (renderIcons === void 0) {
  12242. renderIcons = true;
  12243. }
  12244. var getApi = function (component) {
  12245. return {
  12246. setActive: function (state) {
  12247. Toggling.set(component, state);
  12248. },
  12249. isActive: function () {
  12250. return Toggling.isOn(component);
  12251. },
  12252. isDisabled: function () {
  12253. return Disabling.isDisabled(component);
  12254. },
  12255. setDisabled: function (state) {
  12256. return Disabling.set(component, state);
  12257. }
  12258. };
  12259. };
  12260. var structure = renderItemStructure({
  12261. iconContent: spec.icon,
  12262. textContent: spec.text,
  12263. htmlContent: Optional.none(),
  12264. ariaLabel: spec.text,
  12265. checkMark: Optional.some(renderCheckmark(providersBackstage.icons)),
  12266. caret: Optional.none(),
  12267. shortcutContent: spec.shortcut,
  12268. presets: 'normal',
  12269. meta: spec.meta
  12270. }, providersBackstage, renderIcons);
  12271. return deepMerge(renderCommonItem({
  12272. data: buildData(spec),
  12273. disabled: spec.disabled,
  12274. getApi: getApi,
  12275. onAction: spec.onAction,
  12276. onSetup: spec.onSetup,
  12277. triggersSubmenu: false,
  12278. itemBehaviours: []
  12279. }, structure, itemResponse, providersBackstage), {
  12280. toggling: {
  12281. toggleClass: tickedClass,
  12282. toggleOnExecute: false,
  12283. selected: spec.active
  12284. }
  12285. });
  12286. };
  12287. var autocomplete = renderAutocompleteItem;
  12288. var separator$3 = renderSeparatorItem;
  12289. var normal = renderNormalItem;
  12290. var nested = renderNestedItem;
  12291. var toggle$1 = renderToggleMenuItem;
  12292. var fancy = renderFancyMenuItem;
  12293. var card = renderCardMenuItem;
  12294. var FocusMode;
  12295. (function (FocusMode) {
  12296. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  12297. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  12298. }(FocusMode || (FocusMode = {})));
  12299. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  12300. var providersBackstage = backstage.shared.providers;
  12301. var parseForHorizontalMenu = function (menuitem) {
  12302. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  12303. shortcut: Optional.none(),
  12304. icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon
  12305. });
  12306. };
  12307. switch (item.type) {
  12308. case 'menuitem':
  12309. return createMenuItem(item).fold(handleError, function (d) {
  12310. return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  12311. });
  12312. case 'nestedmenuitem':
  12313. return createNestedMenuItem(item).fold(handleError, function (d) {
  12314. return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  12315. });
  12316. case 'togglemenuitem':
  12317. return createToggleMenuItem(item).fold(handleError, function (d) {
  12318. return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  12319. });
  12320. case 'separator':
  12321. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  12322. return Optional.some(separator$3(d));
  12323. });
  12324. case 'fancymenuitem':
  12325. return createFancyMenuItem(item).fold(handleError, function (d) {
  12326. return fancy(parseForHorizontalMenu(d), backstage);
  12327. });
  12328. default: {
  12329. console.error('Unknown item in general menu', item);
  12330. return Optional.none();
  12331. }
  12332. }
  12333. };
  12334. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) {
  12335. var renderText = columns === 1;
  12336. var renderIcons = !renderText || menuHasIcons(items);
  12337. return cat(map$2(items, function (item) {
  12338. switch (item.type) {
  12339. case 'separator':
  12340. return createSeparatorItem(item).fold(handleError, function (d) {
  12341. return Optional.some(separator$3(d));
  12342. });
  12343. case 'cardmenuitem':
  12344. return createCardMenuItem(item).fold(handleError, function (d) {
  12345. return Optional.some(card(__assign(__assign({}, d), {
  12346. onAction: function (api) {
  12347. d.onAction(api);
  12348. onItemValueHandler(d.value, d.meta);
  12349. }
  12350. }), itemResponse, sharedBackstage, {
  12351. itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage),
  12352. cardText: {
  12353. matchText: matchText,
  12354. highlightOn: highlightOn
  12355. }
  12356. }));
  12357. });
  12358. case 'autocompleteitem':
  12359. default:
  12360. return createAutocompleterItem(item).fold(handleError, function (d) {
  12361. return Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  12362. });
  12363. }
  12364. }));
  12365. };
  12366. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  12367. var hasIcons = menuHasIcons(items);
  12368. var alloyItems = cat(map$2(items, function (item) {
  12369. var itemHasIcon = function (i) {
  12370. return isHorizontalMenu ? !has$2(i, 'text') : hasIcons;
  12371. };
  12372. var createItem = function (i) {
  12373. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  12374. };
  12375. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  12376. return createItem(__assign(__assign({}, item), { disabled: true }));
  12377. } else {
  12378. return createItem(item);
  12379. }
  12380. }));
  12381. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  12382. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  12383. };
  12384. var createTieredDataFrom = function (partialMenu) {
  12385. return tieredMenu.singleData(partialMenu.value, partialMenu);
  12386. };
  12387. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  12388. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2();
  12389. var movement = deriveMenuMovement(columns, presets);
  12390. var menuMarkers = markers(presets);
  12391. return {
  12392. dom: partialMenu.dom,
  12393. components: partialMenu.components,
  12394. items: partialMenu.items,
  12395. value: partialMenu.value,
  12396. markers: {
  12397. selectedItem: menuMarkers.selectedItem,
  12398. item: menuMarkers.item
  12399. },
  12400. movement: movement,
  12401. fakeFocus: focusMode === FocusMode.ContentFocus,
  12402. focusManager: focusManager,
  12403. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  12404. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  12405. var numColumns = _a.numColumns, numRows = _a.numRows;
  12406. Keying.setGridSize(comp, numRows, numColumns);
  12407. });
  12408. })])
  12409. };
  12410. };
  12411. var register$9 = function (editor, sharedBackstage) {
  12412. var activeAutocompleter = value$1();
  12413. var processingAction = Cell(false);
  12414. var autocompleter = build$1(InlineView.sketch({
  12415. dom: {
  12416. tag: 'div',
  12417. classes: ['tox-autocompleter']
  12418. },
  12419. components: [],
  12420. fireDismissalEventInstead: {},
  12421. inlineBehaviours: derive$1([config('dismissAutocompleter', [run$1(dismissRequested(), function () {
  12422. return cancelIfNecessary();
  12423. })])]),
  12424. lazySink: sharedBackstage.getSink
  12425. }));
  12426. var isMenuOpen = function () {
  12427. return InlineView.isOpen(autocompleter);
  12428. };
  12429. var isActive = function () {
  12430. return activeAutocompleter.get().isSome();
  12431. };
  12432. var hideIfNecessary = function () {
  12433. if (isActive()) {
  12434. InlineView.hide(autocompleter);
  12435. }
  12436. };
  12437. var cancelIfNecessary = function () {
  12438. if (isActive()) {
  12439. var lastElement = activeAutocompleter.get().map(function (ac) {
  12440. return ac.element;
  12441. });
  12442. detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap);
  12443. hideIfNecessary();
  12444. activeAutocompleter.clear();
  12445. processingAction.set(false);
  12446. }
  12447. };
  12448. var getAutocompleters = cached(function () {
  12449. return register$b(editor);
  12450. });
  12451. var getCombinedItems = function (triggerChar, matches) {
  12452. var columns = findMap(matches, function (m) {
  12453. return Optional.from(m.columns);
  12454. }).getOr(1);
  12455. return bind$3(matches, function (match) {
  12456. var choices = match.items;
  12457. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  12458. var nr = editor.selection.getRng();
  12459. getContext(editor.dom, nr, triggerChar).fold(function () {
  12460. return console.error('Lost context. Cursor probably moved');
  12461. }, function (_a) {
  12462. var range = _a.range;
  12463. var autocompleterApi = {
  12464. hide: function () {
  12465. cancelIfNecessary();
  12466. },
  12467. reload: function (fetchOptions) {
  12468. hideIfNecessary();
  12469. load(fetchOptions);
  12470. }
  12471. };
  12472. processingAction.set(true);
  12473. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  12474. processingAction.set(false);
  12475. });
  12476. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn);
  12477. });
  12478. };
  12479. var commenceIfNecessary = function (context) {
  12480. if (!isActive()) {
  12481. var wrapper = create$4(editor, context.range);
  12482. activeAutocompleter.set({
  12483. triggerChar: context.triggerChar,
  12484. element: wrapper,
  12485. matchLength: context.text.length
  12486. });
  12487. processingAction.set(false);
  12488. }
  12489. };
  12490. var display = function (ac, context, lookupData, items) {
  12491. ac.matchLength = context.text.length;
  12492. var columns = findMap(lookupData, function (ld) {
  12493. return Optional.from(ld.columns);
  12494. }).getOr(1);
  12495. InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')), {
  12496. anchor: {
  12497. type: 'node',
  12498. root: SugarElement.fromDom(editor.getBody()),
  12499. node: Optional.from(ac.element)
  12500. }
  12501. });
  12502. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  12503. };
  12504. var doLookup = function (fetchOptions) {
  12505. return activeAutocompleter.get().map(function (ac) {
  12506. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  12507. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  12508. });
  12509. }).getOrThunk(function () {
  12510. return lookup$2(editor, getAutocompleters);
  12511. });
  12512. };
  12513. var load = function (fetchOptions) {
  12514. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  12515. commenceIfNecessary(lookupInfo.context);
  12516. lookupInfo.lookupData.then(function (lookupData) {
  12517. activeAutocompleter.get().map(function (ac) {
  12518. var context = lookupInfo.context;
  12519. if (ac.triggerChar === context.triggerChar) {
  12520. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  12521. if (combinedItems.length > 0) {
  12522. display(ac, context, lookupData, combinedItems);
  12523. } else if (context.text.length - ac.matchLength >= 10) {
  12524. cancelIfNecessary();
  12525. } else {
  12526. hideIfNecessary();
  12527. }
  12528. }
  12529. });
  12530. });
  12531. });
  12532. };
  12533. var onKeypress = last(function (e) {
  12534. if (e.which === 27) {
  12535. return;
  12536. }
  12537. load();
  12538. }, 50);
  12539. var autocompleterUiApi = {
  12540. onKeypress: onKeypress,
  12541. cancelIfNecessary: cancelIfNecessary,
  12542. isMenuOpen: isMenuOpen,
  12543. isActive: isActive,
  12544. isProcessingAction: processingAction.get,
  12545. getView: function () {
  12546. return InlineView.getContent(autocompleter);
  12547. }
  12548. };
  12549. if (editor.hasPlugin('rtc') === false) {
  12550. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  12551. }
  12552. };
  12553. var Autocompleter = { register: register$9 };
  12554. var closest = function (scope, selector, isRoot) {
  12555. return closest$1(scope, selector, isRoot).isSome();
  12556. };
  12557. var DelayedFunction = function (fun, delay) {
  12558. var ref = null;
  12559. var schedule = function () {
  12560. var args = [];
  12561. for (var _i = 0; _i < arguments.length; _i++) {
  12562. args[_i] = arguments[_i];
  12563. }
  12564. ref = setTimeout(function () {
  12565. fun.apply(null, args);
  12566. ref = null;
  12567. }, delay);
  12568. };
  12569. var cancel = function () {
  12570. if (ref !== null) {
  12571. clearTimeout(ref);
  12572. ref = null;
  12573. }
  12574. };
  12575. return {
  12576. cancel: cancel,
  12577. schedule: schedule
  12578. };
  12579. };
  12580. var SIGNIFICANT_MOVE = 5;
  12581. var LONGPRESS_DELAY = 400;
  12582. var getTouch = function (event) {
  12583. var raw = event.raw;
  12584. if (raw.touches === undefined || raw.touches.length !== 1) {
  12585. return Optional.none();
  12586. }
  12587. return Optional.some(raw.touches[0]);
  12588. };
  12589. var isFarEnough = function (touch, data) {
  12590. var distX = Math.abs(touch.clientX - data.x);
  12591. var distY = Math.abs(touch.clientY - data.y);
  12592. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  12593. };
  12594. var monitor = function (settings) {
  12595. var startData = value$1();
  12596. var longpressFired = Cell(false);
  12597. var longpress$1 = DelayedFunction(function (event) {
  12598. settings.triggerEvent(longpress(), event);
  12599. longpressFired.set(true);
  12600. }, LONGPRESS_DELAY);
  12601. var handleTouchstart = function (event) {
  12602. getTouch(event).each(function (touch) {
  12603. longpress$1.cancel();
  12604. var data = {
  12605. x: touch.clientX,
  12606. y: touch.clientY,
  12607. target: event.target
  12608. };
  12609. longpress$1.schedule(event);
  12610. longpressFired.set(false);
  12611. startData.set(data);
  12612. });
  12613. return Optional.none();
  12614. };
  12615. var handleTouchmove = function (event) {
  12616. longpress$1.cancel();
  12617. getTouch(event).each(function (touch) {
  12618. startData.on(function (data) {
  12619. if (isFarEnough(touch, data)) {
  12620. startData.clear();
  12621. }
  12622. });
  12623. });
  12624. return Optional.none();
  12625. };
  12626. var handleTouchend = function (event) {
  12627. longpress$1.cancel();
  12628. var isSame = function (data) {
  12629. return eq(data.target, event.target);
  12630. };
  12631. return startData.get().filter(isSame).map(function (_data) {
  12632. if (longpressFired.get()) {
  12633. event.prevent();
  12634. return false;
  12635. } else {
  12636. return settings.triggerEvent(tap(), event);
  12637. }
  12638. });
  12639. };
  12640. var handlers = wrapAll([
  12641. {
  12642. key: touchstart(),
  12643. value: handleTouchstart
  12644. },
  12645. {
  12646. key: touchmove(),
  12647. value: handleTouchmove
  12648. },
  12649. {
  12650. key: touchend(),
  12651. value: handleTouchend
  12652. }
  12653. ]);
  12654. var fireIfReady = function (event, type) {
  12655. return get$e(handlers, type).bind(function (handler) {
  12656. return handler(event);
  12657. });
  12658. };
  12659. return { fireIfReady: fireIfReady };
  12660. };
  12661. var isDangerous = function (event) {
  12662. var keyEv = event.raw;
  12663. return keyEv.which === BACKSPACE[0] && !contains$2([
  12664. 'input',
  12665. 'textarea'
  12666. ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]');
  12667. };
  12668. var isFirefox = function () {
  12669. return detect$1().browser.isFirefox();
  12670. };
  12671. var bindFocus = function (container, handler) {
  12672. if (isFirefox()) {
  12673. return capture(container, 'focus', handler);
  12674. } else {
  12675. return bind(container, 'focusin', handler);
  12676. }
  12677. };
  12678. var bindBlur = function (container, handler) {
  12679. if (isFirefox()) {
  12680. return capture(container, 'blur', handler);
  12681. } else {
  12682. return bind(container, 'focusout', handler);
  12683. }
  12684. };
  12685. var setup$d = function (container, rawSettings) {
  12686. var settings = __assign({ stopBackspace: true }, rawSettings);
  12687. var pointerEvents = [
  12688. 'touchstart',
  12689. 'touchmove',
  12690. 'touchend',
  12691. 'touchcancel',
  12692. 'gesturestart',
  12693. 'mousedown',
  12694. 'mouseup',
  12695. 'mouseover',
  12696. 'mousemove',
  12697. 'mouseout',
  12698. 'click'
  12699. ];
  12700. var tapEvent = monitor(settings);
  12701. var simpleEvents = map$2(pointerEvents.concat([
  12702. 'selectstart',
  12703. 'input',
  12704. 'contextmenu',
  12705. 'change',
  12706. 'transitionend',
  12707. 'transitioncancel',
  12708. 'drag',
  12709. 'dragstart',
  12710. 'dragend',
  12711. 'dragenter',
  12712. 'dragleave',
  12713. 'dragover',
  12714. 'drop',
  12715. 'keyup'
  12716. ]), function (type) {
  12717. return bind(container, type, function (event) {
  12718. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  12719. if (tapStopped) {
  12720. event.kill();
  12721. }
  12722. });
  12723. var stopped = settings.triggerEvent(type, event);
  12724. if (stopped) {
  12725. event.kill();
  12726. }
  12727. });
  12728. });
  12729. var pasteTimeout = value$1();
  12730. var onPaste = bind(container, 'paste', function (event) {
  12731. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  12732. if (tapStopped) {
  12733. event.kill();
  12734. }
  12735. });
  12736. var stopped = settings.triggerEvent('paste', event);
  12737. if (stopped) {
  12738. event.kill();
  12739. }
  12740. pasteTimeout.set(setTimeout(function () {
  12741. settings.triggerEvent(postPaste(), event);
  12742. }, 0));
  12743. });
  12744. var onKeydown = bind(container, 'keydown', function (event) {
  12745. var stopped = settings.triggerEvent('keydown', event);
  12746. if (stopped) {
  12747. event.kill();
  12748. } else if (settings.stopBackspace && isDangerous(event)) {
  12749. event.prevent();
  12750. }
  12751. });
  12752. var onFocusIn = bindFocus(container, function (event) {
  12753. var stopped = settings.triggerEvent('focusin', event);
  12754. if (stopped) {
  12755. event.kill();
  12756. }
  12757. });
  12758. var focusoutTimeout = value$1();
  12759. var onFocusOut = bindBlur(container, function (event) {
  12760. var stopped = settings.triggerEvent('focusout', event);
  12761. if (stopped) {
  12762. event.kill();
  12763. }
  12764. focusoutTimeout.set(setTimeout(function () {
  12765. settings.triggerEvent(postBlur(), event);
  12766. }, 0));
  12767. });
  12768. var unbind = function () {
  12769. each$1(simpleEvents, function (e) {
  12770. e.unbind();
  12771. });
  12772. onKeydown.unbind();
  12773. onFocusIn.unbind();
  12774. onFocusOut.unbind();
  12775. onPaste.unbind();
  12776. pasteTimeout.on(clearTimeout);
  12777. focusoutTimeout.on(clearTimeout);
  12778. };
  12779. return { unbind: unbind };
  12780. };
  12781. var derive = function (rawEvent, rawTarget) {
  12782. var source = get$e(rawEvent, 'target').getOr(rawTarget);
  12783. return Cell(source);
  12784. };
  12785. var fromSource = function (event, source) {
  12786. var stopper = Cell(false);
  12787. var cutter = Cell(false);
  12788. var stop = function () {
  12789. stopper.set(true);
  12790. };
  12791. var cut = function () {
  12792. cutter.set(true);
  12793. };
  12794. return {
  12795. stop: stop,
  12796. cut: cut,
  12797. isStopped: stopper.get,
  12798. isCut: cutter.get,
  12799. event: event,
  12800. setSource: source.set,
  12801. getSource: source.get
  12802. };
  12803. };
  12804. var fromExternal = function (event) {
  12805. var stopper = Cell(false);
  12806. var stop = function () {
  12807. stopper.set(true);
  12808. };
  12809. return {
  12810. stop: stop,
  12811. cut: noop,
  12812. isStopped: stopper.get,
  12813. isCut: never,
  12814. event: event,
  12815. setSource: die('Cannot set source of a broadcasted event'),
  12816. getSource: die('Cannot get source of a broadcasted event')
  12817. };
  12818. };
  12819. var adt$1 = Adt.generate([
  12820. { stopped: [] },
  12821. { resume: ['element'] },
  12822. { complete: [] }
  12823. ]);
  12824. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  12825. var handler = lookup(eventType, target);
  12826. var simulatedEvent = fromSource(rawEvent, source);
  12827. return handler.fold(function () {
  12828. logger.logEventNoHandlers(eventType, target);
  12829. return adt$1.complete();
  12830. }, function (handlerInfo) {
  12831. var descHandler = handlerInfo.descHandler;
  12832. var eventHandler = getCurried(descHandler);
  12833. eventHandler(simulatedEvent);
  12834. if (simulatedEvent.isStopped()) {
  12835. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  12836. return adt$1.stopped();
  12837. } else if (simulatedEvent.isCut()) {
  12838. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  12839. return adt$1.complete();
  12840. } else {
  12841. return parent(handlerInfo.element).fold(function () {
  12842. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  12843. return adt$1.complete();
  12844. }, function (parent) {
  12845. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  12846. return adt$1.resume(parent);
  12847. });
  12848. }
  12849. });
  12850. };
  12851. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12852. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  12853. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12854. }, never);
  12855. };
  12856. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12857. var source = derive(rawEvent, target);
  12858. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12859. };
  12860. var broadcast = function (listeners, rawEvent, _logger) {
  12861. var simulatedEvent = fromExternal(rawEvent);
  12862. each$1(listeners, function (listener) {
  12863. var descHandler = listener.descHandler;
  12864. var handler = getCurried(descHandler);
  12865. handler(simulatedEvent);
  12866. });
  12867. return simulatedEvent.isStopped();
  12868. };
  12869. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12870. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  12871. };
  12872. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12873. var source = derive(rawEvent, rawTarget);
  12874. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12875. };
  12876. var eventHandler = function (element, descHandler) {
  12877. return {
  12878. element: element,
  12879. descHandler: descHandler
  12880. };
  12881. };
  12882. var broadcastHandler = function (id, handler) {
  12883. return {
  12884. id: id,
  12885. descHandler: handler
  12886. };
  12887. };
  12888. var EventRegistry = function () {
  12889. var registry = {};
  12890. var registerId = function (extraArgs, id, events) {
  12891. each(events, function (v, k) {
  12892. var handlers = registry[k] !== undefined ? registry[k] : {};
  12893. handlers[id] = curryArgs(v, extraArgs);
  12894. registry[k] = handlers;
  12895. });
  12896. };
  12897. var findHandler = function (handlers, elem) {
  12898. return read$1(elem).bind(function (id) {
  12899. return get$e(handlers, id);
  12900. }).map(function (descHandler) {
  12901. return eventHandler(elem, descHandler);
  12902. });
  12903. };
  12904. var filterByType = function (type) {
  12905. return get$e(registry, type).map(function (handlers) {
  12906. return mapToArray(handlers, function (f, id) {
  12907. return broadcastHandler(id, f);
  12908. });
  12909. }).getOr([]);
  12910. };
  12911. var find = function (isAboveRoot, type, target) {
  12912. return get$e(registry, type).bind(function (handlers) {
  12913. return closest$4(target, function (elem) {
  12914. return findHandler(handlers, elem);
  12915. }, isAboveRoot);
  12916. });
  12917. };
  12918. var unregisterId = function (id) {
  12919. each(registry, function (handlersById, _eventName) {
  12920. if (has$2(handlersById, id)) {
  12921. delete handlersById[id];
  12922. }
  12923. });
  12924. };
  12925. return {
  12926. registerId: registerId,
  12927. unregisterId: unregisterId,
  12928. filterByType: filterByType,
  12929. find: find
  12930. };
  12931. };
  12932. var Registry = function () {
  12933. var events = EventRegistry();
  12934. var components = {};
  12935. var readOrTag = function (component) {
  12936. var elem = component.element;
  12937. return read$1(elem).getOrThunk(function () {
  12938. return write('uid-', component.element);
  12939. });
  12940. };
  12941. var failOnDuplicate = function (component, tagId) {
  12942. var conflict = components[tagId];
  12943. if (conflict === component) {
  12944. unregister(component);
  12945. } else {
  12946. 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');
  12947. }
  12948. };
  12949. var register = function (component) {
  12950. var tagId = readOrTag(component);
  12951. if (hasNonNullableKey(components, tagId)) {
  12952. failOnDuplicate(component, tagId);
  12953. }
  12954. var extraArgs = [component];
  12955. events.registerId(extraArgs, tagId, component.events);
  12956. components[tagId] = component;
  12957. };
  12958. var unregister = function (component) {
  12959. read$1(component.element).each(function (tagId) {
  12960. delete components[tagId];
  12961. events.unregisterId(tagId);
  12962. });
  12963. };
  12964. var filter = function (type) {
  12965. return events.filterByType(type);
  12966. };
  12967. var find = function (isAboveRoot, type, target) {
  12968. return events.find(isAboveRoot, type, target);
  12969. };
  12970. var getById = function (id) {
  12971. return get$e(components, id);
  12972. };
  12973. return {
  12974. find: find,
  12975. filter: filter,
  12976. register: register,
  12977. unregister: unregister,
  12978. getById: getById
  12979. };
  12980. };
  12981. var factory$j = function (detail) {
  12982. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12983. return {
  12984. uid: detail.uid,
  12985. dom: __assign({
  12986. tag: 'div',
  12987. attributes: __assign({ role: 'presentation' }, attributes)
  12988. }, domWithoutAttributes),
  12989. components: detail.components,
  12990. behaviours: get$2(detail.containerBehaviours),
  12991. events: detail.events,
  12992. domModification: detail.domModification,
  12993. eventOrder: detail.eventOrder
  12994. };
  12995. };
  12996. var Container = single({
  12997. name: 'Container',
  12998. factory: factory$j,
  12999. configFields: [
  13000. defaulted('components', []),
  13001. field('containerBehaviours', []),
  13002. defaulted('events', {}),
  13003. defaulted('domModification', {}),
  13004. defaulted('eventOrder', {})
  13005. ]
  13006. });
  13007. var takeover = function (root) {
  13008. var isAboveRoot = function (el) {
  13009. return parent(root.element).fold(always, function (parent) {
  13010. return eq(el, parent);
  13011. });
  13012. };
  13013. var registry = Registry();
  13014. var lookup = function (eventName, target) {
  13015. return registry.find(isAboveRoot, eventName, target);
  13016. };
  13017. var domEvents = setup$d(root.element, {
  13018. triggerEvent: function (eventName, event) {
  13019. return monitorEvent(eventName, event.target, function (logger) {
  13020. return triggerUntilStopped(lookup, eventName, event, logger);
  13021. });
  13022. }
  13023. });
  13024. var systemApi = {
  13025. debugInfo: constant$1('real'),
  13026. triggerEvent: function (eventName, target, data) {
  13027. monitorEvent(eventName, target, function (logger) {
  13028. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  13029. });
  13030. },
  13031. triggerFocus: function (target, originator) {
  13032. read$1(target).fold(function () {
  13033. focus$3(target);
  13034. }, function (_alloyId) {
  13035. monitorEvent(focus$4(), target, function (logger) {
  13036. triggerHandler(lookup, focus$4(), {
  13037. originator: originator,
  13038. kill: noop,
  13039. prevent: noop,
  13040. target: target
  13041. }, target, logger);
  13042. return false;
  13043. });
  13044. });
  13045. },
  13046. triggerEscape: function (comp, simulatedEvent) {
  13047. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  13048. },
  13049. getByUid: function (uid) {
  13050. return getByUid(uid);
  13051. },
  13052. getByDom: function (elem) {
  13053. return getByDom(elem);
  13054. },
  13055. build: build$1,
  13056. addToGui: function (c) {
  13057. add(c);
  13058. },
  13059. removeFromGui: function (c) {
  13060. remove(c);
  13061. },
  13062. addToWorld: function (c) {
  13063. addToWorld(c);
  13064. },
  13065. removeFromWorld: function (c) {
  13066. removeFromWorld(c);
  13067. },
  13068. broadcast: function (message) {
  13069. broadcast$1(message);
  13070. },
  13071. broadcastOn: function (channels, message) {
  13072. broadcastOn(channels, message);
  13073. },
  13074. broadcastEvent: function (eventName, event) {
  13075. broadcastEvent(eventName, event);
  13076. },
  13077. isConnected: always
  13078. };
  13079. var addToWorld = function (component) {
  13080. component.connect(systemApi);
  13081. if (!isText$1(component.element)) {
  13082. registry.register(component);
  13083. each$1(component.components(), addToWorld);
  13084. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  13085. }
  13086. };
  13087. var removeFromWorld = function (component) {
  13088. if (!isText$1(component.element)) {
  13089. each$1(component.components(), removeFromWorld);
  13090. registry.unregister(component);
  13091. }
  13092. component.disconnect();
  13093. };
  13094. var add = function (component) {
  13095. attach(root, component);
  13096. };
  13097. var remove = function (component) {
  13098. detach(component);
  13099. };
  13100. var destroy = function () {
  13101. domEvents.unbind();
  13102. remove$5(root.element);
  13103. };
  13104. var broadcastData = function (data) {
  13105. var receivers = registry.filter(receive());
  13106. each$1(receivers, function (receiver) {
  13107. var descHandler = receiver.descHandler;
  13108. var handler = getCurried(descHandler);
  13109. handler(data);
  13110. });
  13111. };
  13112. var broadcast$1 = function (message) {
  13113. broadcastData({
  13114. universal: true,
  13115. data: message
  13116. });
  13117. };
  13118. var broadcastOn = function (channels, message) {
  13119. broadcastData({
  13120. universal: false,
  13121. channels: channels,
  13122. data: message
  13123. });
  13124. };
  13125. var broadcastEvent = function (eventName, event) {
  13126. var listeners = registry.filter(eventName);
  13127. return broadcast(listeners, event);
  13128. };
  13129. var getByUid = function (uid) {
  13130. return registry.getById(uid).fold(function () {
  13131. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  13132. }, Result.value);
  13133. };
  13134. var getByDom = function (elem) {
  13135. var uid = read$1(elem).getOr('not found');
  13136. return getByUid(uid);
  13137. };
  13138. addToWorld(root);
  13139. return {
  13140. root: root,
  13141. element: root.element,
  13142. destroy: destroy,
  13143. add: add,
  13144. remove: remove,
  13145. getByUid: getByUid,
  13146. getByDom: getByDom,
  13147. addToWorld: addToWorld,
  13148. removeFromWorld: removeFromWorld,
  13149. broadcast: broadcast$1,
  13150. broadcastOn: broadcastOn,
  13151. broadcastEvent: broadcastEvent
  13152. };
  13153. };
  13154. var renderBar = function (spec, backstage) {
  13155. return {
  13156. dom: {
  13157. tag: 'div',
  13158. classes: [
  13159. 'tox-bar',
  13160. 'tox-form__controls-h-stack'
  13161. ]
  13162. },
  13163. components: map$2(spec.items, backstage.interpreter)
  13164. };
  13165. };
  13166. var schema$l = constant$1([
  13167. defaulted('prefix', 'form-field'),
  13168. field('fieldBehaviours', [
  13169. Composing,
  13170. Representing
  13171. ])
  13172. ]);
  13173. var parts$e = constant$1([
  13174. optional({
  13175. schema: [required$1('dom')],
  13176. name: 'label'
  13177. }),
  13178. optional({
  13179. factory: {
  13180. sketch: function (spec) {
  13181. return {
  13182. uid: spec.uid,
  13183. dom: {
  13184. tag: 'span',
  13185. styles: { display: 'none' },
  13186. attributes: { 'aria-hidden': 'true' },
  13187. innerHtml: spec.text
  13188. }
  13189. };
  13190. }
  13191. },
  13192. schema: [required$1('text')],
  13193. name: 'aria-descriptor'
  13194. }),
  13195. required({
  13196. factory: {
  13197. sketch: function (spec) {
  13198. var excludeFactory = exclude(spec, ['factory']);
  13199. return spec.factory.sketch(excludeFactory);
  13200. }
  13201. },
  13202. schema: [required$1('factory')],
  13203. name: 'field'
  13204. })
  13205. ]);
  13206. var factory$i = function (detail, components, _spec, _externals) {
  13207. var behaviours = augment(detail.fieldBehaviours, [
  13208. Composing.config({
  13209. find: function (container) {
  13210. return getPart(container, detail, 'field');
  13211. }
  13212. }),
  13213. Representing.config({
  13214. store: {
  13215. mode: 'manual',
  13216. getValue: function (field) {
  13217. return Composing.getCurrent(field).bind(Representing.getValue);
  13218. },
  13219. setValue: function (field, value) {
  13220. Composing.getCurrent(field).each(function (current) {
  13221. Representing.setValue(current, value);
  13222. });
  13223. }
  13224. }
  13225. })
  13226. ]);
  13227. var events = derive$2([runOnAttached(function (component, _simulatedEvent) {
  13228. var ps = getParts(component, detail, [
  13229. 'label',
  13230. 'field',
  13231. 'aria-descriptor'
  13232. ]);
  13233. ps.field().each(function (field) {
  13234. var id = generate$6(detail.prefix);
  13235. ps.label().each(function (label) {
  13236. set$8(label.element, 'for', id);
  13237. set$8(field.element, 'id', id);
  13238. });
  13239. ps['aria-descriptor']().each(function (descriptor) {
  13240. var descriptorId = generate$6(detail.prefix);
  13241. set$8(descriptor.element, 'id', descriptorId);
  13242. set$8(field.element, 'aria-describedby', descriptorId);
  13243. });
  13244. });
  13245. })]);
  13246. var apis = {
  13247. getField: function (container) {
  13248. return getPart(container, detail, 'field');
  13249. },
  13250. getLabel: function (container) {
  13251. return getPart(container, detail, 'label');
  13252. }
  13253. };
  13254. return {
  13255. uid: detail.uid,
  13256. dom: detail.dom,
  13257. components: components,
  13258. behaviours: behaviours,
  13259. events: events,
  13260. apis: apis
  13261. };
  13262. };
  13263. var FormField = composite({
  13264. name: 'FormField',
  13265. configFields: schema$l(),
  13266. partFields: parts$e(),
  13267. factory: factory$i,
  13268. apis: {
  13269. getField: function (apis, comp) {
  13270. return apis.getField(comp);
  13271. },
  13272. getLabel: function (apis, comp) {
  13273. return apis.getLabel(comp);
  13274. }
  13275. }
  13276. });
  13277. var exhibit$2 = function (base, tabConfig) {
  13278. return nu$7({
  13279. attributes: wrapAll([{
  13280. key: tabConfig.tabAttr,
  13281. value: 'true'
  13282. }])
  13283. });
  13284. };
  13285. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  13286. __proto__: null,
  13287. exhibit: exhibit$2
  13288. });
  13289. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  13290. var Tabstopping = create$7({
  13291. fields: TabstopSchema,
  13292. name: 'tabstopping',
  13293. active: ActiveTabstopping
  13294. });
  13295. var global$7 = tinymce.util.Tools.resolve('tinymce.html.Entities');
  13296. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13297. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  13298. return FormField.sketch(spec);
  13299. };
  13300. var renderFormField = function (pLabel, pField) {
  13301. return renderFormFieldWith(pLabel, pField, [], []);
  13302. };
  13303. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13304. return {
  13305. dom: renderFormFieldDomWith(extraClasses),
  13306. components: pLabel.toArray().concat([pField]),
  13307. fieldBehaviours: derive$1(extraBehaviours)
  13308. };
  13309. };
  13310. var renderFormFieldDom = function () {
  13311. return renderFormFieldDomWith([]);
  13312. };
  13313. var renderFormFieldDomWith = function (extraClasses) {
  13314. return {
  13315. tag: 'div',
  13316. classes: ['tox-form__group'].concat(extraClasses)
  13317. };
  13318. };
  13319. var renderLabel$2 = function (label, providersBackstage) {
  13320. return FormField.parts.label({
  13321. dom: {
  13322. tag: 'label',
  13323. classes: ['tox-label'],
  13324. innerHtml: providersBackstage.translate(label)
  13325. }
  13326. });
  13327. };
  13328. var formChangeEvent = generate$6('form-component-change');
  13329. var formCloseEvent = generate$6('form-close');
  13330. var formCancelEvent = generate$6('form-cancel');
  13331. var formActionEvent = generate$6('form-action');
  13332. var formSubmitEvent = generate$6('form-submit');
  13333. var formBlockEvent = generate$6('form-block');
  13334. var formUnblockEvent = generate$6('form-unblock');
  13335. var formTabChangeEvent = generate$6('form-tabchange');
  13336. var formResizeEvent = generate$6('form-resize');
  13337. var renderCollection = function (spec, providersBackstage) {
  13338. var _a;
  13339. var pLabel = spec.label.map(function (label) {
  13340. return renderLabel$2(label, providersBackstage);
  13341. });
  13342. var runOnItem = function (f) {
  13343. return function (comp, se) {
  13344. closest$1(se.event.target, '[data-collection-item-value]').each(function (target) {
  13345. f(comp, se, target, get$d(target, 'data-collection-item-value'));
  13346. });
  13347. };
  13348. };
  13349. var setContents = function (comp, items) {
  13350. var htmlLines = map$2(items, function (item) {
  13351. var itemText = global$e.translate(item.text);
  13352. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  13353. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  13354. var mapItemName = {
  13355. '_': ' ',
  13356. ' - ': ' ',
  13357. '-': ' '
  13358. };
  13359. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  13360. return mapItemName[match];
  13361. });
  13362. var disabledClass = providersBackstage.isDisabled() ? ' tox-collection__item--state-disabled' : '';
  13363. return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$7.encodeAllRaw(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  13364. });
  13365. var chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines];
  13366. var html = map$2(chunks, function (ch) {
  13367. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  13368. });
  13369. set$5(comp.element, html.join(''));
  13370. };
  13371. var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  13372. se.stop();
  13373. if (!providersBackstage.isDisabled()) {
  13374. emitWith(comp, formActionEvent, {
  13375. name: spec.name,
  13376. value: itemValue
  13377. });
  13378. }
  13379. });
  13380. var collectionEvents = [
  13381. run$1(mouseover(), runOnItem(function (comp, se, tgt) {
  13382. focus$3(tgt);
  13383. })),
  13384. run$1(click(), onClick),
  13385. run$1(tap(), onClick),
  13386. run$1(focusin(), runOnItem(function (comp, se, tgt) {
  13387. descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  13388. remove$2(currentActive, activeClass);
  13389. });
  13390. add$2(tgt, activeClass);
  13391. })),
  13392. run$1(focusout(), runOnItem(function (comp) {
  13393. descendant(comp.element, '.' + activeClass).each(function (currentActive) {
  13394. remove$2(currentActive, activeClass);
  13395. });
  13396. })),
  13397. runOnExecute$1(runOnItem(function (comp, se, tgt, itemValue) {
  13398. emitWith(comp, formActionEvent, {
  13399. name: spec.name,
  13400. value: itemValue
  13401. });
  13402. }))
  13403. ];
  13404. var iterCollectionItems = function (comp, applyAttributes) {
  13405. return map$2(descendants(comp.element, '.tox-collection__item'), applyAttributes);
  13406. };
  13407. var pField = FormField.parts.field({
  13408. dom: {
  13409. tag: 'div',
  13410. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  13411. },
  13412. components: [],
  13413. factory: { sketch: identity$1 },
  13414. behaviours: derive$1([
  13415. Disabling.config({
  13416. disabled: providersBackstage.isDisabled,
  13417. onDisabled: function (comp) {
  13418. iterCollectionItems(comp, function (childElm) {
  13419. add$2(childElm, 'tox-collection__item--state-disabled');
  13420. set$8(childElm, 'aria-disabled', true);
  13421. });
  13422. },
  13423. onEnabled: function (comp) {
  13424. iterCollectionItems(comp, function (childElm) {
  13425. remove$2(childElm, 'tox-collection__item--state-disabled');
  13426. remove$7(childElm, 'aria-disabled');
  13427. });
  13428. }
  13429. }),
  13430. receivingConfig(),
  13431. Replacing.config({}),
  13432. Representing.config({
  13433. store: {
  13434. mode: 'memory',
  13435. initialValue: []
  13436. },
  13437. onSetValue: function (comp, items) {
  13438. setContents(comp, items);
  13439. if (spec.columns === 'auto') {
  13440. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  13441. var numRows = _a.numRows, numColumns = _a.numColumns;
  13442. Keying.setGridSize(comp, numRows, numColumns);
  13443. });
  13444. }
  13445. emit(comp, formResizeEvent);
  13446. }
  13447. }),
  13448. Tabstopping.config({}),
  13449. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  13450. config('collection-events', collectionEvents)
  13451. ]),
  13452. eventOrder: (_a = {}, _a[execute$5()] = [
  13453. 'disabling',
  13454. 'alloy.base.behaviour',
  13455. 'collection-events'
  13456. ], _a)
  13457. });
  13458. var extraClasses = ['tox-form__group--collection'];
  13459. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  13460. };
  13461. var schema$k = constant$1([
  13462. option('data'),
  13463. defaulted('inputAttributes', {}),
  13464. defaulted('inputStyles', {}),
  13465. defaulted('tag', 'input'),
  13466. defaulted('inputClasses', []),
  13467. onHandler('onSetValue'),
  13468. defaulted('styles', {}),
  13469. defaulted('eventOrder', {}),
  13470. field('inputBehaviours', [
  13471. Representing,
  13472. Focusing
  13473. ]),
  13474. defaulted('selectOnFocus', true)
  13475. ]);
  13476. var focusBehaviours = function (detail) {
  13477. return derive$1([Focusing.config({
  13478. onFocus: !detail.selectOnFocus ? noop : function (component) {
  13479. var input = component.element;
  13480. var value = get$5(input);
  13481. input.dom.setSelectionRange(0, value.length);
  13482. }
  13483. })]);
  13484. };
  13485. var behaviours = function (detail) {
  13486. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  13487. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  13488. return { initialValue: data };
  13489. }).getOr({})), {
  13490. getValue: function (input) {
  13491. return get$5(input.element);
  13492. },
  13493. setValue: function (input, data) {
  13494. var current = get$5(input.element);
  13495. if (current !== data) {
  13496. set$4(input.element, data);
  13497. }
  13498. }
  13499. }),
  13500. onSetValue: detail.onSetValue
  13501. })]));
  13502. };
  13503. var dom = function (detail) {
  13504. return {
  13505. tag: detail.tag,
  13506. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  13507. styles: detail.inputStyles,
  13508. classes: detail.inputClasses
  13509. };
  13510. };
  13511. var factory$h = function (detail, _spec) {
  13512. return {
  13513. uid: detail.uid,
  13514. dom: dom(detail),
  13515. components: [],
  13516. behaviours: behaviours(detail),
  13517. eventOrder: detail.eventOrder
  13518. };
  13519. };
  13520. var Input = single({
  13521. name: 'Input',
  13522. configFields: schema$k(),
  13523. factory: factory$h
  13524. });
  13525. var exports$1 = {}, module = { exports: exports$1 };
  13526. (function (define, exports, module, require) {
  13527. (function (global, factory) {
  13528. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  13529. }(this, function () {
  13530. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  13531. var promise = { exports: {} };
  13532. (function (module) {
  13533. (function (root) {
  13534. var setTimeoutFunc = setTimeout;
  13535. function noop() {
  13536. }
  13537. function bind(fn, thisArg) {
  13538. return function () {
  13539. fn.apply(thisArg, arguments);
  13540. };
  13541. }
  13542. function Promise(fn) {
  13543. if (typeof this !== 'object')
  13544. throw new TypeError('Promises must be constructed via new');
  13545. if (typeof fn !== 'function')
  13546. throw new TypeError('not a function');
  13547. this._state = 0;
  13548. this._handled = false;
  13549. this._value = undefined;
  13550. this._deferreds = [];
  13551. doResolve(fn, this);
  13552. }
  13553. function handle(self, deferred) {
  13554. while (self._state === 3) {
  13555. self = self._value;
  13556. }
  13557. if (self._state === 0) {
  13558. self._deferreds.push(deferred);
  13559. return;
  13560. }
  13561. self._handled = true;
  13562. Promise._immediateFn(function () {
  13563. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  13564. if (cb === null) {
  13565. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  13566. return;
  13567. }
  13568. var ret;
  13569. try {
  13570. ret = cb(self._value);
  13571. } catch (e) {
  13572. reject(deferred.promise, e);
  13573. return;
  13574. }
  13575. resolve(deferred.promise, ret);
  13576. });
  13577. }
  13578. function resolve(self, newValue) {
  13579. try {
  13580. if (newValue === self)
  13581. throw new TypeError('A promise cannot be resolved with itself.');
  13582. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  13583. var then = newValue.then;
  13584. if (newValue instanceof Promise) {
  13585. self._state = 3;
  13586. self._value = newValue;
  13587. finale(self);
  13588. return;
  13589. } else if (typeof then === 'function') {
  13590. doResolve(bind(then, newValue), self);
  13591. return;
  13592. }
  13593. }
  13594. self._state = 1;
  13595. self._value = newValue;
  13596. finale(self);
  13597. } catch (e) {
  13598. reject(self, e);
  13599. }
  13600. }
  13601. function reject(self, newValue) {
  13602. self._state = 2;
  13603. self._value = newValue;
  13604. finale(self);
  13605. }
  13606. function finale(self) {
  13607. if (self._state === 2 && self._deferreds.length === 0) {
  13608. Promise._immediateFn(function () {
  13609. if (!self._handled) {
  13610. Promise._unhandledRejectionFn(self._value);
  13611. }
  13612. });
  13613. }
  13614. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  13615. handle(self, self._deferreds[i]);
  13616. }
  13617. self._deferreds = null;
  13618. }
  13619. function Handler(onFulfilled, onRejected, promise) {
  13620. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  13621. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  13622. this.promise = promise;
  13623. }
  13624. function doResolve(fn, self) {
  13625. var done = false;
  13626. try {
  13627. fn(function (value) {
  13628. if (done)
  13629. return;
  13630. done = true;
  13631. resolve(self, value);
  13632. }, function (reason) {
  13633. if (done)
  13634. return;
  13635. done = true;
  13636. reject(self, reason);
  13637. });
  13638. } catch (ex) {
  13639. if (done)
  13640. return;
  13641. done = true;
  13642. reject(self, ex);
  13643. }
  13644. }
  13645. Promise.prototype['catch'] = function (onRejected) {
  13646. return this.then(null, onRejected);
  13647. };
  13648. Promise.prototype.then = function (onFulfilled, onRejected) {
  13649. var prom = new this.constructor(noop);
  13650. handle(this, new Handler(onFulfilled, onRejected, prom));
  13651. return prom;
  13652. };
  13653. Promise.all = function (arr) {
  13654. var args = Array.prototype.slice.call(arr);
  13655. return new Promise(function (resolve, reject) {
  13656. if (args.length === 0)
  13657. return resolve([]);
  13658. var remaining = args.length;
  13659. function res(i, val) {
  13660. try {
  13661. if (val && (typeof val === 'object' || typeof val === 'function')) {
  13662. var then = val.then;
  13663. if (typeof then === 'function') {
  13664. then.call(val, function (val) {
  13665. res(i, val);
  13666. }, reject);
  13667. return;
  13668. }
  13669. }
  13670. args[i] = val;
  13671. if (--remaining === 0) {
  13672. resolve(args);
  13673. }
  13674. } catch (ex) {
  13675. reject(ex);
  13676. }
  13677. }
  13678. for (var i = 0; i < args.length; i++) {
  13679. res(i, args[i]);
  13680. }
  13681. });
  13682. };
  13683. Promise.resolve = function (value) {
  13684. if (value && typeof value === 'object' && value.constructor === Promise) {
  13685. return value;
  13686. }
  13687. return new Promise(function (resolve) {
  13688. resolve(value);
  13689. });
  13690. };
  13691. Promise.reject = function (value) {
  13692. return new Promise(function (resolve, reject) {
  13693. reject(value);
  13694. });
  13695. };
  13696. Promise.race = function (values) {
  13697. return new Promise(function (resolve, reject) {
  13698. for (var i = 0, len = values.length; i < len; i++) {
  13699. values[i].then(resolve, reject);
  13700. }
  13701. });
  13702. };
  13703. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  13704. setImmediate(fn);
  13705. } : function (fn) {
  13706. setTimeoutFunc(fn, 0);
  13707. };
  13708. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  13709. if (typeof console !== 'undefined' && console) {
  13710. console.warn('Possible Unhandled Promise Rejection:', err);
  13711. }
  13712. };
  13713. Promise._setImmediateFn = function _setImmediateFn(fn) {
  13714. Promise._immediateFn = fn;
  13715. };
  13716. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  13717. Promise._unhandledRejectionFn = fn;
  13718. };
  13719. if (module.exports) {
  13720. module.exports = Promise;
  13721. } else if (!root.Promise) {
  13722. root.Promise = Promise;
  13723. }
  13724. }(commonjsGlobal));
  13725. }(promise));
  13726. var promisePolyfill = promise.exports;
  13727. var Global = function () {
  13728. if (typeof window !== 'undefined') {
  13729. return window;
  13730. } else {
  13731. return Function('return this;')();
  13732. }
  13733. }();
  13734. var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  13735. return promisePolyfill_1;
  13736. }));
  13737. }(undefined, exports$1, module));
  13738. var Promise$1 = module.exports.boltExport;
  13739. var nu$3 = function (baseFn) {
  13740. var data = Optional.none();
  13741. var callbacks = [];
  13742. var map = function (f) {
  13743. return nu$3(function (nCallback) {
  13744. get(function (data) {
  13745. nCallback(f(data));
  13746. });
  13747. });
  13748. };
  13749. var get = function (nCallback) {
  13750. if (isReady()) {
  13751. call(nCallback);
  13752. } else {
  13753. callbacks.push(nCallback);
  13754. }
  13755. };
  13756. var set = function (x) {
  13757. if (!isReady()) {
  13758. data = Optional.some(x);
  13759. run(callbacks);
  13760. callbacks = [];
  13761. }
  13762. };
  13763. var isReady = function () {
  13764. return data.isSome();
  13765. };
  13766. var run = function (cbs) {
  13767. each$1(cbs, call);
  13768. };
  13769. var call = function (cb) {
  13770. data.each(function (x) {
  13771. setTimeout(function () {
  13772. cb(x);
  13773. }, 0);
  13774. });
  13775. };
  13776. baseFn(set);
  13777. return {
  13778. get: get,
  13779. map: map,
  13780. isReady: isReady
  13781. };
  13782. };
  13783. var pure$1 = function (a) {
  13784. return nu$3(function (callback) {
  13785. callback(a);
  13786. });
  13787. };
  13788. var LazyValue = {
  13789. nu: nu$3,
  13790. pure: pure$1
  13791. };
  13792. var errorReporter = function (err) {
  13793. setTimeout(function () {
  13794. throw err;
  13795. }, 0);
  13796. };
  13797. var make$5 = function (run) {
  13798. var get = function (callback) {
  13799. run().then(callback, errorReporter);
  13800. };
  13801. var map = function (fab) {
  13802. return make$5(function () {
  13803. return run().then(fab);
  13804. });
  13805. };
  13806. var bind = function (aFutureB) {
  13807. return make$5(function () {
  13808. return run().then(function (v) {
  13809. return aFutureB(v).toPromise();
  13810. });
  13811. });
  13812. };
  13813. var anonBind = function (futureB) {
  13814. return make$5(function () {
  13815. return run().then(function () {
  13816. return futureB.toPromise();
  13817. });
  13818. });
  13819. };
  13820. var toLazy = function () {
  13821. return LazyValue.nu(get);
  13822. };
  13823. var toCached = function () {
  13824. var cache = null;
  13825. return make$5(function () {
  13826. if (cache === null) {
  13827. cache = run();
  13828. }
  13829. return cache;
  13830. });
  13831. };
  13832. var toPromise = run;
  13833. return {
  13834. map: map,
  13835. bind: bind,
  13836. anonBind: anonBind,
  13837. toLazy: toLazy,
  13838. toCached: toCached,
  13839. toPromise: toPromise,
  13840. get: get
  13841. };
  13842. };
  13843. var nu$2 = function (baseFn) {
  13844. return make$5(function () {
  13845. return new Promise$1(baseFn);
  13846. });
  13847. };
  13848. var pure = function (a) {
  13849. return make$5(function () {
  13850. return Promise$1.resolve(a);
  13851. });
  13852. };
  13853. var Future = {
  13854. nu: nu$2,
  13855. pure: pure
  13856. };
  13857. var ariaElements = [
  13858. 'input',
  13859. 'textarea'
  13860. ];
  13861. var isAriaElement = function (elem) {
  13862. var name = name$2(elem);
  13863. return contains$2(ariaElements, name);
  13864. };
  13865. var markValid = function (component, invalidConfig) {
  13866. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13867. remove$2(elem, invalidConfig.invalidClass);
  13868. invalidConfig.notify.each(function (notifyInfo) {
  13869. if (isAriaElement(component.element)) {
  13870. set$8(component.element, 'aria-invalid', false);
  13871. }
  13872. notifyInfo.getContainer(component).each(function (container) {
  13873. set$5(container, notifyInfo.validHtml);
  13874. });
  13875. notifyInfo.onValid(component);
  13876. });
  13877. };
  13878. var markInvalid = function (component, invalidConfig, invalidState, text) {
  13879. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13880. add$2(elem, invalidConfig.invalidClass);
  13881. invalidConfig.notify.each(function (notifyInfo) {
  13882. if (isAriaElement(component.element)) {
  13883. set$8(component.element, 'aria-invalid', true);
  13884. }
  13885. notifyInfo.getContainer(component).each(function (container) {
  13886. set$5(container, text);
  13887. });
  13888. notifyInfo.onInvalid(component, text);
  13889. });
  13890. };
  13891. var query = function (component, invalidConfig, _invalidState) {
  13892. return invalidConfig.validator.fold(function () {
  13893. return Future.pure(Result.value(true));
  13894. }, function (validatorInfo) {
  13895. return validatorInfo.validate(component);
  13896. });
  13897. };
  13898. var run = function (component, invalidConfig, invalidState) {
  13899. invalidConfig.notify.each(function (notifyInfo) {
  13900. notifyInfo.onValidate(component);
  13901. });
  13902. return query(component, invalidConfig).map(function (valid) {
  13903. if (component.getSystem().isConnected()) {
  13904. return valid.fold(function (err) {
  13905. markInvalid(component, invalidConfig, invalidState, err);
  13906. return Result.error(err);
  13907. }, function (v) {
  13908. markValid(component, invalidConfig);
  13909. return Result.value(v);
  13910. });
  13911. } else {
  13912. return Result.error('No longer in system');
  13913. }
  13914. });
  13915. };
  13916. var isInvalid = function (component, invalidConfig) {
  13917. var elem = invalidConfig.getRoot(component).getOr(component.element);
  13918. return has(elem, invalidConfig.invalidClass);
  13919. };
  13920. var InvalidateApis = /*#__PURE__*/Object.freeze({
  13921. __proto__: null,
  13922. markValid: markValid,
  13923. markInvalid: markInvalid,
  13924. query: query,
  13925. run: run,
  13926. isInvalid: isInvalid
  13927. });
  13928. var events$8 = function (invalidConfig, invalidState) {
  13929. return invalidConfig.validator.map(function (validatorInfo) {
  13930. return derive$2([run$1(validatorInfo.onEvent, function (component) {
  13931. run(component, invalidConfig, invalidState).get(identity$1);
  13932. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  13933. run(component, invalidConfig, invalidState).get(noop);
  13934. })] : []));
  13935. }).getOr({});
  13936. };
  13937. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  13938. __proto__: null,
  13939. events: events$8
  13940. });
  13941. var InvalidateSchema = [
  13942. required$1('invalidClass'),
  13943. defaulted('getRoot', Optional.none),
  13944. optionObjOf('notify', [
  13945. defaulted('aria', 'alert'),
  13946. defaulted('getContainer', Optional.none),
  13947. defaulted('validHtml', ''),
  13948. onHandler('onValid'),
  13949. onHandler('onInvalid'),
  13950. onHandler('onValidate')
  13951. ]),
  13952. optionObjOf('validator', [
  13953. required$1('validate'),
  13954. defaulted('onEvent', 'input'),
  13955. defaulted('validateOnLoad', true)
  13956. ])
  13957. ];
  13958. var Invalidating = create$7({
  13959. fields: InvalidateSchema,
  13960. name: 'invalidating',
  13961. active: ActiveInvalidate,
  13962. apis: InvalidateApis,
  13963. extra: {
  13964. validation: function (validator) {
  13965. return function (component) {
  13966. var v = Representing.getValue(component);
  13967. return Future.pure(validator(v));
  13968. };
  13969. }
  13970. }
  13971. });
  13972. var getCoupled = function (component, coupleConfig, coupleState, name) {
  13973. return coupleState.getOrCreate(component, coupleConfig, name);
  13974. };
  13975. var CouplingApis = /*#__PURE__*/Object.freeze({
  13976. __proto__: null,
  13977. getCoupled: getCoupled
  13978. });
  13979. var CouplingSchema = [requiredOf('others', setOf(Result.value, anyValue()))];
  13980. var init$a = function () {
  13981. var coupled = {};
  13982. var getOrCreate = function (component, coupleConfig, name) {
  13983. var available = keys(coupleConfig.others);
  13984. if (!available) {
  13985. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  13986. } else {
  13987. return get$e(coupled, name).getOrThunk(function () {
  13988. var builder = get$e(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  13989. var spec = builder(component);
  13990. var built = component.getSystem().build(spec);
  13991. coupled[name] = built;
  13992. return built;
  13993. });
  13994. }
  13995. };
  13996. var readState = constant$1({});
  13997. return nu$8({
  13998. readState: readState,
  13999. getOrCreate: getOrCreate
  14000. });
  14001. };
  14002. var CouplingState = /*#__PURE__*/Object.freeze({
  14003. __proto__: null,
  14004. init: init$a
  14005. });
  14006. var Coupling = create$7({
  14007. fields: CouplingSchema,
  14008. name: 'coupling',
  14009. apis: CouplingApis,
  14010. state: CouplingState
  14011. });
  14012. var suffix = constant$1('sink');
  14013. var partType$1 = constant$1(optional({
  14014. name: suffix(),
  14015. overrides: constant$1({
  14016. dom: { tag: 'div' },
  14017. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  14018. events: derive$2([
  14019. cutter(keydown()),
  14020. cutter(mousedown()),
  14021. cutter(click())
  14022. ])
  14023. })
  14024. }));
  14025. var HighlightOnOpen;
  14026. (function (HighlightOnOpen) {
  14027. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  14028. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  14029. }(HighlightOnOpen || (HighlightOnOpen = {})));
  14030. var getAnchor = function (detail, component) {
  14031. var hotspot = detail.getHotspot(component).getOr(component);
  14032. var type = 'hotspot';
  14033. var overrides = detail.getAnchorOverrides();
  14034. return detail.layouts.fold(function () {
  14035. return {
  14036. type: type,
  14037. hotspot: hotspot,
  14038. overrides: overrides
  14039. };
  14040. }, function (layouts) {
  14041. return {
  14042. type: type,
  14043. hotspot: hotspot,
  14044. overrides: overrides,
  14045. layouts: layouts
  14046. };
  14047. });
  14048. };
  14049. var fetch = function (detail, mapFetch, component) {
  14050. var fetcher = detail.fetch;
  14051. return fetcher(component).map(mapFetch);
  14052. };
  14053. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  14054. var futureData = fetch(detail, mapFetch, component);
  14055. var getLazySink = getSink(component, detail);
  14056. return futureData.map(function (tdata) {
  14057. return tdata.bind(function (data) {
  14058. return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  14059. uid: generate$5(''),
  14060. data: data,
  14061. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  14062. onOpenMenu: function (tmenu, menu) {
  14063. var sink = getLazySink().getOrDie();
  14064. Positioning.position(sink, menu, { anchor: anchor });
  14065. Sandboxing.decloak(sandbox);
  14066. },
  14067. onOpenSubmenu: function (tmenu, item, submenu) {
  14068. var sink = getLazySink().getOrDie();
  14069. Positioning.position(sink, submenu, {
  14070. anchor: {
  14071. type: 'submenu',
  14072. item: item
  14073. }
  14074. });
  14075. Sandboxing.decloak(sandbox);
  14076. },
  14077. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  14078. var sink = getLazySink().getOrDie();
  14079. Positioning.position(sink, primaryMenu, { anchor: anchor });
  14080. each$1(submenuTriggers, function (st) {
  14081. Positioning.position(sink, st.triggeredMenu, {
  14082. anchor: {
  14083. type: 'submenu',
  14084. item: st.triggeringItem
  14085. }
  14086. });
  14087. });
  14088. },
  14089. onEscape: function () {
  14090. Focusing.focus(component);
  14091. Sandboxing.close(sandbox);
  14092. return Optional.some(true);
  14093. }
  14094. })));
  14095. });
  14096. });
  14097. };
  14098. var open = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  14099. var anchor = getAnchor(detail, hotspot);
  14100. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  14101. return processed.map(function (tdata) {
  14102. tdata.fold(function () {
  14103. if (Sandboxing.isOpen(sandbox)) {
  14104. Sandboxing.close(sandbox);
  14105. }
  14106. }, function (data) {
  14107. Sandboxing.cloak(sandbox);
  14108. Sandboxing.open(sandbox, data);
  14109. onOpenSync(sandbox);
  14110. });
  14111. return sandbox;
  14112. });
  14113. };
  14114. var close = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  14115. Sandboxing.close(sandbox);
  14116. return Future.pure(sandbox);
  14117. };
  14118. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  14119. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  14120. var showing = Sandboxing.isOpen(sandbox);
  14121. var action = showing ? close : open;
  14122. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  14123. };
  14124. var matchWidth = function (hotspot, container, useMinWidth) {
  14125. var menu = Composing.getCurrent(container).getOr(container);
  14126. var buttonWidth = get$a(hotspot.element);
  14127. if (useMinWidth) {
  14128. set$7(menu.element, 'min-width', buttonWidth + 'px');
  14129. } else {
  14130. set$6(menu.element, buttonWidth);
  14131. }
  14132. };
  14133. var getSink = function (anyInSystem, sinkDetail) {
  14134. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  14135. return function () {
  14136. return Result.value(internalSink);
  14137. };
  14138. }).getOrThunk(function () {
  14139. return sinkDetail.lazySink.fold(function () {
  14140. return function () {
  14141. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  14142. };
  14143. }, function (lazySinkFn) {
  14144. return function () {
  14145. return lazySinkFn(anyInSystem);
  14146. };
  14147. });
  14148. });
  14149. };
  14150. var doRepositionMenus = function (sandbox) {
  14151. Sandboxing.getState(sandbox).each(function (tmenu) {
  14152. tieredMenu.repositionMenus(tmenu);
  14153. });
  14154. };
  14155. var makeSandbox$1 = function (detail, hotspot, extras) {
  14156. var ariaOwner = manager();
  14157. var onOpen = function (component, menu) {
  14158. var anchor = getAnchor(detail, hotspot);
  14159. ariaOwner.link(hotspot.element);
  14160. if (detail.matchWidth) {
  14161. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  14162. }
  14163. detail.onOpen(anchor, component, menu);
  14164. if (extras !== undefined && extras.onOpen !== undefined) {
  14165. extras.onOpen(component, menu);
  14166. }
  14167. };
  14168. var onClose = function (component, menu) {
  14169. ariaOwner.unlink(hotspot.element);
  14170. if (extras !== undefined && extras.onClose !== undefined) {
  14171. extras.onClose(component, menu);
  14172. }
  14173. };
  14174. var lazySink = getSink(hotspot, detail);
  14175. return {
  14176. dom: {
  14177. tag: 'div',
  14178. classes: detail.sandboxClasses,
  14179. attributes: {
  14180. id: ariaOwner.id,
  14181. role: 'listbox'
  14182. }
  14183. },
  14184. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  14185. Representing.config({
  14186. store: {
  14187. mode: 'memory',
  14188. initialValue: hotspot
  14189. }
  14190. }),
  14191. Sandboxing.config({
  14192. onOpen: onOpen,
  14193. onClose: onClose,
  14194. isPartOf: function (container, data, queryElem) {
  14195. return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem);
  14196. },
  14197. getAttachPoint: function () {
  14198. return lazySink().getOrDie();
  14199. }
  14200. }),
  14201. Composing.config({
  14202. find: function (sandbox) {
  14203. return Sandboxing.getState(sandbox).bind(function (menu) {
  14204. return Composing.getCurrent(menu);
  14205. });
  14206. }
  14207. }),
  14208. Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) })
  14209. ])
  14210. };
  14211. };
  14212. var repositionMenus = function (comp) {
  14213. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  14214. doRepositionMenus(sandbox);
  14215. };
  14216. var sandboxFields = function () {
  14217. return [
  14218. defaulted('sandboxClasses', []),
  14219. SketchBehaviours.field('sandboxBehaviours', [
  14220. Composing,
  14221. Receiving,
  14222. Sandboxing,
  14223. Representing
  14224. ])
  14225. ];
  14226. };
  14227. var schema$j = constant$1([
  14228. required$1('dom'),
  14229. required$1('fetch'),
  14230. onHandler('onOpen'),
  14231. onKeyboardHandler('onExecute'),
  14232. defaulted('getHotspot', Optional.some),
  14233. defaulted('getAnchorOverrides', constant$1({})),
  14234. schema$y(),
  14235. field('dropdownBehaviours', [
  14236. Toggling,
  14237. Coupling,
  14238. Keying,
  14239. Focusing
  14240. ]),
  14241. required$1('toggleClass'),
  14242. defaulted('eventOrder', {}),
  14243. option('lazySink'),
  14244. defaulted('matchWidth', false),
  14245. defaulted('useMinWidth', false),
  14246. option('role')
  14247. ].concat(sandboxFields()));
  14248. var parts$d = constant$1([
  14249. external$1({
  14250. schema: [tieredMenuMarkers()],
  14251. name: 'menu',
  14252. defaults: function (detail) {
  14253. return { onExecute: detail.onExecute };
  14254. }
  14255. }),
  14256. partType$1()
  14257. ]);
  14258. var factory$g = function (detail, components, _spec, externals) {
  14259. var _a;
  14260. var lookupAttr = function (attr) {
  14261. return get$e(detail.dom, 'attributes').bind(function (attrs) {
  14262. return get$e(attrs, attr);
  14263. });
  14264. };
  14265. var switchToMenu = function (sandbox) {
  14266. Sandboxing.getState(sandbox).each(function (tmenu) {
  14267. tieredMenu.highlightPrimary(tmenu);
  14268. });
  14269. };
  14270. var action = function (component) {
  14271. var onOpenSync = switchToMenu;
  14272. togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  14273. };
  14274. var apis = {
  14275. expand: function (comp) {
  14276. if (!Toggling.isOn(comp)) {
  14277. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  14278. }
  14279. },
  14280. open: function (comp) {
  14281. if (!Toggling.isOn(comp)) {
  14282. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  14283. }
  14284. },
  14285. isOpen: Toggling.isOn,
  14286. close: function (comp) {
  14287. if (Toggling.isOn(comp)) {
  14288. togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  14289. }
  14290. },
  14291. repositionMenus: function (comp) {
  14292. if (Toggling.isOn(comp)) {
  14293. repositionMenus(comp);
  14294. }
  14295. }
  14296. };
  14297. var triggerExecute = function (comp, _se) {
  14298. emitExecute(comp);
  14299. return Optional.some(true);
  14300. };
  14301. return {
  14302. uid: detail.uid,
  14303. dom: detail.dom,
  14304. components: components,
  14305. behaviours: augment(detail.dropdownBehaviours, [
  14306. Toggling.config({
  14307. toggleClass: detail.toggleClass,
  14308. aria: { mode: 'expanded' }
  14309. }),
  14310. Coupling.config({
  14311. others: {
  14312. sandbox: function (hotspot) {
  14313. return makeSandbox$1(detail, hotspot, {
  14314. onOpen: function () {
  14315. return Toggling.on(hotspot);
  14316. },
  14317. onClose: function () {
  14318. return Toggling.off(hotspot);
  14319. }
  14320. });
  14321. }
  14322. }
  14323. }),
  14324. Keying.config({
  14325. mode: 'special',
  14326. onSpace: triggerExecute,
  14327. onEnter: triggerExecute,
  14328. onDown: function (comp, _se) {
  14329. if (Dropdown.isOpen(comp)) {
  14330. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  14331. switchToMenu(sandbox);
  14332. } else {
  14333. Dropdown.open(comp);
  14334. }
  14335. return Optional.some(true);
  14336. },
  14337. onEscape: function (comp, _se) {
  14338. if (Dropdown.isOpen(comp)) {
  14339. Dropdown.close(comp);
  14340. return Optional.some(true);
  14341. } else {
  14342. return Optional.none();
  14343. }
  14344. }
  14345. }),
  14346. Focusing.config({})
  14347. ]),
  14348. events: events$a(Optional.some(action)),
  14349. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  14350. 'disabling',
  14351. 'toggling',
  14352. 'alloy.base.behaviour'
  14353. ], _a)),
  14354. apis: apis,
  14355. domModification: {
  14356. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  14357. return {};
  14358. }, function (role) {
  14359. return { role: role };
  14360. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  14361. }
  14362. };
  14363. };
  14364. var Dropdown = composite({
  14365. name: 'Dropdown',
  14366. configFields: schema$j(),
  14367. partFields: parts$d(),
  14368. factory: factory$g,
  14369. apis: {
  14370. open: function (apis, comp) {
  14371. return apis.open(comp);
  14372. },
  14373. expand: function (apis, comp) {
  14374. return apis.expand(comp);
  14375. },
  14376. close: function (apis, comp) {
  14377. return apis.close(comp);
  14378. },
  14379. isOpen: function (apis, comp) {
  14380. return apis.isOpen(comp);
  14381. },
  14382. repositionMenus: function (apis, comp) {
  14383. return apis.repositionMenus(comp);
  14384. }
  14385. }
  14386. });
  14387. var exhibit$1 = function () {
  14388. return nu$7({
  14389. styles: {
  14390. '-webkit-user-select': 'none',
  14391. 'user-select': 'none',
  14392. '-ms-user-select': 'none',
  14393. '-moz-user-select': '-moz-none'
  14394. },
  14395. attributes: { unselectable: 'on' }
  14396. });
  14397. };
  14398. var events$7 = function () {
  14399. return derive$2([abort(selectstart(), always)]);
  14400. };
  14401. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  14402. __proto__: null,
  14403. events: events$7,
  14404. exhibit: exhibit$1
  14405. });
  14406. var Unselecting = create$7({
  14407. fields: [],
  14408. name: 'unselecting',
  14409. active: ActiveUnselecting
  14410. });
  14411. var renderPanelButton = function (spec, sharedBackstage) {
  14412. return Dropdown.sketch({
  14413. dom: spec.dom,
  14414. components: spec.components,
  14415. toggleClass: 'mce-active',
  14416. dropdownBehaviours: derive$1([
  14417. DisablingConfigs.button(sharedBackstage.providers.isDisabled),
  14418. receivingConfig(),
  14419. Unselecting.config({}),
  14420. Tabstopping.config({})
  14421. ]),
  14422. layouts: spec.layouts,
  14423. sandboxClasses: ['tox-dialog__popups'],
  14424. lazySink: sharedBackstage.getSink,
  14425. fetch: function (comp) {
  14426. return Future.nu(function (callback) {
  14427. return spec.fetch(callback);
  14428. }).map(function (items) {
  14429. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  14430. spec.onItemAction(comp, value);
  14431. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  14432. });
  14433. },
  14434. parts: { menu: part(false, 1, spec.presets) }
  14435. });
  14436. };
  14437. var colorInputChangeEvent = generate$6('color-input-change');
  14438. var colorSwatchChangeEvent = generate$6('color-swatch-change');
  14439. var colorPickerCancelEvent = generate$6('color-picker-cancel');
  14440. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  14441. var pField = FormField.parts.field({
  14442. factory: Input,
  14443. inputClasses: ['tox-textfield'],
  14444. onSetValue: function (c) {
  14445. return Invalidating.run(c).get(noop);
  14446. },
  14447. inputBehaviours: derive$1([
  14448. Disabling.config({ disabled: sharedBackstage.providers.isDisabled }),
  14449. receivingConfig(),
  14450. Tabstopping.config({}),
  14451. Invalidating.config({
  14452. invalidClass: 'tox-textbox-field-invalid',
  14453. getRoot: function (comp) {
  14454. return parent(comp.element);
  14455. },
  14456. notify: {
  14457. onValid: function (comp) {
  14458. var val = Representing.getValue(comp);
  14459. emitWith(comp, colorInputChangeEvent, { color: val });
  14460. }
  14461. },
  14462. validator: {
  14463. validateOnLoad: false,
  14464. validate: function (input) {
  14465. var inputValue = Representing.getValue(input);
  14466. if (inputValue.length === 0) {
  14467. return Future.pure(Result.value(true));
  14468. } else {
  14469. var span = SugarElement.fromTag('span');
  14470. set$7(span, 'background-color', inputValue);
  14471. var res = getRaw(span, 'background-color').fold(function () {
  14472. return Result.error('blah');
  14473. }, function (_) {
  14474. return Result.value(inputValue);
  14475. });
  14476. return Future.pure(res);
  14477. }
  14478. }
  14479. }
  14480. })
  14481. ]),
  14482. selectOnFocus: false
  14483. });
  14484. var pLabel = spec.label.map(function (label) {
  14485. return renderLabel$2(label, sharedBackstage.providers);
  14486. });
  14487. var emitSwatchChange = function (colorBit, value) {
  14488. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  14489. };
  14490. var onItemAction = function (comp, value) {
  14491. memColorButton.getOpt(comp).each(function (colorBit) {
  14492. if (value === 'custom') {
  14493. colorInputBackstage.colorPicker(function (valueOpt) {
  14494. valueOpt.fold(function () {
  14495. return emit(colorBit, colorPickerCancelEvent);
  14496. }, function (value) {
  14497. emitSwatchChange(colorBit, value);
  14498. addColor(value);
  14499. });
  14500. }, '#ffffff');
  14501. } else if (value === 'remove') {
  14502. emitSwatchChange(colorBit, '');
  14503. } else {
  14504. emitSwatchChange(colorBit, value);
  14505. }
  14506. });
  14507. };
  14508. var memColorButton = record(renderPanelButton({
  14509. dom: {
  14510. tag: 'span',
  14511. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  14512. },
  14513. layouts: {
  14514. onRtl: function () {
  14515. return [
  14516. southwest$2,
  14517. southeast$2,
  14518. south$2
  14519. ];
  14520. },
  14521. onLtr: function () {
  14522. return [
  14523. southeast$2,
  14524. southwest$2,
  14525. south$2
  14526. ];
  14527. }
  14528. },
  14529. components: [],
  14530. fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  14531. columns: colorInputBackstage.getColorCols(),
  14532. presets: 'color',
  14533. onItemAction: onItemAction
  14534. }, sharedBackstage));
  14535. return FormField.sketch({
  14536. dom: {
  14537. tag: 'div',
  14538. classes: ['tox-form__group']
  14539. },
  14540. components: pLabel.toArray().concat([{
  14541. dom: {
  14542. tag: 'div',
  14543. classes: ['tox-color-input']
  14544. },
  14545. components: [
  14546. pField,
  14547. memColorButton.asSpec()
  14548. ]
  14549. }]),
  14550. fieldBehaviours: derive$1([config('form-field-events', [
  14551. run$1(colorInputChangeEvent, function (comp, se) {
  14552. memColorButton.getOpt(comp).each(function (colorButton) {
  14553. set$7(colorButton.element, 'background-color', se.event.color);
  14554. });
  14555. emitWith(comp, formChangeEvent, { name: spec.name });
  14556. }),
  14557. run$1(colorSwatchChangeEvent, function (comp, se) {
  14558. FormField.getField(comp).each(function (field) {
  14559. Representing.setValue(field, se.event.value);
  14560. Composing.getCurrent(comp).each(Focusing.focus);
  14561. });
  14562. }),
  14563. run$1(colorPickerCancelEvent, function (comp, _se) {
  14564. FormField.getField(comp).each(function (_field) {
  14565. Composing.getCurrent(comp).each(Focusing.focus);
  14566. });
  14567. })
  14568. ])])
  14569. });
  14570. };
  14571. var labelPart = optional({
  14572. schema: [required$1('dom')],
  14573. name: 'label'
  14574. });
  14575. var edgePart = function (name) {
  14576. return optional({
  14577. name: '' + name + '-edge',
  14578. overrides: function (detail) {
  14579. var action = detail.model.manager.edgeActions[name];
  14580. return action.fold(function () {
  14581. return {};
  14582. }, function (a) {
  14583. return {
  14584. events: derive$2([
  14585. runActionExtra(touchstart(), function (comp, se, d) {
  14586. return a(comp, d);
  14587. }, [detail]),
  14588. runActionExtra(mousedown(), function (comp, se, d) {
  14589. return a(comp, d);
  14590. }, [detail]),
  14591. runActionExtra(mousemove(), function (comp, se, det) {
  14592. if (det.mouseIsDown.get()) {
  14593. a(comp, det);
  14594. }
  14595. }, [detail])
  14596. ])
  14597. };
  14598. });
  14599. }
  14600. });
  14601. };
  14602. var tlEdgePart = edgePart('top-left');
  14603. var tedgePart = edgePart('top');
  14604. var trEdgePart = edgePart('top-right');
  14605. var redgePart = edgePart('right');
  14606. var brEdgePart = edgePart('bottom-right');
  14607. var bedgePart = edgePart('bottom');
  14608. var blEdgePart = edgePart('bottom-left');
  14609. var ledgePart = edgePart('left');
  14610. var thumbPart = required({
  14611. name: 'thumb',
  14612. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  14613. overrides: function (detail) {
  14614. return {
  14615. events: derive$2([
  14616. redirectToPart(touchstart(), detail, 'spectrum'),
  14617. redirectToPart(touchmove(), detail, 'spectrum'),
  14618. redirectToPart(touchend(), detail, 'spectrum'),
  14619. redirectToPart(mousedown(), detail, 'spectrum'),
  14620. redirectToPart(mousemove(), detail, 'spectrum'),
  14621. redirectToPart(mouseup(), detail, 'spectrum')
  14622. ])
  14623. };
  14624. }
  14625. });
  14626. var spectrumPart = required({
  14627. schema: [customField('mouseIsDown', function () {
  14628. return Cell(false);
  14629. })],
  14630. name: 'spectrum',
  14631. overrides: function (detail) {
  14632. var modelDetail = detail.model;
  14633. var model = modelDetail.manager;
  14634. var setValueFrom = function (component, simulatedEvent) {
  14635. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14636. return model.setValueFrom(component, detail, value);
  14637. });
  14638. };
  14639. return {
  14640. behaviours: derive$1([
  14641. Keying.config({
  14642. mode: 'special',
  14643. onLeft: function (spectrum) {
  14644. return model.onLeft(spectrum, detail);
  14645. },
  14646. onRight: function (spectrum) {
  14647. return model.onRight(spectrum, detail);
  14648. },
  14649. onUp: function (spectrum) {
  14650. return model.onUp(spectrum, detail);
  14651. },
  14652. onDown: function (spectrum) {
  14653. return model.onDown(spectrum, detail);
  14654. }
  14655. }),
  14656. Focusing.config({})
  14657. ]),
  14658. events: derive$2([
  14659. run$1(touchstart(), setValueFrom),
  14660. run$1(touchmove(), setValueFrom),
  14661. run$1(mousedown(), setValueFrom),
  14662. run$1(mousemove(), function (spectrum, se) {
  14663. if (detail.mouseIsDown.get()) {
  14664. setValueFrom(spectrum, se);
  14665. }
  14666. })
  14667. ])
  14668. };
  14669. }
  14670. });
  14671. var SliderParts = [
  14672. labelPart,
  14673. ledgePart,
  14674. redgePart,
  14675. tedgePart,
  14676. bedgePart,
  14677. tlEdgePart,
  14678. trEdgePart,
  14679. blEdgePart,
  14680. brEdgePart,
  14681. thumbPart,
  14682. spectrumPart
  14683. ];
  14684. var _sliderChangeEvent = 'slider.change.value';
  14685. var sliderChangeEvent = constant$1(_sliderChangeEvent);
  14686. var isTouchEvent$2 = function (evt) {
  14687. return evt.type.indexOf('touch') !== -1;
  14688. };
  14689. var getEventSource = function (simulatedEvent) {
  14690. var evt = simulatedEvent.event.raw;
  14691. if (isTouchEvent$2(evt)) {
  14692. var touchEvent = evt;
  14693. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  14694. return SugarPosition(t.clientX, t.clientY);
  14695. }) : Optional.none();
  14696. } else {
  14697. var mouseEvent = evt;
  14698. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  14699. return SugarPosition(me.clientX, me.clientY);
  14700. }) : Optional.none();
  14701. }
  14702. };
  14703. var t = 'top', r = 'right', b = 'bottom', l = 'left';
  14704. var minX = function (detail) {
  14705. return detail.model.minX;
  14706. };
  14707. var minY = function (detail) {
  14708. return detail.model.minY;
  14709. };
  14710. var min1X = function (detail) {
  14711. return detail.model.minX - 1;
  14712. };
  14713. var min1Y = function (detail) {
  14714. return detail.model.minY - 1;
  14715. };
  14716. var maxX = function (detail) {
  14717. return detail.model.maxX;
  14718. };
  14719. var maxY = function (detail) {
  14720. return detail.model.maxY;
  14721. };
  14722. var max1X = function (detail) {
  14723. return detail.model.maxX + 1;
  14724. };
  14725. var max1Y = function (detail) {
  14726. return detail.model.maxY + 1;
  14727. };
  14728. var range = function (detail, max, min) {
  14729. return max(detail) - min(detail);
  14730. };
  14731. var xRange = function (detail) {
  14732. return range(detail, maxX, minX);
  14733. };
  14734. var yRange = function (detail) {
  14735. return range(detail, maxY, minY);
  14736. };
  14737. var halfX = function (detail) {
  14738. return xRange(detail) / 2;
  14739. };
  14740. var halfY = function (detail) {
  14741. return yRange(detail) / 2;
  14742. };
  14743. var step = function (detail) {
  14744. return detail.stepSize;
  14745. };
  14746. var snap = function (detail) {
  14747. return detail.snapToGrid;
  14748. };
  14749. var snapStart = function (detail) {
  14750. return detail.snapStart;
  14751. };
  14752. var rounded = function (detail) {
  14753. return detail.rounded;
  14754. };
  14755. var hasEdge = function (detail, edgeName) {
  14756. return detail[edgeName + '-edge'] !== undefined;
  14757. };
  14758. var hasLEdge = function (detail) {
  14759. return hasEdge(detail, l);
  14760. };
  14761. var hasREdge = function (detail) {
  14762. return hasEdge(detail, r);
  14763. };
  14764. var hasTEdge = function (detail) {
  14765. return hasEdge(detail, t);
  14766. };
  14767. var hasBEdge = function (detail) {
  14768. return hasEdge(detail, b);
  14769. };
  14770. var currentValue = function (detail) {
  14771. return detail.model.value.get();
  14772. };
  14773. var xValue = function (x) {
  14774. return { x: x };
  14775. };
  14776. var yValue = function (y) {
  14777. return { y: y };
  14778. };
  14779. var xyValue = function (x, y) {
  14780. return {
  14781. x: x,
  14782. y: y
  14783. };
  14784. };
  14785. var fireSliderChange$3 = function (component, value) {
  14786. emitWith(component, sliderChangeEvent(), { value: value });
  14787. };
  14788. var setToTLEdgeXY = function (edge, detail) {
  14789. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  14790. };
  14791. var setToTEdge = function (edge, detail) {
  14792. fireSliderChange$3(edge, yValue(min1Y(detail)));
  14793. };
  14794. var setToTEdgeXY = function (edge, detail) {
  14795. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  14796. };
  14797. var setToTREdgeXY = function (edge, detail) {
  14798. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  14799. };
  14800. var setToREdge = function (edge, detail) {
  14801. fireSliderChange$3(edge, xValue(max1X(detail)));
  14802. };
  14803. var setToREdgeXY = function (edge, detail) {
  14804. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  14805. };
  14806. var setToBREdgeXY = function (edge, detail) {
  14807. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  14808. };
  14809. var setToBEdge = function (edge, detail) {
  14810. fireSliderChange$3(edge, yValue(max1Y(detail)));
  14811. };
  14812. var setToBEdgeXY = function (edge, detail) {
  14813. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  14814. };
  14815. var setToBLEdgeXY = function (edge, detail) {
  14816. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  14817. };
  14818. var setToLEdge = function (edge, detail) {
  14819. fireSliderChange$3(edge, xValue(min1X(detail)));
  14820. };
  14821. var setToLEdgeXY = function (edge, detail) {
  14822. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  14823. };
  14824. var reduceBy = function (value, min, max, step) {
  14825. if (value < min) {
  14826. return value;
  14827. } else if (value > max) {
  14828. return max;
  14829. } else if (value === min) {
  14830. return min - 1;
  14831. } else {
  14832. return Math.max(min, value - step);
  14833. }
  14834. };
  14835. var increaseBy = function (value, min, max, step) {
  14836. if (value > max) {
  14837. return value;
  14838. } else if (value < min) {
  14839. return min;
  14840. } else if (value === max) {
  14841. return max + 1;
  14842. } else {
  14843. return Math.min(max, value + step);
  14844. }
  14845. };
  14846. var capValue = function (value, min, max) {
  14847. return Math.max(min, Math.min(max, value));
  14848. };
  14849. var snapValueOf = function (value, min, max, step, snapStart) {
  14850. return snapStart.fold(function () {
  14851. var initValue = value - min;
  14852. var extraValue = Math.round(initValue / step) * step;
  14853. return capValue(min + extraValue, min - 1, max + 1);
  14854. }, function (start) {
  14855. var remainder = (value - start) % step;
  14856. var adjustment = Math.round(remainder / step);
  14857. var rawSteps = Math.floor((value - start) / step);
  14858. var maxSteps = Math.floor((max - start) / step);
  14859. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  14860. var r = start + numSteps * step;
  14861. return Math.max(start, r);
  14862. });
  14863. };
  14864. var findOffsetOf = function (value, min, max) {
  14865. return Math.min(max, Math.max(value, min)) - min;
  14866. };
  14867. var findValueOf = function (args) {
  14868. 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;
  14869. var capMin = hasMinEdge ? min - 1 : min;
  14870. var capMax = hasMaxEdge ? max + 1 : max;
  14871. if (value < minBound) {
  14872. return capMin;
  14873. } else if (value > maxBound) {
  14874. return capMax;
  14875. } else {
  14876. var offset = findOffsetOf(value, minBound, maxBound);
  14877. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  14878. if (snap && newValue >= min && newValue <= max) {
  14879. return snapValueOf(newValue, min, max, step, snapStart);
  14880. } else if (rounded) {
  14881. return Math.round(newValue);
  14882. } else {
  14883. return newValue;
  14884. }
  14885. }
  14886. };
  14887. var findOffsetOfValue$2 = function (args) {
  14888. 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;
  14889. if (value < min) {
  14890. return hasMinEdge ? 0 : centerMinEdge;
  14891. } else if (value > max) {
  14892. return hasMaxEdge ? maxBound : centerMaxEdge;
  14893. } else {
  14894. return (value - min) / range * maxOffset;
  14895. }
  14896. };
  14897. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  14898. var getBounds = function (component) {
  14899. return component.element.dom.getBoundingClientRect();
  14900. };
  14901. var getBoundsProperty = function (bounds, property) {
  14902. return bounds[property];
  14903. };
  14904. var getMinXBounds = function (component) {
  14905. var bounds = getBounds(component);
  14906. return getBoundsProperty(bounds, left);
  14907. };
  14908. var getMaxXBounds = function (component) {
  14909. var bounds = getBounds(component);
  14910. return getBoundsProperty(bounds, right);
  14911. };
  14912. var getMinYBounds = function (component) {
  14913. var bounds = getBounds(component);
  14914. return getBoundsProperty(bounds, top);
  14915. };
  14916. var getMaxYBounds = function (component) {
  14917. var bounds = getBounds(component);
  14918. return getBoundsProperty(bounds, bottom);
  14919. };
  14920. var getXScreenRange = function (component) {
  14921. var bounds = getBounds(component);
  14922. return getBoundsProperty(bounds, width);
  14923. };
  14924. var getYScreenRange = function (component) {
  14925. var bounds = getBounds(component);
  14926. return getBoundsProperty(bounds, height);
  14927. };
  14928. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  14929. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  14930. };
  14931. var getXCenterOffSetOf = function (component, spectrum) {
  14932. var componentBounds = getBounds(component);
  14933. var spectrumBounds = getBounds(spectrum);
  14934. var componentMinEdge = getBoundsProperty(componentBounds, left);
  14935. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  14936. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  14937. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14938. };
  14939. var getYCenterOffSetOf = function (component, spectrum) {
  14940. var componentBounds = getBounds(component);
  14941. var spectrumBounds = getBounds(spectrum);
  14942. var componentMinEdge = getBoundsProperty(componentBounds, top);
  14943. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  14944. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  14945. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14946. };
  14947. var fireSliderChange$2 = function (spectrum, value) {
  14948. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14949. };
  14950. var sliderValue$2 = function (x) {
  14951. return { x: x };
  14952. };
  14953. var findValueOfOffset$1 = function (spectrum, detail, left) {
  14954. var args = {
  14955. min: minX(detail),
  14956. max: maxX(detail),
  14957. range: xRange(detail),
  14958. value: left,
  14959. step: step(detail),
  14960. snap: snap(detail),
  14961. snapStart: snapStart(detail),
  14962. rounded: rounded(detail),
  14963. hasMinEdge: hasLEdge(detail),
  14964. hasMaxEdge: hasREdge(detail),
  14965. minBound: getMinXBounds(spectrum),
  14966. maxBound: getMaxXBounds(spectrum),
  14967. screenRange: getXScreenRange(spectrum)
  14968. };
  14969. return findValueOf(args);
  14970. };
  14971. var setValueFrom$2 = function (spectrum, detail, value) {
  14972. var xValue = findValueOfOffset$1(spectrum, detail, value);
  14973. var sliderVal = sliderValue$2(xValue);
  14974. fireSliderChange$2(spectrum, sliderVal);
  14975. return xValue;
  14976. };
  14977. var setToMin$2 = function (spectrum, detail) {
  14978. var min = minX(detail);
  14979. fireSliderChange$2(spectrum, sliderValue$2(min));
  14980. };
  14981. var setToMax$2 = function (spectrum, detail) {
  14982. var max = maxX(detail);
  14983. fireSliderChange$2(spectrum, sliderValue$2(max));
  14984. };
  14985. var moveBy$2 = function (direction, spectrum, detail) {
  14986. var f = direction > 0 ? increaseBy : reduceBy;
  14987. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  14988. fireSliderChange$2(spectrum, sliderValue$2(xValue));
  14989. return Optional.some(xValue);
  14990. };
  14991. var handleMovement$2 = function (direction) {
  14992. return function (spectrum, detail) {
  14993. return moveBy$2(direction, spectrum, detail).map(always);
  14994. };
  14995. };
  14996. var getValueFromEvent$2 = function (simulatedEvent) {
  14997. var pos = getEventSource(simulatedEvent);
  14998. return pos.map(function (p) {
  14999. return p.left;
  15000. });
  15001. };
  15002. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  15003. var minOffset = 0;
  15004. var maxOffset = getXScreenRange(spectrum);
  15005. var centerMinEdge = minEdge.bind(function (edge) {
  15006. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  15007. }).getOr(minOffset);
  15008. var centerMaxEdge = maxEdge.bind(function (edge) {
  15009. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  15010. }).getOr(maxOffset);
  15011. var args = {
  15012. min: minX(detail),
  15013. max: maxX(detail),
  15014. range: xRange(detail),
  15015. value: value,
  15016. hasMinEdge: hasLEdge(detail),
  15017. hasMaxEdge: hasREdge(detail),
  15018. minBound: getMinXBounds(spectrum),
  15019. minOffset: minOffset,
  15020. maxBound: getMaxXBounds(spectrum),
  15021. maxOffset: maxOffset,
  15022. centerMinEdge: centerMinEdge,
  15023. centerMaxEdge: centerMaxEdge
  15024. };
  15025. return findOffsetOfValue$2(args);
  15026. };
  15027. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  15028. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  15029. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  15030. };
  15031. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  15032. var value = currentValue(detail);
  15033. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  15034. var thumbRadius = get$a(thumb.element) / 2;
  15035. set$7(thumb.element, 'left', pos - thumbRadius + 'px');
  15036. };
  15037. var onLeft$2 = handleMovement$2(-1);
  15038. var onRight$2 = handleMovement$2(1);
  15039. var onUp$2 = Optional.none;
  15040. var onDown$2 = Optional.none;
  15041. var edgeActions$2 = {
  15042. 'top-left': Optional.none(),
  15043. 'top': Optional.none(),
  15044. 'top-right': Optional.none(),
  15045. 'right': Optional.some(setToREdge),
  15046. 'bottom-right': Optional.none(),
  15047. 'bottom': Optional.none(),
  15048. 'bottom-left': Optional.none(),
  15049. 'left': Optional.some(setToLEdge)
  15050. };
  15051. var HorizontalModel = /*#__PURE__*/Object.freeze({
  15052. __proto__: null,
  15053. setValueFrom: setValueFrom$2,
  15054. setToMin: setToMin$2,
  15055. setToMax: setToMax$2,
  15056. findValueOfOffset: findValueOfOffset$1,
  15057. getValueFromEvent: getValueFromEvent$2,
  15058. findPositionOfValue: findPositionOfValue$1,
  15059. setPositionFromValue: setPositionFromValue$2,
  15060. onLeft: onLeft$2,
  15061. onRight: onRight$2,
  15062. onUp: onUp$2,
  15063. onDown: onDown$2,
  15064. edgeActions: edgeActions$2
  15065. });
  15066. var fireSliderChange$1 = function (spectrum, value) {
  15067. emitWith(spectrum, sliderChangeEvent(), { value: value });
  15068. };
  15069. var sliderValue$1 = function (y) {
  15070. return { y: y };
  15071. };
  15072. var findValueOfOffset = function (spectrum, detail, top) {
  15073. var args = {
  15074. min: minY(detail),
  15075. max: maxY(detail),
  15076. range: yRange(detail),
  15077. value: top,
  15078. step: step(detail),
  15079. snap: snap(detail),
  15080. snapStart: snapStart(detail),
  15081. rounded: rounded(detail),
  15082. hasMinEdge: hasTEdge(detail),
  15083. hasMaxEdge: hasBEdge(detail),
  15084. minBound: getMinYBounds(spectrum),
  15085. maxBound: getMaxYBounds(spectrum),
  15086. screenRange: getYScreenRange(spectrum)
  15087. };
  15088. return findValueOf(args);
  15089. };
  15090. var setValueFrom$1 = function (spectrum, detail, value) {
  15091. var yValue = findValueOfOffset(spectrum, detail, value);
  15092. var sliderVal = sliderValue$1(yValue);
  15093. fireSliderChange$1(spectrum, sliderVal);
  15094. return yValue;
  15095. };
  15096. var setToMin$1 = function (spectrum, detail) {
  15097. var min = minY(detail);
  15098. fireSliderChange$1(spectrum, sliderValue$1(min));
  15099. };
  15100. var setToMax$1 = function (spectrum, detail) {
  15101. var max = maxY(detail);
  15102. fireSliderChange$1(spectrum, sliderValue$1(max));
  15103. };
  15104. var moveBy$1 = function (direction, spectrum, detail) {
  15105. var f = direction > 0 ? increaseBy : reduceBy;
  15106. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  15107. fireSliderChange$1(spectrum, sliderValue$1(yValue));
  15108. return Optional.some(yValue);
  15109. };
  15110. var handleMovement$1 = function (direction) {
  15111. return function (spectrum, detail) {
  15112. return moveBy$1(direction, spectrum, detail).map(always);
  15113. };
  15114. };
  15115. var getValueFromEvent$1 = function (simulatedEvent) {
  15116. var pos = getEventSource(simulatedEvent);
  15117. return pos.map(function (p) {
  15118. return p.top;
  15119. });
  15120. };
  15121. var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  15122. var minOffset = 0;
  15123. var maxOffset = getYScreenRange(spectrum);
  15124. var centerMinEdge = minEdge.bind(function (edge) {
  15125. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  15126. }).getOr(minOffset);
  15127. var centerMaxEdge = maxEdge.bind(function (edge) {
  15128. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  15129. }).getOr(maxOffset);
  15130. var args = {
  15131. min: minY(detail),
  15132. max: maxY(detail),
  15133. range: yRange(detail),
  15134. value: value,
  15135. hasMinEdge: hasTEdge(detail),
  15136. hasMaxEdge: hasBEdge(detail),
  15137. minBound: getMinYBounds(spectrum),
  15138. minOffset: minOffset,
  15139. maxBound: getMaxYBounds(spectrum),
  15140. maxOffset: maxOffset,
  15141. centerMinEdge: centerMinEdge,
  15142. centerMaxEdge: centerMaxEdge
  15143. };
  15144. return findOffsetOfValue$2(args);
  15145. };
  15146. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  15147. var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  15148. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  15149. };
  15150. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  15151. var value = currentValue(detail);
  15152. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  15153. var thumbRadius = get$b(thumb.element) / 2;
  15154. set$7(thumb.element, 'top', pos - thumbRadius + 'px');
  15155. };
  15156. var onLeft$1 = Optional.none;
  15157. var onRight$1 = Optional.none;
  15158. var onUp$1 = handleMovement$1(-1);
  15159. var onDown$1 = handleMovement$1(1);
  15160. var edgeActions$1 = {
  15161. 'top-left': Optional.none(),
  15162. 'top': Optional.some(setToTEdge),
  15163. 'top-right': Optional.none(),
  15164. 'right': Optional.none(),
  15165. 'bottom-right': Optional.none(),
  15166. 'bottom': Optional.some(setToBEdge),
  15167. 'bottom-left': Optional.none(),
  15168. 'left': Optional.none()
  15169. };
  15170. var VerticalModel = /*#__PURE__*/Object.freeze({
  15171. __proto__: null,
  15172. setValueFrom: setValueFrom$1,
  15173. setToMin: setToMin$1,
  15174. setToMax: setToMax$1,
  15175. findValueOfOffset: findValueOfOffset,
  15176. getValueFromEvent: getValueFromEvent$1,
  15177. findPositionOfValue: findPositionOfValue,
  15178. setPositionFromValue: setPositionFromValue$1,
  15179. onLeft: onLeft$1,
  15180. onRight: onRight$1,
  15181. onUp: onUp$1,
  15182. onDown: onDown$1,
  15183. edgeActions: edgeActions$1
  15184. });
  15185. var fireSliderChange = function (spectrum, value) {
  15186. emitWith(spectrum, sliderChangeEvent(), { value: value });
  15187. };
  15188. var sliderValue = function (x, y) {
  15189. return {
  15190. x: x,
  15191. y: y
  15192. };
  15193. };
  15194. var setValueFrom = function (spectrum, detail, value) {
  15195. var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  15196. var yValue = findValueOfOffset(spectrum, detail, value.top);
  15197. var val = sliderValue(xValue, yValue);
  15198. fireSliderChange(spectrum, val);
  15199. return val;
  15200. };
  15201. var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  15202. var f = direction > 0 ? increaseBy : reduceBy;
  15203. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  15204. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  15205. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  15206. return Optional.some(xValue);
  15207. };
  15208. var handleMovement = function (direction, isVerticalMovement) {
  15209. return function (spectrum, detail) {
  15210. return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  15211. };
  15212. };
  15213. var setToMin = function (spectrum, detail) {
  15214. var mX = minX(detail);
  15215. var mY = minY(detail);
  15216. fireSliderChange(spectrum, sliderValue(mX, mY));
  15217. };
  15218. var setToMax = function (spectrum, detail) {
  15219. var mX = maxX(detail);
  15220. var mY = maxY(detail);
  15221. fireSliderChange(spectrum, sliderValue(mX, mY));
  15222. };
  15223. var getValueFromEvent = function (simulatedEvent) {
  15224. return getEventSource(simulatedEvent);
  15225. };
  15226. var setPositionFromValue = function (slider, thumb, detail, edges) {
  15227. var value = currentValue(detail);
  15228. var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  15229. var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  15230. var thumbXRadius = get$a(thumb.element) / 2;
  15231. var thumbYRadius = get$b(thumb.element) / 2;
  15232. set$7(thumb.element, 'left', xPos - thumbXRadius + 'px');
  15233. set$7(thumb.element, 'top', yPos - thumbYRadius + 'px');
  15234. };
  15235. var onLeft = handleMovement(-1, false);
  15236. var onRight = handleMovement(1, false);
  15237. var onUp = handleMovement(-1, true);
  15238. var onDown = handleMovement(1, true);
  15239. var edgeActions = {
  15240. 'top-left': Optional.some(setToTLEdgeXY),
  15241. 'top': Optional.some(setToTEdgeXY),
  15242. 'top-right': Optional.some(setToTREdgeXY),
  15243. 'right': Optional.some(setToREdgeXY),
  15244. 'bottom-right': Optional.some(setToBREdgeXY),
  15245. 'bottom': Optional.some(setToBEdgeXY),
  15246. 'bottom-left': Optional.some(setToBLEdgeXY),
  15247. 'left': Optional.some(setToLEdgeXY)
  15248. };
  15249. var TwoDModel = /*#__PURE__*/Object.freeze({
  15250. __proto__: null,
  15251. setValueFrom: setValueFrom,
  15252. setToMin: setToMin,
  15253. setToMax: setToMax,
  15254. getValueFromEvent: getValueFromEvent,
  15255. setPositionFromValue: setPositionFromValue,
  15256. onLeft: onLeft,
  15257. onRight: onRight,
  15258. onUp: onUp,
  15259. onDown: onDown,
  15260. edgeActions: edgeActions
  15261. });
  15262. var SliderSchema = [
  15263. defaulted('stepSize', 1),
  15264. defaulted('onChange', noop),
  15265. defaulted('onChoose', noop),
  15266. defaulted('onInit', noop),
  15267. defaulted('onDragStart', noop),
  15268. defaulted('onDragEnd', noop),
  15269. defaulted('snapToGrid', false),
  15270. defaulted('rounded', true),
  15271. option('snapStart'),
  15272. requiredOf('model', choose$1('mode', {
  15273. x: [
  15274. defaulted('minX', 0),
  15275. defaulted('maxX', 100),
  15276. customField('value', function (spec) {
  15277. return Cell(spec.mode.minX);
  15278. }),
  15279. required$1('getInitialValue'),
  15280. output$1('manager', HorizontalModel)
  15281. ],
  15282. y: [
  15283. defaulted('minY', 0),
  15284. defaulted('maxY', 100),
  15285. customField('value', function (spec) {
  15286. return Cell(spec.mode.minY);
  15287. }),
  15288. required$1('getInitialValue'),
  15289. output$1('manager', VerticalModel)
  15290. ],
  15291. xy: [
  15292. defaulted('minX', 0),
  15293. defaulted('maxX', 100),
  15294. defaulted('minY', 0),
  15295. defaulted('maxY', 100),
  15296. customField('value', function (spec) {
  15297. return Cell({
  15298. x: spec.mode.minX,
  15299. y: spec.mode.minY
  15300. });
  15301. }),
  15302. required$1('getInitialValue'),
  15303. output$1('manager', TwoDModel)
  15304. ]
  15305. })),
  15306. field('sliderBehaviours', [
  15307. Keying,
  15308. Representing
  15309. ]),
  15310. customField('mouseIsDown', function () {
  15311. return Cell(false);
  15312. })
  15313. ];
  15314. var sketch$2 = function (detail, components, _spec, _externals) {
  15315. var _a;
  15316. var getThumb = function (component) {
  15317. return getPartOrDie(component, detail, 'thumb');
  15318. };
  15319. var getSpectrum = function (component) {
  15320. return getPartOrDie(component, detail, 'spectrum');
  15321. };
  15322. var getLeftEdge = function (component) {
  15323. return getPart(component, detail, 'left-edge');
  15324. };
  15325. var getRightEdge = function (component) {
  15326. return getPart(component, detail, 'right-edge');
  15327. };
  15328. var getTopEdge = function (component) {
  15329. return getPart(component, detail, 'top-edge');
  15330. };
  15331. var getBottomEdge = function (component) {
  15332. return getPart(component, detail, 'bottom-edge');
  15333. };
  15334. var modelDetail = detail.model;
  15335. var model = modelDetail.manager;
  15336. var refresh = function (slider, thumb) {
  15337. model.setPositionFromValue(slider, thumb, detail, {
  15338. getLeftEdge: getLeftEdge,
  15339. getRightEdge: getRightEdge,
  15340. getTopEdge: getTopEdge,
  15341. getBottomEdge: getBottomEdge,
  15342. getSpectrum: getSpectrum
  15343. });
  15344. };
  15345. var setValue = function (slider, newValue) {
  15346. modelDetail.value.set(newValue);
  15347. var thumb = getThumb(slider);
  15348. refresh(slider, thumb);
  15349. };
  15350. var changeValue = function (slider, newValue) {
  15351. setValue(slider, newValue);
  15352. var thumb = getThumb(slider);
  15353. detail.onChange(slider, thumb, newValue);
  15354. return Optional.some(true);
  15355. };
  15356. var resetToMin = function (slider) {
  15357. model.setToMin(slider, detail);
  15358. };
  15359. var resetToMax = function (slider) {
  15360. model.setToMax(slider, detail);
  15361. };
  15362. var choose = function (slider) {
  15363. var fireOnChoose = function () {
  15364. getPart(slider, detail, 'thumb').each(function (thumb) {
  15365. var value = modelDetail.value.get();
  15366. detail.onChoose(slider, thumb, value);
  15367. });
  15368. };
  15369. var wasDown = detail.mouseIsDown.get();
  15370. detail.mouseIsDown.set(false);
  15371. if (wasDown) {
  15372. fireOnChoose();
  15373. }
  15374. };
  15375. var onDragStart = function (slider, simulatedEvent) {
  15376. simulatedEvent.stop();
  15377. detail.mouseIsDown.set(true);
  15378. detail.onDragStart(slider, getThumb(slider));
  15379. };
  15380. var onDragEnd = function (slider, simulatedEvent) {
  15381. simulatedEvent.stop();
  15382. detail.onDragEnd(slider, getThumb(slider));
  15383. choose(slider);
  15384. };
  15385. return {
  15386. uid: detail.uid,
  15387. dom: detail.dom,
  15388. components: components,
  15389. behaviours: augment(detail.sliderBehaviours, [
  15390. Keying.config({
  15391. mode: 'special',
  15392. focusIn: function (slider) {
  15393. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  15394. }
  15395. }),
  15396. Representing.config({
  15397. store: {
  15398. mode: 'manual',
  15399. getValue: function (_) {
  15400. return modelDetail.value.get();
  15401. }
  15402. }
  15403. }),
  15404. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  15405. ]),
  15406. events: derive$2([
  15407. run$1(sliderChangeEvent(), function (slider, simulatedEvent) {
  15408. changeValue(slider, simulatedEvent.event.value);
  15409. }),
  15410. runOnAttached(function (slider, _simulatedEvent) {
  15411. var getInitial = modelDetail.getInitialValue();
  15412. modelDetail.value.set(getInitial);
  15413. var thumb = getThumb(slider);
  15414. refresh(slider, thumb);
  15415. var spectrum = getSpectrum(slider);
  15416. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  15417. }),
  15418. run$1(touchstart(), onDragStart),
  15419. run$1(touchend(), onDragEnd),
  15420. run$1(mousedown(), onDragStart),
  15421. run$1(mouseup(), onDragEnd)
  15422. ]),
  15423. apis: {
  15424. resetToMin: resetToMin,
  15425. resetToMax: resetToMax,
  15426. setValue: setValue,
  15427. refresh: refresh
  15428. },
  15429. domModification: { styles: { position: 'relative' } }
  15430. };
  15431. };
  15432. var Slider = composite({
  15433. name: 'Slider',
  15434. configFields: SliderSchema,
  15435. partFields: SliderParts,
  15436. factory: sketch$2,
  15437. apis: {
  15438. setValue: function (apis, slider, value) {
  15439. apis.setValue(slider, value);
  15440. },
  15441. resetToMin: function (apis, slider) {
  15442. apis.resetToMin(slider);
  15443. },
  15444. resetToMax: function (apis, slider) {
  15445. apis.resetToMax(slider);
  15446. },
  15447. refresh: function (apis, slider) {
  15448. apis.refresh(slider);
  15449. }
  15450. }
  15451. });
  15452. var fieldsUpdate = generate$6('rgb-hex-update');
  15453. var sliderUpdate = generate$6('slider-update');
  15454. var paletteUpdate = generate$6('palette-update');
  15455. var sliderFactory = function (translate, getClass) {
  15456. var spectrum = Slider.parts.spectrum({
  15457. dom: {
  15458. tag: 'div',
  15459. classes: [getClass('hue-slider-spectrum')],
  15460. attributes: { role: 'presentation' }
  15461. }
  15462. });
  15463. var thumb = Slider.parts.thumb({
  15464. dom: {
  15465. tag: 'div',
  15466. classes: [getClass('hue-slider-thumb')],
  15467. attributes: { role: 'presentation' }
  15468. }
  15469. });
  15470. return Slider.sketch({
  15471. dom: {
  15472. tag: 'div',
  15473. classes: [getClass('hue-slider')],
  15474. attributes: { role: 'presentation' }
  15475. },
  15476. rounded: false,
  15477. model: {
  15478. mode: 'y',
  15479. getInitialValue: constant$1({ y: 0 })
  15480. },
  15481. components: [
  15482. spectrum,
  15483. thumb
  15484. ],
  15485. sliderBehaviours: derive$1([Focusing.config({})]),
  15486. onChange: function (slider, _thumb, value) {
  15487. emitWith(slider, sliderUpdate, { value: value });
  15488. }
  15489. });
  15490. };
  15491. var owner$1 = 'form';
  15492. var schema$i = [field('formBehaviours', [Representing])];
  15493. var getPartName$1 = function (name) {
  15494. return '<alloy.field.' + name + '>';
  15495. };
  15496. var sketch$1 = function (fSpec) {
  15497. var parts = function () {
  15498. var record = [];
  15499. var field = function (name, config) {
  15500. record.push(name);
  15501. return generateOne$1(owner$1, getPartName$1(name), config);
  15502. };
  15503. return {
  15504. field: field,
  15505. record: constant$1(record)
  15506. };
  15507. }();
  15508. var spec = fSpec(parts);
  15509. var partNames = parts.record();
  15510. var fieldParts = map$2(partNames, function (n) {
  15511. return required({
  15512. name: n,
  15513. pname: getPartName$1(n)
  15514. });
  15515. });
  15516. return composite$1(owner$1, schema$i, fieldParts, make$4, spec);
  15517. };
  15518. var toResult = function (o, e) {
  15519. return o.fold(function () {
  15520. return Result.error(e);
  15521. }, Result.value);
  15522. };
  15523. var make$4 = function (detail, components) {
  15524. return {
  15525. uid: detail.uid,
  15526. dom: detail.dom,
  15527. components: components,
  15528. behaviours: augment(detail.formBehaviours, [Representing.config({
  15529. store: {
  15530. mode: 'manual',
  15531. getValue: function (form) {
  15532. var resPs = getAllParts(form, detail);
  15533. return map$1(resPs, function (resPThunk, pName) {
  15534. return resPThunk().bind(function (v) {
  15535. var opt = Composing.getCurrent(v);
  15536. return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  15537. }).map(Representing.getValue);
  15538. });
  15539. },
  15540. setValue: function (form, values) {
  15541. each(values, function (newValue, key) {
  15542. getPart(form, detail, key).each(function (wrapper) {
  15543. Composing.getCurrent(wrapper).each(function (field) {
  15544. Representing.setValue(field, newValue);
  15545. });
  15546. });
  15547. });
  15548. }
  15549. }
  15550. })]),
  15551. apis: {
  15552. getField: function (form, key) {
  15553. return getPart(form, detail, key).bind(Composing.getCurrent);
  15554. }
  15555. }
  15556. };
  15557. };
  15558. var Form = {
  15559. getField: makeApi(function (apis, component, key) {
  15560. return apis.getField(component, key);
  15561. }),
  15562. sketch: sketch$1
  15563. };
  15564. var validInput = generate$6('valid-input');
  15565. var invalidInput = generate$6('invalid-input');
  15566. var validatingInput = generate$6('validating-input');
  15567. var translatePrefix = 'colorcustom.rgb.';
  15568. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  15569. var invalidation = function (label, isValid) {
  15570. return Invalidating.config({
  15571. invalidClass: getClass('invalid'),
  15572. notify: {
  15573. onValidate: function (comp) {
  15574. emitWith(comp, validatingInput, { type: label });
  15575. },
  15576. onValid: function (comp) {
  15577. emitWith(comp, validInput, {
  15578. type: label,
  15579. value: Representing.getValue(comp)
  15580. });
  15581. },
  15582. onInvalid: function (comp) {
  15583. emitWith(comp, invalidInput, {
  15584. type: label,
  15585. value: Representing.getValue(comp)
  15586. });
  15587. }
  15588. },
  15589. validator: {
  15590. validate: function (comp) {
  15591. var value = Representing.getValue(comp);
  15592. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  15593. return Future.pure(res);
  15594. },
  15595. validateOnLoad: false
  15596. }
  15597. });
  15598. };
  15599. var renderTextField = function (isValid, name, label, description, data) {
  15600. var helptext = translate(translatePrefix + 'range');
  15601. var pLabel = FormField.parts.label({
  15602. dom: {
  15603. tag: 'label',
  15604. innerHtml: label,
  15605. attributes: { 'aria-label': description }
  15606. }
  15607. });
  15608. var pField = FormField.parts.field({
  15609. data: data,
  15610. factory: Input,
  15611. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15612. inputClasses: [getClass('textfield')],
  15613. inputBehaviours: derive$1([
  15614. invalidation(name, isValid),
  15615. Tabstopping.config({})
  15616. ]),
  15617. onSetValue: function (input) {
  15618. if (Invalidating.isInvalid(input)) {
  15619. var run = Invalidating.run(input);
  15620. run.get(noop);
  15621. }
  15622. }
  15623. });
  15624. var comps = [
  15625. pLabel,
  15626. pField
  15627. ];
  15628. var concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : [];
  15629. var components = comps.concat(concats);
  15630. return {
  15631. dom: {
  15632. tag: 'div',
  15633. attributes: { role: 'presentation' }
  15634. },
  15635. components: components
  15636. };
  15637. };
  15638. var copyRgbToHex = function (form, rgba) {
  15639. var hex = fromRgba(rgba);
  15640. Form.getField(form, 'hex').each(function (hexField) {
  15641. if (!Focusing.isFocused(hexField)) {
  15642. Representing.setValue(form, { hex: hex.value });
  15643. }
  15644. });
  15645. return hex;
  15646. };
  15647. var copyRgbToForm = function (form, rgb) {
  15648. var red = rgb.red;
  15649. var green = rgb.green;
  15650. var blue = rgb.blue;
  15651. Representing.setValue(form, {
  15652. red: red,
  15653. green: green,
  15654. blue: blue
  15655. });
  15656. };
  15657. var memPreview = record({
  15658. dom: {
  15659. tag: 'div',
  15660. classes: [getClass('rgba-preview')],
  15661. styles: { 'background-color': 'white' },
  15662. attributes: { role: 'presentation' }
  15663. }
  15664. });
  15665. var updatePreview = function (anyInSystem, hex) {
  15666. memPreview.getOpt(anyInSystem).each(function (preview) {
  15667. set$7(preview.element, 'background-color', '#' + hex.value);
  15668. });
  15669. };
  15670. var factory = function () {
  15671. var state = {
  15672. red: Cell(Optional.some(255)),
  15673. green: Cell(Optional.some(255)),
  15674. blue: Cell(Optional.some(255)),
  15675. hex: Cell(Optional.some('ffffff'))
  15676. };
  15677. var copyHexToRgb = function (form, hex) {
  15678. var rgb = fromHex(hex);
  15679. copyRgbToForm(form, rgb);
  15680. setValueRgb(rgb);
  15681. };
  15682. var get = function (prop) {
  15683. return state[prop].get();
  15684. };
  15685. var set = function (prop, value) {
  15686. state[prop].set(value);
  15687. };
  15688. var getValueRgb = function () {
  15689. return get('red').bind(function (red) {
  15690. return get('green').bind(function (green) {
  15691. return get('blue').map(function (blue) {
  15692. return rgbaColour(red, green, blue, 1);
  15693. });
  15694. });
  15695. });
  15696. };
  15697. var setValueRgb = function (rgb) {
  15698. var red = rgb.red;
  15699. var green = rgb.green;
  15700. var blue = rgb.blue;
  15701. set('red', Optional.some(red));
  15702. set('green', Optional.some(green));
  15703. set('blue', Optional.some(blue));
  15704. };
  15705. var onInvalidInput = function (form, simulatedEvent) {
  15706. var data = simulatedEvent.event;
  15707. if (data.type !== 'hex') {
  15708. set(data.type, Optional.none());
  15709. } else {
  15710. onInvalidHexx(form);
  15711. }
  15712. };
  15713. var onValidHex = function (form, value) {
  15714. onValidHexx(form);
  15715. var hex = hexColour(value);
  15716. set('hex', Optional.some(value));
  15717. var rgb = fromHex(hex);
  15718. copyRgbToForm(form, rgb);
  15719. setValueRgb(rgb);
  15720. emitWith(form, fieldsUpdate, { hex: hex });
  15721. updatePreview(form, hex);
  15722. };
  15723. var onValidRgb = function (form, prop, value) {
  15724. var val = parseInt(value, 10);
  15725. set(prop, Optional.some(val));
  15726. getValueRgb().each(function (rgb) {
  15727. var hex = copyRgbToHex(form, rgb);
  15728. emitWith(form, fieldsUpdate, { hex: hex });
  15729. updatePreview(form, hex);
  15730. });
  15731. };
  15732. var isHexInputEvent = function (data) {
  15733. return data.type === 'hex';
  15734. };
  15735. var onValidInput = function (form, simulatedEvent) {
  15736. var data = simulatedEvent.event;
  15737. if (isHexInputEvent(data)) {
  15738. onValidHex(form, data.value);
  15739. } else {
  15740. onValidRgb(form, data.type, data.value);
  15741. }
  15742. };
  15743. var formPartStrings = function (key) {
  15744. return {
  15745. label: translate(translatePrefix + key + '.label'),
  15746. description: translate(translatePrefix + key + '.description')
  15747. };
  15748. };
  15749. var redStrings = formPartStrings('red');
  15750. var greenStrings = formPartStrings('green');
  15751. var blueStrings = formPartStrings('blue');
  15752. var hexStrings = formPartStrings('hex');
  15753. return deepMerge(Form.sketch(function (parts) {
  15754. return {
  15755. dom: {
  15756. tag: 'form',
  15757. classes: [getClass('rgb-form')],
  15758. attributes: { 'aria-label': translate('aria.color.picker') }
  15759. },
  15760. components: [
  15761. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  15762. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  15763. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  15764. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  15765. memPreview.asSpec()
  15766. ],
  15767. formBehaviours: derive$1([
  15768. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  15769. config('rgb-form-events', [
  15770. run$1(validInput, onValidInput),
  15771. run$1(invalidInput, onInvalidInput),
  15772. run$1(validatingInput, onInvalidInput)
  15773. ])
  15774. ])
  15775. };
  15776. }), {
  15777. apis: {
  15778. updateHex: function (form, hex) {
  15779. Representing.setValue(form, { hex: hex.value });
  15780. copyHexToRgb(form, hex);
  15781. updatePreview(form, hex);
  15782. }
  15783. }
  15784. });
  15785. };
  15786. var rgbFormSketcher = single({
  15787. factory: factory,
  15788. name: 'RgbForm',
  15789. configFields: [],
  15790. apis: {
  15791. updateHex: function (apis, form, hex) {
  15792. apis.updateHex(form, hex);
  15793. }
  15794. },
  15795. extraApis: {}
  15796. });
  15797. return rgbFormSketcher;
  15798. };
  15799. var paletteFactory = function (_translate, getClass) {
  15800. var spectrumPart = Slider.parts.spectrum({
  15801. dom: {
  15802. tag: 'canvas',
  15803. attributes: { role: 'presentation' },
  15804. classes: [getClass('sv-palette-spectrum')]
  15805. }
  15806. });
  15807. var thumbPart = Slider.parts.thumb({
  15808. dom: {
  15809. tag: 'div',
  15810. attributes: { role: 'presentation' },
  15811. classes: [getClass('sv-palette-thumb')],
  15812. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  15813. }
  15814. });
  15815. var setColour = function (canvas, rgba) {
  15816. var width = canvas.width, height = canvas.height;
  15817. var ctx = canvas.getContext('2d');
  15818. if (ctx === null) {
  15819. return;
  15820. }
  15821. ctx.fillStyle = rgba;
  15822. ctx.fillRect(0, 0, width, height);
  15823. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  15824. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  15825. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  15826. ctx.fillStyle = grdWhite;
  15827. ctx.fillRect(0, 0, width, height);
  15828. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  15829. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  15830. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  15831. ctx.fillStyle = grdBlack;
  15832. ctx.fillRect(0, 0, width, height);
  15833. };
  15834. var setPaletteHue = function (slider, hue) {
  15835. var canvas = slider.components()[0].element.dom;
  15836. var hsv = hsvColour(hue, 100, 100);
  15837. var rgba = fromHsv(hsv);
  15838. setColour(canvas, toString(rgba));
  15839. };
  15840. var setPaletteThumb = function (slider, hex) {
  15841. var hsv = fromRgb(fromHex(hex));
  15842. Slider.setValue(slider, {
  15843. x: hsv.saturation,
  15844. y: 100 - hsv.value
  15845. });
  15846. };
  15847. var factory = function (_detail) {
  15848. var getInitialValue = constant$1({
  15849. x: 0,
  15850. y: 0
  15851. });
  15852. var onChange = function (slider, _thumb, value) {
  15853. emitWith(slider, paletteUpdate, { value: value });
  15854. };
  15855. var onInit = function (_slider, _thumb, spectrum, _value) {
  15856. setColour(spectrum.element.dom, toString(red));
  15857. };
  15858. var sliderBehaviours = derive$1([
  15859. Composing.config({ find: Optional.some }),
  15860. Focusing.config({})
  15861. ]);
  15862. return Slider.sketch({
  15863. dom: {
  15864. tag: 'div',
  15865. attributes: { role: 'presentation' },
  15866. classes: [getClass('sv-palette')]
  15867. },
  15868. model: {
  15869. mode: 'xy',
  15870. getInitialValue: getInitialValue
  15871. },
  15872. rounded: false,
  15873. components: [
  15874. spectrumPart,
  15875. thumbPart
  15876. ],
  15877. onChange: onChange,
  15878. onInit: onInit,
  15879. sliderBehaviours: sliderBehaviours
  15880. });
  15881. };
  15882. var saturationBrightnessPaletteSketcher = single({
  15883. factory: factory,
  15884. name: 'SaturationBrightnessPalette',
  15885. configFields: [],
  15886. apis: {
  15887. setHue: function (_apis, slider, hue) {
  15888. setPaletteHue(slider, hue);
  15889. },
  15890. setThumb: function (_apis, slider, hex) {
  15891. setPaletteThumb(slider, hex);
  15892. }
  15893. },
  15894. extraApis: {}
  15895. });
  15896. return saturationBrightnessPaletteSketcher;
  15897. };
  15898. var makeFactory = function (translate, getClass) {
  15899. var factory = function (detail) {
  15900. var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  15901. var sbPalette = paletteFactory(translate, getClass);
  15902. var hueSliderToDegrees = function (hue) {
  15903. return (100 - hue) / 100 * 360;
  15904. };
  15905. var hueDegreesToSlider = function (hue) {
  15906. return 100 - hue / 360 * 100;
  15907. };
  15908. var state = {
  15909. paletteRgba: Cell(red),
  15910. paletteHue: Cell(0)
  15911. };
  15912. var memSlider = record(sliderFactory(translate, getClass));
  15913. var memPalette = record(sbPalette.sketch({}));
  15914. var memRgb = record(rgbForm.sketch({}));
  15915. var updatePalette = function (anyInSystem, _hex, hue) {
  15916. memPalette.getOpt(anyInSystem).each(function (palette) {
  15917. sbPalette.setHue(palette, hue);
  15918. });
  15919. };
  15920. var updateFields = function (anyInSystem, hex) {
  15921. memRgb.getOpt(anyInSystem).each(function (form) {
  15922. rgbForm.updateHex(form, hex);
  15923. });
  15924. };
  15925. var updateSlider = function (anyInSystem, _hex, hue) {
  15926. memSlider.getOpt(anyInSystem).each(function (slider) {
  15927. Slider.setValue(slider, { y: hueDegreesToSlider(hue) });
  15928. });
  15929. };
  15930. var updatePaletteThumb = function (anyInSystem, hex) {
  15931. memPalette.getOpt(anyInSystem).each(function (palette) {
  15932. sbPalette.setThumb(palette, hex);
  15933. });
  15934. };
  15935. var updateState = function (hex, hue) {
  15936. var rgba = fromHex(hex);
  15937. state.paletteRgba.set(rgba);
  15938. state.paletteHue.set(hue);
  15939. };
  15940. var runUpdates = function (anyInSystem, hex, hue, updates) {
  15941. updateState(hex, hue);
  15942. each$1(updates, function (update) {
  15943. update(anyInSystem, hex, hue);
  15944. });
  15945. };
  15946. var onPaletteUpdate = function () {
  15947. var updates = [updateFields];
  15948. return function (form, simulatedEvent) {
  15949. var value = simulatedEvent.event.value;
  15950. var oldHue = state.paletteHue.get();
  15951. var newHsv = hsvColour(oldHue, value.x, 100 - value.y);
  15952. var newHex = hsvToHex(newHsv);
  15953. runUpdates(form, newHex, oldHue, updates);
  15954. };
  15955. };
  15956. var onSliderUpdate = function () {
  15957. var updates = [
  15958. updatePalette,
  15959. updateFields
  15960. ];
  15961. return function (form, simulatedEvent) {
  15962. var hue = hueSliderToDegrees(simulatedEvent.event.value.y);
  15963. var oldRgb = state.paletteRgba.get();
  15964. var oldHsv = fromRgb(oldRgb);
  15965. var newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value);
  15966. var newHex = hsvToHex(newHsv);
  15967. runUpdates(form, newHex, hue, updates);
  15968. };
  15969. };
  15970. var onFieldsUpdate = function () {
  15971. var updates = [
  15972. updatePalette,
  15973. updateSlider,
  15974. updatePaletteThumb
  15975. ];
  15976. return function (form, simulatedEvent) {
  15977. var hex = simulatedEvent.event.hex;
  15978. var hsv = hexToHsv(hex);
  15979. runUpdates(form, hex, hsv.hue, updates);
  15980. };
  15981. };
  15982. return {
  15983. uid: detail.uid,
  15984. dom: detail.dom,
  15985. components: [
  15986. memPalette.asSpec(),
  15987. memSlider.asSpec(),
  15988. memRgb.asSpec()
  15989. ],
  15990. behaviours: derive$1([
  15991. config('colour-picker-events', [
  15992. run$1(fieldsUpdate, onFieldsUpdate()),
  15993. run$1(paletteUpdate, onPaletteUpdate()),
  15994. run$1(sliderUpdate, onSliderUpdate())
  15995. ]),
  15996. Composing.config({
  15997. find: function (comp) {
  15998. return memRgb.getOpt(comp);
  15999. }
  16000. }),
  16001. Keying.config({ mode: 'acyclic' })
  16002. ])
  16003. };
  16004. };
  16005. var colourPickerSketcher = single({
  16006. name: 'ColourPicker',
  16007. configFields: [
  16008. required$1('dom'),
  16009. defaulted('onValidHex', noop),
  16010. defaulted('onInvalidHex', noop)
  16011. ],
  16012. factory: factory
  16013. });
  16014. return colourPickerSketcher;
  16015. };
  16016. var self$1 = function () {
  16017. return Composing.config({ find: Optional.some });
  16018. };
  16019. var memento$1 = function (mem) {
  16020. return Composing.config({ find: mem.getOpt });
  16021. };
  16022. var childAt = function (index) {
  16023. return Composing.config({
  16024. find: function (comp) {
  16025. return child$2(comp.element, index).bind(function (element) {
  16026. return comp.getSystem().getByDom(element).toOptional();
  16027. });
  16028. }
  16029. });
  16030. };
  16031. var ComposingConfigs = {
  16032. self: self$1,
  16033. memento: memento$1,
  16034. childAt: childAt
  16035. };
  16036. var english = {
  16037. 'colorcustom.rgb.red.label': 'R',
  16038. 'colorcustom.rgb.red.description': 'Red component',
  16039. 'colorcustom.rgb.green.label': 'G',
  16040. 'colorcustom.rgb.green.description': 'Green component',
  16041. 'colorcustom.rgb.blue.label': 'B',
  16042. 'colorcustom.rgb.blue.description': 'Blue component',
  16043. 'colorcustom.rgb.hex.label': '#',
  16044. 'colorcustom.rgb.hex.description': 'Hex color code',
  16045. 'colorcustom.rgb.range': 'Range 0 to 255',
  16046. 'colorcustom.sb.saturation': 'Saturation',
  16047. 'colorcustom.sb.brightness': 'Brightness',
  16048. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  16049. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  16050. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  16051. 'colorcustom.hue.hue': 'Hue',
  16052. 'colorcustom.hue.slider': 'Hue Slider',
  16053. 'colorcustom.hue.palette': 'Hue Palette',
  16054. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  16055. 'aria.color.picker': 'Color Picker',
  16056. 'aria.input.invalid': 'Invalid input'
  16057. };
  16058. var getEnglishText = function (key) {
  16059. return english[key];
  16060. };
  16061. var translate$1 = function (key) {
  16062. return getEnglishText(key);
  16063. };
  16064. var renderColorPicker = function (_spec) {
  16065. var getClass = function (key) {
  16066. return 'tox-' + key;
  16067. };
  16068. var colourPickerFactory = makeFactory(translate$1, getClass);
  16069. var onValidHex = function (form) {
  16070. emitWith(form, formActionEvent, {
  16071. name: 'hex-valid',
  16072. value: true
  16073. });
  16074. };
  16075. var onInvalidHex = function (form) {
  16076. emitWith(form, formActionEvent, {
  16077. name: 'hex-valid',
  16078. value: false
  16079. });
  16080. };
  16081. var memPicker = record(colourPickerFactory.sketch({
  16082. dom: {
  16083. tag: 'div',
  16084. classes: [getClass('color-picker-container')],
  16085. attributes: { role: 'presentation' }
  16086. },
  16087. onValidHex: onValidHex,
  16088. onInvalidHex: onInvalidHex
  16089. }));
  16090. return {
  16091. dom: { tag: 'div' },
  16092. components: [memPicker.asSpec()],
  16093. behaviours: derive$1([
  16094. Representing.config({
  16095. store: {
  16096. mode: 'manual',
  16097. getValue: function (comp) {
  16098. var picker = memPicker.get(comp);
  16099. var optRgbForm = Composing.getCurrent(picker);
  16100. var optHex = optRgbForm.bind(function (rgbForm) {
  16101. var formValues = Representing.getValue(rgbForm);
  16102. return formValues.hex;
  16103. });
  16104. return optHex.map(function (hex) {
  16105. return '#' + hex;
  16106. }).getOr('');
  16107. },
  16108. setValue: function (comp, newValue) {
  16109. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  16110. var m = pattern.exec(newValue);
  16111. var picker = memPicker.get(comp);
  16112. var optRgbForm = Composing.getCurrent(picker);
  16113. optRgbForm.fold(function () {
  16114. console.log('Can not find form');
  16115. }, function (rgbForm) {
  16116. Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') });
  16117. Form.getField(rgbForm, 'hex').each(function (hexField) {
  16118. emit(hexField, input());
  16119. });
  16120. });
  16121. }
  16122. }
  16123. }),
  16124. ComposingConfigs.self()
  16125. ])
  16126. };
  16127. };
  16128. var global$6 = tinymce.util.Tools.resolve('tinymce.Resource');
  16129. var isOldCustomEditor = function (spec) {
  16130. return has$2(spec, 'init');
  16131. };
  16132. var renderCustomEditor = function (spec) {
  16133. var editorApi = value$1();
  16134. var memReplaced = record({ dom: { tag: spec.tag } });
  16135. var initialValue = value$1();
  16136. return {
  16137. dom: {
  16138. tag: 'div',
  16139. classes: ['tox-custom-editor']
  16140. },
  16141. behaviours: derive$1([
  16142. config('custom-editor-events', [runOnAttached(function (component) {
  16143. memReplaced.getOpt(component).each(function (ta) {
  16144. (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$6.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  16145. return init(ta.element.dom, spec.settings);
  16146. })).then(function (ea) {
  16147. initialValue.on(function (cvalue) {
  16148. ea.setValue(cvalue);
  16149. });
  16150. initialValue.clear();
  16151. editorApi.set(ea);
  16152. });
  16153. });
  16154. })]),
  16155. Representing.config({
  16156. store: {
  16157. mode: 'manual',
  16158. getValue: function () {
  16159. return editorApi.get().fold(function () {
  16160. return initialValue.get().getOr('');
  16161. }, function (ed) {
  16162. return ed.getValue();
  16163. });
  16164. },
  16165. setValue: function (component, value) {
  16166. editorApi.get().fold(function () {
  16167. initialValue.set(value);
  16168. }, function (ed) {
  16169. return ed.setValue(value);
  16170. });
  16171. }
  16172. }
  16173. }),
  16174. ComposingConfigs.self()
  16175. ]),
  16176. components: [memReplaced.asSpec()]
  16177. };
  16178. };
  16179. var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  16180. var processors = objOf([
  16181. defaulted('preprocess', identity$1),
  16182. defaulted('postprocess', identity$1)
  16183. ]);
  16184. var memento = function (mem, rawProcessors) {
  16185. var ps = asRawOrDie$1('RepresentingConfigs.memento processors', processors, rawProcessors);
  16186. return Representing.config({
  16187. store: {
  16188. mode: 'manual',
  16189. getValue: function (comp) {
  16190. var other = mem.get(comp);
  16191. var rawValue = Representing.getValue(other);
  16192. return ps.postprocess(rawValue);
  16193. },
  16194. setValue: function (comp, rawValue) {
  16195. var newValue = ps.preprocess(rawValue);
  16196. var other = mem.get(comp);
  16197. Representing.setValue(other, newValue);
  16198. }
  16199. }
  16200. });
  16201. };
  16202. var withComp = function (optInitialValue, getter, setter) {
  16203. return Representing.config(deepMerge({
  16204. store: {
  16205. mode: 'manual',
  16206. getValue: getter,
  16207. setValue: setter
  16208. }
  16209. }, optInitialValue.map(function (initialValue) {
  16210. return { store: { initialValue: initialValue } };
  16211. }).getOr({})));
  16212. };
  16213. var withElement = function (initialValue, getter, setter) {
  16214. return withComp(initialValue, function (c) {
  16215. return getter(c.element);
  16216. }, function (c, v) {
  16217. return setter(c.element, v);
  16218. });
  16219. };
  16220. var domValue = function (optInitialValue) {
  16221. return withElement(optInitialValue, get$5, set$4);
  16222. };
  16223. var domHtml = function (optInitialValue) {
  16224. return withElement(optInitialValue, get$7, set$5);
  16225. };
  16226. var memory = function (initialValue) {
  16227. return Representing.config({
  16228. store: {
  16229. mode: 'memory',
  16230. initialValue: initialValue
  16231. }
  16232. });
  16233. };
  16234. var RepresentingConfigs = {
  16235. memento: memento,
  16236. withElement: withElement,
  16237. withComp: withComp,
  16238. domValue: domValue,
  16239. domHtml: domHtml,
  16240. memory: memory
  16241. };
  16242. var defaultImageFileTypes = 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp';
  16243. var filterByExtension = function (files, providersBackstage) {
  16244. var allowedImageFileTypes = global$5.explode(providersBackstage.getSetting('images_file_types', defaultImageFileTypes, 'string'));
  16245. var isFileInAllowedTypes = function (file) {
  16246. return exists(allowedImageFileTypes, function (type) {
  16247. return endsWith(file.name.toLowerCase(), '.' + type.toLowerCase());
  16248. });
  16249. };
  16250. return filter$2(from(files), isFileInAllowedTypes);
  16251. };
  16252. var renderDropZone = function (spec, providersBackstage) {
  16253. var stopper = function (_, se) {
  16254. se.stop();
  16255. };
  16256. var sequence = function (actions) {
  16257. return function (comp, se) {
  16258. each$1(actions, function (a) {
  16259. a(comp, se);
  16260. });
  16261. };
  16262. };
  16263. var onDrop = function (comp, se) {
  16264. if (!Disabling.isDisabled(comp)) {
  16265. var transferEvent = se.event.raw;
  16266. handleFiles(comp, transferEvent.dataTransfer.files);
  16267. }
  16268. };
  16269. var onSelect = function (component, simulatedEvent) {
  16270. var input = simulatedEvent.event.raw.target;
  16271. handleFiles(component, input.files);
  16272. };
  16273. var handleFiles = function (component, files) {
  16274. Representing.setValue(component, filterByExtension(files, providersBackstage));
  16275. emitWith(component, formChangeEvent, { name: spec.name });
  16276. };
  16277. var memInput = record({
  16278. dom: {
  16279. tag: 'input',
  16280. attributes: {
  16281. type: 'file',
  16282. accept: 'image/*'
  16283. },
  16284. styles: { display: 'none' }
  16285. },
  16286. behaviours: derive$1([config('input-file-events', [
  16287. cutter(click()),
  16288. cutter(tap())
  16289. ])])
  16290. });
  16291. var renderField = function (s) {
  16292. return {
  16293. uid: s.uid,
  16294. dom: {
  16295. tag: 'div',
  16296. classes: ['tox-dropzone-container']
  16297. },
  16298. behaviours: derive$1([
  16299. RepresentingConfigs.memory([]),
  16300. ComposingConfigs.self(),
  16301. Disabling.config({}),
  16302. Toggling.config({
  16303. toggleClass: 'dragenter',
  16304. toggleOnExecute: false
  16305. }),
  16306. config('dropzone-events', [
  16307. run$1('dragenter', sequence([
  16308. stopper,
  16309. Toggling.toggle
  16310. ])),
  16311. run$1('dragleave', sequence([
  16312. stopper,
  16313. Toggling.toggle
  16314. ])),
  16315. run$1('dragover', stopper),
  16316. run$1('drop', sequence([
  16317. stopper,
  16318. onDrop
  16319. ])),
  16320. run$1(change(), onSelect)
  16321. ])
  16322. ]),
  16323. components: [{
  16324. dom: {
  16325. tag: 'div',
  16326. classes: ['tox-dropzone'],
  16327. styles: {}
  16328. },
  16329. components: [
  16330. {
  16331. dom: {
  16332. tag: 'p',
  16333. innerHtml: providersBackstage.translate('Drop an image here')
  16334. }
  16335. },
  16336. Button.sketch({
  16337. dom: {
  16338. tag: 'button',
  16339. innerHtml: providersBackstage.translate('Browse for an image'),
  16340. styles: { position: 'relative' },
  16341. classes: [
  16342. 'tox-button',
  16343. 'tox-button--secondary'
  16344. ]
  16345. },
  16346. components: [memInput.asSpec()],
  16347. action: function (comp) {
  16348. var inputComp = memInput.get(comp);
  16349. inputComp.element.dom.click();
  16350. },
  16351. buttonBehaviours: derive$1([
  16352. Tabstopping.config({}),
  16353. DisablingConfigs.button(providersBackstage.isDisabled),
  16354. receivingConfig()
  16355. ])
  16356. })
  16357. ]
  16358. }]
  16359. };
  16360. };
  16361. var pLabel = spec.label.map(function (label) {
  16362. return renderLabel$2(label, providersBackstage);
  16363. });
  16364. var pField = FormField.parts.field({ factory: { sketch: renderField } });
  16365. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16366. };
  16367. var renderGrid = function (spec, backstage) {
  16368. return {
  16369. dom: {
  16370. tag: 'div',
  16371. classes: [
  16372. 'tox-form__grid',
  16373. 'tox-form__grid--' + spec.columns + 'col'
  16374. ]
  16375. },
  16376. components: map$2(spec.items, backstage.interpreter)
  16377. };
  16378. };
  16379. var beforeObject = generate$6('alloy-fake-before-tabstop');
  16380. var afterObject = generate$6('alloy-fake-after-tabstop');
  16381. var craftWithClasses = function (classes) {
  16382. return {
  16383. dom: {
  16384. tag: 'div',
  16385. styles: {
  16386. width: '1px',
  16387. height: '1px',
  16388. outline: 'none'
  16389. },
  16390. attributes: { tabindex: '0' },
  16391. classes: classes
  16392. },
  16393. behaviours: derive$1([
  16394. Focusing.config({ ignore: true }),
  16395. Tabstopping.config({})
  16396. ])
  16397. };
  16398. };
  16399. var craft = function (spec) {
  16400. return {
  16401. dom: {
  16402. tag: 'div',
  16403. classes: ['tox-navobj']
  16404. },
  16405. components: [
  16406. craftWithClasses([beforeObject]),
  16407. spec,
  16408. craftWithClasses([afterObject])
  16409. ],
  16410. behaviours: derive$1([ComposingConfigs.childAt(1)])
  16411. };
  16412. };
  16413. var triggerTab = function (placeholder, shiftKey) {
  16414. emitWith(placeholder, keydown(), {
  16415. raw: {
  16416. which: 9,
  16417. shiftKey: shiftKey
  16418. }
  16419. });
  16420. };
  16421. var onFocus = function (container, targetComp) {
  16422. var target = targetComp.element;
  16423. if (has(target, beforeObject)) {
  16424. triggerTab(container, true);
  16425. } else if (has(target, afterObject)) {
  16426. triggerTab(container, false);
  16427. }
  16428. };
  16429. var isPseudoStop = function (element) {
  16430. return closest(element, [
  16431. '.' + beforeObject,
  16432. '.' + afterObject
  16433. ].join(','), never);
  16434. };
  16435. var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge());
  16436. var getDynamicSource = function (isSandbox) {
  16437. var cachedValue = Cell('');
  16438. return {
  16439. getValue: function (_frameComponent) {
  16440. return cachedValue.get();
  16441. },
  16442. setValue: function (frameComponent, html) {
  16443. if (!isSandbox) {
  16444. set$8(frameComponent.element, 'src', 'javascript:\'\'');
  16445. var doc = frameComponent.element.dom.contentWindow.document;
  16446. doc.open();
  16447. doc.write(html);
  16448. doc.close();
  16449. } else {
  16450. set$8(frameComponent.element, 'srcdoc', html);
  16451. }
  16452. cachedValue.set(html);
  16453. }
  16454. };
  16455. };
  16456. var renderIFrame = function (spec, providersBackstage) {
  16457. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  16458. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  16459. return { title: title };
  16460. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  16461. var sourcing = getDynamicSource(isSandbox);
  16462. var pLabel = spec.label.map(function (label) {
  16463. return renderLabel$2(label, providersBackstage);
  16464. });
  16465. var factory = function (newSpec) {
  16466. return craft({
  16467. uid: newSpec.uid,
  16468. dom: {
  16469. tag: 'iframe',
  16470. attributes: attributes
  16471. },
  16472. behaviours: derive$1([
  16473. Tabstopping.config({}),
  16474. Focusing.config({}),
  16475. RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue)
  16476. ])
  16477. });
  16478. };
  16479. var pField = FormField.parts.field({ factory: { sketch: factory } });
  16480. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  16481. };
  16482. var create$3 = function (width, height) {
  16483. return resize$3(document.createElement('canvas'), width, height);
  16484. };
  16485. var clone = function (canvas) {
  16486. var tCanvas = create$3(canvas.width, canvas.height);
  16487. var ctx = get2dContext(tCanvas);
  16488. ctx.drawImage(canvas, 0, 0);
  16489. return tCanvas;
  16490. };
  16491. var get2dContext = function (canvas) {
  16492. return canvas.getContext('2d');
  16493. };
  16494. var resize$3 = function (canvas, width, height) {
  16495. canvas.width = width;
  16496. canvas.height = height;
  16497. return canvas;
  16498. };
  16499. var getWidth$1 = function (image) {
  16500. return image.naturalWidth || image.width;
  16501. };
  16502. var getHeight$1 = function (image) {
  16503. return image.naturalHeight || image.height;
  16504. };
  16505. var blobToImage = function (blob) {
  16506. return new Promise$1(function (resolve, reject) {
  16507. var blobUrl = URL.createObjectURL(blob);
  16508. var image = new Image();
  16509. var removeListeners = function () {
  16510. image.removeEventListener('load', loaded);
  16511. image.removeEventListener('error', error);
  16512. };
  16513. var loaded = function () {
  16514. removeListeners();
  16515. resolve(image);
  16516. };
  16517. var error = function () {
  16518. removeListeners();
  16519. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16520. };
  16521. image.addEventListener('load', loaded);
  16522. image.addEventListener('error', error);
  16523. image.src = blobUrl;
  16524. if (image.complete) {
  16525. setTimeout(loaded, 0);
  16526. }
  16527. });
  16528. };
  16529. var dataUriToBlobSync = function (uri) {
  16530. var data = uri.split(',');
  16531. var matches = /data:([^;]+)/.exec(data[0]);
  16532. if (!matches) {
  16533. return Optional.none();
  16534. }
  16535. var mimetype = matches[1];
  16536. var base64 = data[1];
  16537. var sliceSize = 1024;
  16538. var byteCharacters = atob(base64);
  16539. var bytesLength = byteCharacters.length;
  16540. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16541. var byteArrays = new Array(slicesCount);
  16542. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16543. var begin = sliceIndex * sliceSize;
  16544. var end = Math.min(begin + sliceSize, bytesLength);
  16545. var bytes = new Array(end - begin);
  16546. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  16547. bytes[i] = byteCharacters[offset].charCodeAt(0);
  16548. }
  16549. byteArrays[sliceIndex] = new Uint8Array(bytes);
  16550. }
  16551. return Optional.some(new Blob(byteArrays, { type: mimetype }));
  16552. };
  16553. var dataUriToBlob = function (uri) {
  16554. return new Promise$1(function (resolve, reject) {
  16555. dataUriToBlobSync(uri).fold(function () {
  16556. reject('uri is not base64: ' + uri);
  16557. }, resolve);
  16558. });
  16559. };
  16560. var canvasToBlob = function (canvas, type, quality) {
  16561. type = type || 'image/png';
  16562. if (isFunction(HTMLCanvasElement.prototype.toBlob)) {
  16563. return new Promise$1(function (resolve, reject) {
  16564. canvas.toBlob(function (blob) {
  16565. if (blob) {
  16566. resolve(blob);
  16567. } else {
  16568. reject();
  16569. }
  16570. }, type, quality);
  16571. });
  16572. } else {
  16573. return dataUriToBlob(canvas.toDataURL(type, quality));
  16574. }
  16575. };
  16576. var canvasToDataURL = function (canvas, type, quality) {
  16577. type = type || 'image/png';
  16578. return canvas.toDataURL(type, quality);
  16579. };
  16580. var blobToCanvas = function (blob) {
  16581. return blobToImage(blob).then(function (image) {
  16582. revokeImageUrl(image);
  16583. var canvas = create$3(getWidth$1(image), getHeight$1(image));
  16584. var context = get2dContext(canvas);
  16585. context.drawImage(image, 0, 0);
  16586. return canvas;
  16587. });
  16588. };
  16589. var blobToDataUri = function (blob) {
  16590. return new Promise$1(function (resolve) {
  16591. var reader = new FileReader();
  16592. reader.onloadend = function () {
  16593. resolve(reader.result);
  16594. };
  16595. reader.readAsDataURL(blob);
  16596. });
  16597. };
  16598. var revokeImageUrl = function (image) {
  16599. URL.revokeObjectURL(image.src);
  16600. };
  16601. var create$2 = function (getCanvas, blob, uri) {
  16602. var initialType = blob.type;
  16603. var getType = constant$1(initialType);
  16604. var toBlob = function () {
  16605. return Promise$1.resolve(blob);
  16606. };
  16607. var toDataURL = constant$1(uri);
  16608. var toBase64 = function () {
  16609. return uri.split(',')[1];
  16610. };
  16611. var toAdjustedBlob = function (type, quality) {
  16612. return getCanvas.then(function (canvas) {
  16613. return canvasToBlob(canvas, type, quality);
  16614. });
  16615. };
  16616. var toAdjustedDataURL = function (type, quality) {
  16617. return getCanvas.then(function (canvas) {
  16618. return canvasToDataURL(canvas, type, quality);
  16619. });
  16620. };
  16621. var toAdjustedBase64 = function (type, quality) {
  16622. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  16623. return dataurl.split(',')[1];
  16624. });
  16625. };
  16626. var toCanvas = function () {
  16627. return getCanvas.then(clone);
  16628. };
  16629. return {
  16630. getType: getType,
  16631. toBlob: toBlob,
  16632. toDataURL: toDataURL,
  16633. toBase64: toBase64,
  16634. toAdjustedBlob: toAdjustedBlob,
  16635. toAdjustedDataURL: toAdjustedDataURL,
  16636. toAdjustedBase64: toAdjustedBase64,
  16637. toCanvas: toCanvas
  16638. };
  16639. };
  16640. var fromBlob = function (blob) {
  16641. return blobToDataUri(blob).then(function (uri) {
  16642. return create$2(blobToCanvas(blob), blob, uri);
  16643. });
  16644. };
  16645. var fromCanvas = function (canvas, type) {
  16646. return canvasToBlob(canvas, type).then(function (blob) {
  16647. return create$2(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  16648. });
  16649. };
  16650. var blobToImageResult = function (blob) {
  16651. return fromBlob(blob);
  16652. };
  16653. var clamp = function (value, min, max) {
  16654. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  16655. if (parsedValue > max) {
  16656. parsedValue = max;
  16657. } else if (parsedValue < min) {
  16658. parsedValue = min;
  16659. }
  16660. return parsedValue;
  16661. };
  16662. var identity = function () {
  16663. return [
  16664. 1,
  16665. 0,
  16666. 0,
  16667. 0,
  16668. 0,
  16669. 0,
  16670. 1,
  16671. 0,
  16672. 0,
  16673. 0,
  16674. 0,
  16675. 0,
  16676. 1,
  16677. 0,
  16678. 0,
  16679. 0,
  16680. 0,
  16681. 0,
  16682. 1,
  16683. 0,
  16684. 0,
  16685. 0,
  16686. 0,
  16687. 0,
  16688. 1
  16689. ];
  16690. };
  16691. var DELTA_INDEX = [
  16692. 0,
  16693. 0.01,
  16694. 0.02,
  16695. 0.04,
  16696. 0.05,
  16697. 0.06,
  16698. 0.07,
  16699. 0.08,
  16700. 0.1,
  16701. 0.11,
  16702. 0.12,
  16703. 0.14,
  16704. 0.15,
  16705. 0.16,
  16706. 0.17,
  16707. 0.18,
  16708. 0.2,
  16709. 0.21,
  16710. 0.22,
  16711. 0.24,
  16712. 0.25,
  16713. 0.27,
  16714. 0.28,
  16715. 0.3,
  16716. 0.32,
  16717. 0.34,
  16718. 0.36,
  16719. 0.38,
  16720. 0.4,
  16721. 0.42,
  16722. 0.44,
  16723. 0.46,
  16724. 0.48,
  16725. 0.5,
  16726. 0.53,
  16727. 0.56,
  16728. 0.59,
  16729. 0.62,
  16730. 0.65,
  16731. 0.68,
  16732. 0.71,
  16733. 0.74,
  16734. 0.77,
  16735. 0.8,
  16736. 0.83,
  16737. 0.86,
  16738. 0.89,
  16739. 0.92,
  16740. 0.95,
  16741. 0.98,
  16742. 1,
  16743. 1.06,
  16744. 1.12,
  16745. 1.18,
  16746. 1.24,
  16747. 1.3,
  16748. 1.36,
  16749. 1.42,
  16750. 1.48,
  16751. 1.54,
  16752. 1.6,
  16753. 1.66,
  16754. 1.72,
  16755. 1.78,
  16756. 1.84,
  16757. 1.9,
  16758. 1.96,
  16759. 2,
  16760. 2.12,
  16761. 2.25,
  16762. 2.37,
  16763. 2.5,
  16764. 2.62,
  16765. 2.75,
  16766. 2.87,
  16767. 3,
  16768. 3.2,
  16769. 3.4,
  16770. 3.6,
  16771. 3.8,
  16772. 4,
  16773. 4.3,
  16774. 4.7,
  16775. 4.9,
  16776. 5,
  16777. 5.5,
  16778. 6,
  16779. 6.5,
  16780. 6.8,
  16781. 7,
  16782. 7.3,
  16783. 7.5,
  16784. 7.8,
  16785. 8,
  16786. 8.4,
  16787. 8.7,
  16788. 9,
  16789. 9.4,
  16790. 9.6,
  16791. 9.8,
  16792. 10
  16793. ];
  16794. var multiply = function (matrix1, matrix2) {
  16795. var col = [];
  16796. var out = new Array(25);
  16797. var val;
  16798. for (var i = 0; i < 5; i++) {
  16799. for (var j = 0; j < 5; j++) {
  16800. col[j] = matrix2[j + i * 5];
  16801. }
  16802. for (var j = 0; j < 5; j++) {
  16803. val = 0;
  16804. for (var k = 0; k < 5; k++) {
  16805. val += matrix1[j + k * 5] * col[k];
  16806. }
  16807. out[j + i * 5] = val;
  16808. }
  16809. }
  16810. return out;
  16811. };
  16812. var adjustContrast = function (matrix, value) {
  16813. var x;
  16814. value = clamp(value, -1, 1);
  16815. value *= 100;
  16816. if (value < 0) {
  16817. x = 127 + value / 100 * 127;
  16818. } else {
  16819. x = value % 1;
  16820. if (x === 0) {
  16821. x = DELTA_INDEX[value];
  16822. } else {
  16823. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  16824. }
  16825. x = x * 127 + 127;
  16826. }
  16827. return multiply(matrix, [
  16828. x / 127,
  16829. 0,
  16830. 0,
  16831. 0,
  16832. 0.5 * (127 - x),
  16833. 0,
  16834. x / 127,
  16835. 0,
  16836. 0,
  16837. 0.5 * (127 - x),
  16838. 0,
  16839. 0,
  16840. x / 127,
  16841. 0,
  16842. 0.5 * (127 - x),
  16843. 0,
  16844. 0,
  16845. 0,
  16846. 1,
  16847. 0,
  16848. 0,
  16849. 0,
  16850. 0,
  16851. 0,
  16852. 1
  16853. ]);
  16854. };
  16855. var adjustBrightness = function (matrix, value) {
  16856. value = clamp(255 * value, -255, 255);
  16857. return multiply(matrix, [
  16858. 1,
  16859. 0,
  16860. 0,
  16861. 0,
  16862. value,
  16863. 0,
  16864. 1,
  16865. 0,
  16866. 0,
  16867. value,
  16868. 0,
  16869. 0,
  16870. 1,
  16871. 0,
  16872. value,
  16873. 0,
  16874. 0,
  16875. 0,
  16876. 1,
  16877. 0,
  16878. 0,
  16879. 0,
  16880. 0,
  16881. 0,
  16882. 1
  16883. ]);
  16884. };
  16885. var adjustColors = function (matrix, adjustR, adjustG, adjustB) {
  16886. adjustR = clamp(adjustR, 0, 2);
  16887. adjustG = clamp(adjustG, 0, 2);
  16888. adjustB = clamp(adjustB, 0, 2);
  16889. return multiply(matrix, [
  16890. adjustR,
  16891. 0,
  16892. 0,
  16893. 0,
  16894. 0,
  16895. 0,
  16896. adjustG,
  16897. 0,
  16898. 0,
  16899. 0,
  16900. 0,
  16901. 0,
  16902. adjustB,
  16903. 0,
  16904. 0,
  16905. 0,
  16906. 0,
  16907. 0,
  16908. 1,
  16909. 0,
  16910. 0,
  16911. 0,
  16912. 0,
  16913. 0,
  16914. 1
  16915. ]);
  16916. };
  16917. var colorFilter = function (ir, matrix) {
  16918. return ir.toCanvas().then(function (canvas) {
  16919. return applyColorFilter(canvas, ir.getType(), matrix);
  16920. });
  16921. };
  16922. var applyColorFilter = function (canvas, type, matrix) {
  16923. var context = get2dContext(canvas);
  16924. var applyMatrix = function (pixelsData, m) {
  16925. var r, g, b, a;
  16926. 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];
  16927. for (var i = 0; i < data.length; i += 4) {
  16928. r = data[i];
  16929. g = data[i + 1];
  16930. b = data[i + 2];
  16931. a = data[i + 3];
  16932. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  16933. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  16934. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  16935. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  16936. }
  16937. return pixelsData;
  16938. };
  16939. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  16940. context.putImageData(pixels, 0, 0);
  16941. return fromCanvas(canvas, type);
  16942. };
  16943. var convoluteFilter = function (ir, matrix) {
  16944. return ir.toCanvas().then(function (canvas) {
  16945. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  16946. });
  16947. };
  16948. var applyConvoluteFilter = function (canvas, type, matrix) {
  16949. var context = get2dContext(canvas);
  16950. var applyMatrix = function (pIn, pOut, aMatrix) {
  16951. var clamp = function (value, min, max) {
  16952. if (value > max) {
  16953. value = max;
  16954. } else if (value < min) {
  16955. value = min;
  16956. }
  16957. return value;
  16958. };
  16959. var side = Math.round(Math.sqrt(aMatrix.length));
  16960. var halfSide = Math.floor(side / 2);
  16961. var rgba = pIn.data;
  16962. var drgba = pOut.data;
  16963. var w = pIn.width;
  16964. var h = pIn.height;
  16965. for (var y = 0; y < h; y++) {
  16966. for (var x = 0; x < w; x++) {
  16967. var r = 0;
  16968. var g = 0;
  16969. var b = 0;
  16970. for (var cy = 0; cy < side; cy++) {
  16971. for (var cx = 0; cx < side; cx++) {
  16972. var scx = clamp(x + cx - halfSide, 0, w - 1);
  16973. var scy = clamp(y + cy - halfSide, 0, h - 1);
  16974. var innerOffset = (scy * w + scx) * 4;
  16975. var wt = aMatrix[cy * side + cx];
  16976. r += rgba[innerOffset] * wt;
  16977. g += rgba[innerOffset + 1] * wt;
  16978. b += rgba[innerOffset + 2] * wt;
  16979. }
  16980. }
  16981. var offset = (y * w + x) * 4;
  16982. drgba[offset] = clamp(r, 0, 255);
  16983. drgba[offset + 1] = clamp(g, 0, 255);
  16984. drgba[offset + 2] = clamp(b, 0, 255);
  16985. }
  16986. }
  16987. return pOut;
  16988. };
  16989. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  16990. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  16991. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  16992. context.putImageData(pixelsOut, 0, 0);
  16993. return fromCanvas(canvas, type);
  16994. };
  16995. var functionColorFilter = function (colorFn) {
  16996. var filterImpl = function (canvas, type, value) {
  16997. var context = get2dContext(canvas);
  16998. var lookup = new Array(256);
  16999. var applyLookup = function (pixelsData, lookupData) {
  17000. var data = pixelsData.data;
  17001. for (var i = 0; i < data.length; i += 4) {
  17002. data[i] = lookupData[data[i]];
  17003. data[i + 1] = lookupData[data[i + 1]];
  17004. data[i + 2] = lookupData[data[i + 2]];
  17005. }
  17006. return pixelsData;
  17007. };
  17008. for (var i = 0; i < lookup.length; i++) {
  17009. lookup[i] = colorFn(i, value);
  17010. }
  17011. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  17012. context.putImageData(pixels, 0, 0);
  17013. return fromCanvas(canvas, type);
  17014. };
  17015. return function (ir, value) {
  17016. return ir.toCanvas().then(function (canvas) {
  17017. return filterImpl(canvas, ir.getType(), value);
  17018. });
  17019. };
  17020. };
  17021. var complexAdjustableColorFilter = function (matrixAdjustFn) {
  17022. return function (ir, adjust) {
  17023. return colorFilter(ir, matrixAdjustFn(identity(), adjust));
  17024. };
  17025. };
  17026. var basicColorFilter = function (matrix) {
  17027. return function (ir) {
  17028. return colorFilter(ir, matrix);
  17029. };
  17030. };
  17031. var basicConvolutionFilter = function (kernel) {
  17032. return function (ir) {
  17033. return convoluteFilter(ir, kernel);
  17034. };
  17035. };
  17036. var invert$1 = basicColorFilter([
  17037. -1,
  17038. 0,
  17039. 0,
  17040. 0,
  17041. 255,
  17042. 0,
  17043. -1,
  17044. 0,
  17045. 0,
  17046. 255,
  17047. 0,
  17048. 0,
  17049. -1,
  17050. 0,
  17051. 255,
  17052. 0,
  17053. 0,
  17054. 0,
  17055. 1,
  17056. 0,
  17057. 0,
  17058. 0,
  17059. 0,
  17060. 0,
  17061. 1
  17062. ]);
  17063. var brightness$1 = complexAdjustableColorFilter(adjustBrightness);
  17064. var contrast$1 = complexAdjustableColorFilter(adjustContrast);
  17065. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  17066. return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB));
  17067. };
  17068. var sharpen$1 = basicConvolutionFilter([
  17069. 0,
  17070. -1,
  17071. 0,
  17072. -1,
  17073. 5,
  17074. -1,
  17075. 0,
  17076. -1,
  17077. 0
  17078. ]);
  17079. var gamma$1 = functionColorFilter(function (color, value) {
  17080. return Math.pow(color / 255, 1 - value) * 255;
  17081. });
  17082. var scale = function (image, dW, dH) {
  17083. var sW = getWidth$1(image);
  17084. var sH = getHeight$1(image);
  17085. var wRatio = dW / sW;
  17086. var hRatio = dH / sH;
  17087. var scaleCapped = false;
  17088. if (wRatio < 0.5 || wRatio > 2) {
  17089. wRatio = wRatio < 0.5 ? 0.5 : 2;
  17090. scaleCapped = true;
  17091. }
  17092. if (hRatio < 0.5 || hRatio > 2) {
  17093. hRatio = hRatio < 0.5 ? 0.5 : 2;
  17094. scaleCapped = true;
  17095. }
  17096. var scaled = _scale(image, wRatio, hRatio);
  17097. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  17098. return scale(tCanvas, dW, dH);
  17099. });
  17100. };
  17101. var _scale = function (image, wRatio, hRatio) {
  17102. return new Promise$1(function (resolve) {
  17103. var sW = getWidth$1(image);
  17104. var sH = getHeight$1(image);
  17105. var dW = Math.floor(sW * wRatio);
  17106. var dH = Math.floor(sH * hRatio);
  17107. var canvas = create$3(dW, dH);
  17108. var context = get2dContext(canvas);
  17109. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  17110. resolve(canvas);
  17111. });
  17112. };
  17113. var ceilWithPrecision = function (num, precision) {
  17114. if (precision === void 0) {
  17115. precision = 2;
  17116. }
  17117. var mul = Math.pow(10, precision);
  17118. var upper = Math.round(num * mul);
  17119. return Math.ceil(upper / mul);
  17120. };
  17121. var rotate$1 = function (ir, angle) {
  17122. return ir.toCanvas().then(function (canvas) {
  17123. return applyRotate(canvas, ir.getType(), angle);
  17124. });
  17125. };
  17126. var applyRotate = function (image, type, angle) {
  17127. var degrees = angle < 0 ? 360 + angle : angle;
  17128. var rad = degrees * Math.PI / 180;
  17129. var width = image.width;
  17130. var height = image.height;
  17131. var sin = Math.sin(rad);
  17132. var cos = Math.cos(rad);
  17133. var newWidth = ceilWithPrecision(Math.abs(width * cos) + Math.abs(height * sin));
  17134. var newHeight = ceilWithPrecision(Math.abs(width * sin) + Math.abs(height * cos));
  17135. var canvas = create$3(newWidth, newHeight);
  17136. var context = get2dContext(canvas);
  17137. context.translate(newWidth / 2, newHeight / 2);
  17138. context.rotate(rad);
  17139. context.drawImage(image, -width / 2, -height / 2);
  17140. return fromCanvas(canvas, type);
  17141. };
  17142. var flip$1 = function (ir, axis) {
  17143. return ir.toCanvas().then(function (canvas) {
  17144. return applyFlip(canvas, ir.getType(), axis);
  17145. });
  17146. };
  17147. var applyFlip = function (image, type, axis) {
  17148. var canvas = create$3(image.width, image.height);
  17149. var context = get2dContext(canvas);
  17150. if (axis === 'v') {
  17151. context.scale(1, -1);
  17152. context.drawImage(image, 0, -canvas.height);
  17153. } else {
  17154. context.scale(-1, 1);
  17155. context.drawImage(image, -canvas.width, 0);
  17156. }
  17157. return fromCanvas(canvas, type);
  17158. };
  17159. var crop$1 = function (ir, x, y, w, h) {
  17160. return ir.toCanvas().then(function (canvas) {
  17161. return applyCrop(canvas, ir.getType(), x, y, w, h);
  17162. });
  17163. };
  17164. var applyCrop = function (image, type, x, y, w, h) {
  17165. var canvas = create$3(w, h);
  17166. var context = get2dContext(canvas);
  17167. context.drawImage(image, -x, -y);
  17168. return fromCanvas(canvas, type);
  17169. };
  17170. var resize$2 = function (ir, w, h) {
  17171. return ir.toCanvas().then(function (canvas) {
  17172. return scale(canvas, w, h).then(function (newCanvas) {
  17173. return fromCanvas(newCanvas, ir.getType());
  17174. });
  17175. });
  17176. };
  17177. var invert = function (ir) {
  17178. return invert$1(ir);
  17179. };
  17180. var sharpen = function (ir) {
  17181. return sharpen$1(ir);
  17182. };
  17183. var gamma = function (ir, value) {
  17184. return gamma$1(ir, value);
  17185. };
  17186. var colorize = function (ir, adjustR, adjustG, adjustB) {
  17187. return colorize$1(ir, adjustR, adjustG, adjustB);
  17188. };
  17189. var brightness = function (ir, adjust) {
  17190. return brightness$1(ir, adjust);
  17191. };
  17192. var contrast = function (ir, adjust) {
  17193. return contrast$1(ir, adjust);
  17194. };
  17195. var flip = function (ir, axis) {
  17196. return flip$1(ir, axis);
  17197. };
  17198. var crop = function (ir, x, y, w, h) {
  17199. return crop$1(ir, x, y, w, h);
  17200. };
  17201. var resize$1 = function (ir, w, h) {
  17202. return resize$2(ir, w, h);
  17203. };
  17204. var rotate = function (ir, angle) {
  17205. return rotate$1(ir, angle);
  17206. };
  17207. var renderIcon = function (iconName, iconsProvider, behaviours) {
  17208. return render$3(iconName, {
  17209. tag: 'span',
  17210. classes: [
  17211. 'tox-icon',
  17212. 'tox-tbtn__icon-wrap'
  17213. ],
  17214. behaviours: behaviours
  17215. }, iconsProvider);
  17216. };
  17217. var renderIconFromPack = function (iconName, iconsProvider) {
  17218. return renderIcon(iconName, iconsProvider, []);
  17219. };
  17220. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  17221. return renderIcon(iconName, iconsProvider, [Replacing.config({})]);
  17222. };
  17223. var renderLabel$1 = function (text, prefix, providersBackstage) {
  17224. return {
  17225. dom: {
  17226. tag: 'span',
  17227. innerHtml: providersBackstage.translate(text),
  17228. classes: [prefix + '__select-label']
  17229. },
  17230. behaviours: derive$1([Replacing.config({})])
  17231. };
  17232. };
  17233. var _a;
  17234. var internalToolbarButtonExecute = generate$6('toolbar.button.execute');
  17235. var onToolbarButtonExecute = function (info) {
  17236. return runOnExecute$1(function (comp, _simulatedEvent) {
  17237. runWithApi(info, comp)(function (itemApi) {
  17238. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  17239. info.onAction(itemApi);
  17240. });
  17241. });
  17242. };
  17243. var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [
  17244. 'disabling',
  17245. 'alloy.base.behaviour',
  17246. 'toggling',
  17247. 'toolbar-button-events'
  17248. ], _a);
  17249. var updateMenuText = generate$6('update-menu-text');
  17250. var updateMenuIcon = generate$6('update-menu-icon');
  17251. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  17252. var editorOffCell = Cell(noop);
  17253. var optMemDisplayText = spec.text.map(function (text) {
  17254. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  17255. });
  17256. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  17257. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  17258. });
  17259. var onLeftOrRightInMenu = function (comp, se) {
  17260. var dropdown = Representing.getValue(comp);
  17261. Focusing.focus(dropdown);
  17262. emitWith(dropdown, 'keydown', { raw: se.event.raw });
  17263. Dropdown.close(dropdown);
  17264. return Optional.some(true);
  17265. };
  17266. var role = spec.role.fold(function () {
  17267. return {};
  17268. }, function (role) {
  17269. return { role: role };
  17270. });
  17271. var tooltipAttributes = spec.tooltip.fold(function () {
  17272. return {};
  17273. }, function (tooltip) {
  17274. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  17275. return {
  17276. 'title': translatedTooltip,
  17277. 'aria-label': translatedTooltip
  17278. };
  17279. });
  17280. var iconSpec = render$3('chevron-down', {
  17281. tag: 'div',
  17282. classes: [prefix + '__select-chevron']
  17283. }, sharedBackstage.providers.icons);
  17284. var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), {
  17285. dom: {
  17286. tag: 'button',
  17287. classes: [
  17288. prefix,
  17289. prefix + '--select'
  17290. ].concat(map$2(spec.classes, function (c) {
  17291. return prefix + '--' + c;
  17292. })),
  17293. attributes: __assign({}, tooltipAttributes)
  17294. },
  17295. components: componentRenderPipeline([
  17296. optMemDisplayIcon.map(function (mem) {
  17297. return mem.asSpec();
  17298. }),
  17299. optMemDisplayText.map(function (mem) {
  17300. return mem.asSpec();
  17301. }),
  17302. Optional.some(iconSpec)
  17303. ]),
  17304. matchWidth: true,
  17305. useMinWidth: true,
  17306. dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours, true), [
  17307. DisablingConfigs.button(function () {
  17308. return spec.disabled || sharedBackstage.providers.isDisabled();
  17309. }),
  17310. receivingConfig(),
  17311. Unselecting.config({}),
  17312. Replacing.config({}),
  17313. config('dropdown-events', [
  17314. onControlAttached(spec, editorOffCell),
  17315. onControlDetached(spec, editorOffCell)
  17316. ]),
  17317. config('menubutton-update-display-text', [
  17318. run$1(updateMenuText, function (comp, se) {
  17319. optMemDisplayText.bind(function (mem) {
  17320. return mem.getOpt(comp);
  17321. }).each(function (displayText) {
  17322. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event.text))]);
  17323. });
  17324. }),
  17325. run$1(updateMenuIcon, function (comp, se) {
  17326. optMemDisplayIcon.bind(function (mem) {
  17327. return mem.getOpt(comp);
  17328. }).each(function (displayIcon) {
  17329. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]);
  17330. });
  17331. })
  17332. ])
  17333. ], false)),
  17334. eventOrder: deepMerge(toolbarButtonEventOrder, {
  17335. mousedown: [
  17336. 'focusing',
  17337. 'alloy.base.behaviour',
  17338. 'item-type-events',
  17339. 'normal-dropdown-events'
  17340. ]
  17341. }),
  17342. sandboxBehaviours: derive$1([Keying.config({
  17343. mode: 'special',
  17344. onLeft: onLeftOrRightInMenu,
  17345. onRight: onLeftOrRightInMenu
  17346. })]),
  17347. lazySink: sharedBackstage.getSink,
  17348. toggleClass: prefix + '--active',
  17349. parts: { menu: part(false, spec.columns, spec.presets) },
  17350. fetch: function (comp) {
  17351. return Future.nu(curry(spec.fetch, comp));
  17352. }
  17353. })));
  17354. return memDropdown.asSpec();
  17355. };
  17356. var isMenuItemReference = function (item) {
  17357. return isString(item);
  17358. };
  17359. var isSeparator$1 = function (item) {
  17360. return item.type === 'separator';
  17361. };
  17362. var isExpandingMenuItem = function (item) {
  17363. return has$2(item, 'getSubmenuItems');
  17364. };
  17365. var separator$2 = { type: 'separator' };
  17366. var unwrapReferences = function (items, menuItems) {
  17367. var realItems = foldl(items, function (acc, item) {
  17368. if (isMenuItemReference(item)) {
  17369. if (item === '') {
  17370. return acc;
  17371. } else if (item === '|') {
  17372. return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc;
  17373. } else if (has$2(menuItems, item.toLowerCase())) {
  17374. return acc.concat([menuItems[item.toLowerCase()]]);
  17375. } else {
  17376. return acc;
  17377. }
  17378. } else {
  17379. return acc.concat([item]);
  17380. }
  17381. }, []);
  17382. if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) {
  17383. realItems.pop();
  17384. }
  17385. return realItems;
  17386. };
  17387. var getFromExpandingItem = function (item, menuItems) {
  17388. var submenuItems = item.getSubmenuItems();
  17389. var rest = expand(submenuItems, menuItems);
  17390. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  17391. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  17392. return {
  17393. item: item,
  17394. menus: newMenus,
  17395. expansions: newExpansions
  17396. };
  17397. };
  17398. var getFromItem = function (item, menuItems) {
  17399. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  17400. item: item,
  17401. menus: {},
  17402. expansions: {}
  17403. };
  17404. };
  17405. var generateValueIfRequired = function (item) {
  17406. if (isSeparator$1(item)) {
  17407. return item;
  17408. } else {
  17409. var itemValue = get$e(item, 'value').getOrThunk(function () {
  17410. return generate$6('generated-menu-item');
  17411. });
  17412. return deepMerge({ value: itemValue }, item);
  17413. }
  17414. };
  17415. var expand = function (items, menuItems) {
  17416. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  17417. return foldr(realItems, function (acc, item) {
  17418. var itemWithValue = generateValueIfRequired(item);
  17419. var newData = getFromItem(itemWithValue, menuItems);
  17420. return {
  17421. menus: deepMerge(acc.menus, newData.menus),
  17422. items: [newData.item].concat(acc.items),
  17423. expansions: deepMerge(acc.expansions, newData.expansions)
  17424. };
  17425. }, {
  17426. menus: {},
  17427. expansions: {},
  17428. items: []
  17429. });
  17430. };
  17431. var build = function (items, itemResponse, backstage, isHorizontalMenu) {
  17432. var primary = generate$6('primary-menu');
  17433. var data = expand(items, backstage.shared.providers.menuItems());
  17434. if (data.items.length === 0) {
  17435. return Optional.none();
  17436. }
  17437. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  17438. var submenus = map$1(data.menus, function (menuItems, menuName) {
  17439. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  17440. });
  17441. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  17442. return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions));
  17443. };
  17444. var getMenuButtonApi = function (component) {
  17445. return {
  17446. isDisabled: function () {
  17447. return Disabling.isDisabled(component);
  17448. },
  17449. setDisabled: function (state) {
  17450. return Disabling.set(component, state);
  17451. },
  17452. setActive: function (state) {
  17453. var elm = component.element;
  17454. if (state) {
  17455. add$2(elm, 'tox-tbtn--enabled');
  17456. set$8(elm, 'aria-pressed', true);
  17457. } else {
  17458. remove$2(elm, 'tox-tbtn--enabled');
  17459. remove$7(elm, 'aria-pressed');
  17460. }
  17461. },
  17462. isActive: function () {
  17463. return has(component.element, 'tox-tbtn--enabled');
  17464. }
  17465. };
  17466. };
  17467. var renderMenuButton = function (spec, prefix, backstage, role) {
  17468. return renderCommonDropdown({
  17469. text: spec.text,
  17470. icon: spec.icon,
  17471. tooltip: spec.tooltip,
  17472. role: role,
  17473. fetch: function (_comp, callback) {
  17474. spec.fetch(function (items) {
  17475. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  17476. });
  17477. },
  17478. onSetup: spec.onSetup,
  17479. getApi: getMenuButtonApi,
  17480. columns: 1,
  17481. presets: 'normal',
  17482. classes: [],
  17483. dropdownBehaviours: [Tabstopping.config({})]
  17484. }, prefix, backstage.shared);
  17485. };
  17486. var getFetch = function (items, getButton, backstage) {
  17487. var getMenuItemAction = function (item) {
  17488. return function (api) {
  17489. var newValue = !api.isActive();
  17490. api.setActive(newValue);
  17491. item.storage.set(newValue);
  17492. backstage.shared.getSink().each(function (sink) {
  17493. getButton().getOpt(sink).each(function (orig) {
  17494. focus$3(orig.element);
  17495. emitWith(orig, formActionEvent, {
  17496. name: item.name,
  17497. value: item.storage.get()
  17498. });
  17499. });
  17500. });
  17501. };
  17502. };
  17503. var getMenuItemSetup = function (item) {
  17504. return function (api) {
  17505. api.setActive(item.storage.get());
  17506. };
  17507. };
  17508. return function (success) {
  17509. success(map$2(items, function (item) {
  17510. var text = item.text.fold(function () {
  17511. return {};
  17512. }, function (text) {
  17513. return { text: text };
  17514. });
  17515. return __assign(__assign({
  17516. type: item.type,
  17517. active: false
  17518. }, text), {
  17519. onAction: getMenuItemAction(item),
  17520. onSetup: getMenuItemSetup(item)
  17521. });
  17522. }));
  17523. };
  17524. };
  17525. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) {
  17526. if (extraBehaviours === void 0) {
  17527. extraBehaviours = [];
  17528. }
  17529. var action = actionOpt.fold(function () {
  17530. return {};
  17531. }, function (action) {
  17532. return { action: action };
  17533. });
  17534. var common = __assign({
  17535. buttonBehaviours: derive$1([
  17536. DisablingConfigs.button(function () {
  17537. return spec.disabled || providersBackstage.isDisabled();
  17538. }),
  17539. receivingConfig(),
  17540. Tabstopping.config({}),
  17541. config('button press', [
  17542. preventDefault('click'),
  17543. preventDefault('mousedown')
  17544. ])
  17545. ].concat(extraBehaviours)),
  17546. eventOrder: {
  17547. click: [
  17548. 'button press',
  17549. 'alloy.base.behaviour'
  17550. ],
  17551. mousedown: [
  17552. 'button press',
  17553. 'alloy.base.behaviour'
  17554. ]
  17555. }
  17556. }, action);
  17557. var domFinal = deepMerge(common, { dom: dom });
  17558. return deepMerge(domFinal, { components: components });
  17559. };
  17560. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  17561. if (extraBehaviours === void 0) {
  17562. extraBehaviours = [];
  17563. }
  17564. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  17565. return {
  17566. 'aria-label': providersBackstage.translate(tooltip),
  17567. 'title': providersBackstage.translate(tooltip)
  17568. };
  17569. }).getOr({});
  17570. var dom = {
  17571. tag: 'button',
  17572. classes: ['tox-tbtn'],
  17573. attributes: tooltipAttributes
  17574. };
  17575. var icon = spec.icon.map(function (iconName) {
  17576. return renderIconFromPack(iconName, providersBackstage.icons);
  17577. });
  17578. var components = componentRenderPipeline([icon]);
  17579. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17580. };
  17581. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  17582. if (extraBehaviours === void 0) {
  17583. extraBehaviours = [];
  17584. }
  17585. var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours);
  17586. return Button.sketch(iconButtonSpec);
  17587. };
  17588. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17589. if (extraBehaviours === void 0) {
  17590. extraBehaviours = [];
  17591. }
  17592. if (extraClasses === void 0) {
  17593. extraClasses = [];
  17594. }
  17595. var translatedText = providersBackstage.translate(spec.text);
  17596. var icon = spec.icon ? spec.icon.map(function (iconName) {
  17597. return renderIconFromPack(iconName, providersBackstage.icons);
  17598. }) : Optional.none();
  17599. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  17600. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  17601. var classes = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [
  17602. 'tox-button',
  17603. 'tox-button--secondary'
  17604. ] : ['tox-button'], true), icon.isSome() ? ['tox-button--icon'] : [], true), spec.borderless ? ['tox-button--naked'] : [], true), extraClasses, true);
  17605. var dom = __assign(__assign({
  17606. tag: 'button',
  17607. classes: classes
  17608. }, innerHtml), { attributes: { title: translatedText } });
  17609. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17610. };
  17611. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17612. if (extraBehaviours === void 0) {
  17613. extraBehaviours = [];
  17614. }
  17615. if (extraClasses === void 0) {
  17616. extraClasses = [];
  17617. }
  17618. var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses);
  17619. return Button.sketch(buttonSpec);
  17620. };
  17621. var getAction = function (name, buttonType) {
  17622. return function (comp) {
  17623. if (buttonType === 'custom') {
  17624. emitWith(comp, formActionEvent, {
  17625. name: name,
  17626. value: {}
  17627. });
  17628. } else if (buttonType === 'submit') {
  17629. emit(comp, formSubmitEvent);
  17630. } else if (buttonType === 'cancel') {
  17631. emit(comp, formCancelEvent);
  17632. } else {
  17633. console.error('Unknown button type: ', buttonType);
  17634. }
  17635. };
  17636. };
  17637. var isMenuFooterButtonSpec = function (spec, buttonType) {
  17638. return buttonType === 'menu';
  17639. };
  17640. var isNormalFooterButtonSpec = function (spec, buttonType) {
  17641. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  17642. };
  17643. var renderFooterButton = function (spec, buttonType, backstage) {
  17644. if (isMenuFooterButtonSpec(spec, buttonType)) {
  17645. var getButton = function () {
  17646. return memButton_1;
  17647. };
  17648. var menuButtonSpec = spec;
  17649. var fixedSpec = __assign(__assign({}, spec), {
  17650. onSetup: function (api) {
  17651. api.setDisabled(spec.disabled);
  17652. return noop;
  17653. },
  17654. fetch: getFetch(menuButtonSpec.items, getButton, backstage)
  17655. });
  17656. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none()));
  17657. return memButton_1.asSpec();
  17658. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  17659. var action = getAction(spec.name, buttonType);
  17660. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  17661. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  17662. } else {
  17663. console.error('Unknown footer button type: ', buttonType);
  17664. }
  17665. };
  17666. var renderDialogButton = function (spec, providersBackstage) {
  17667. var action = getAction(spec.name, 'custom');
  17668. return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [
  17669. RepresentingConfigs.memory(''),
  17670. ComposingConfigs.self()
  17671. ]))));
  17672. };
  17673. var schema$h = constant$1([
  17674. defaulted('field1Name', 'field1'),
  17675. defaulted('field2Name', 'field2'),
  17676. onStrictHandler('onLockedChange'),
  17677. markers$1(['lockClass']),
  17678. defaulted('locked', false),
  17679. SketchBehaviours.field('coupledFieldBehaviours', [
  17680. Composing,
  17681. Representing
  17682. ])
  17683. ]);
  17684. var getField = function (comp, detail, partName) {
  17685. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  17686. };
  17687. var coupledPart = function (selfName, otherName) {
  17688. return required({
  17689. factory: FormField,
  17690. name: selfName,
  17691. overrides: function (detail) {
  17692. return {
  17693. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run$1(input(), function (me) {
  17694. getField(me, detail, otherName).each(function (other) {
  17695. getPart(me, detail, 'lock').each(function (lock) {
  17696. if (Toggling.isOn(lock)) {
  17697. detail.onLockedChange(me, other, lock);
  17698. }
  17699. });
  17700. });
  17701. })])])
  17702. };
  17703. }
  17704. });
  17705. };
  17706. var parts$c = constant$1([
  17707. coupledPart('field1', 'field2'),
  17708. coupledPart('field2', 'field1'),
  17709. required({
  17710. factory: Button,
  17711. schema: [required$1('dom')],
  17712. name: 'lock',
  17713. overrides: function (detail) {
  17714. return {
  17715. buttonBehaviours: derive$1([Toggling.config({
  17716. selected: detail.locked,
  17717. toggleClass: detail.markers.lockClass,
  17718. aria: { mode: 'pressed' }
  17719. })])
  17720. };
  17721. }
  17722. })
  17723. ]);
  17724. var factory$f = function (detail, components, _spec, _externals) {
  17725. return {
  17726. uid: detail.uid,
  17727. dom: detail.dom,
  17728. components: components,
  17729. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  17730. Composing.config({ find: Optional.some }),
  17731. Representing.config({
  17732. store: {
  17733. mode: 'manual',
  17734. getValue: function (comp) {
  17735. var _a;
  17736. var parts = getPartsOrDie(comp, detail, [
  17737. 'field1',
  17738. 'field2'
  17739. ]);
  17740. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  17741. },
  17742. setValue: function (comp, value) {
  17743. var parts = getPartsOrDie(comp, detail, [
  17744. 'field1',
  17745. 'field2'
  17746. ]);
  17747. if (hasNonNullableKey(value, detail.field1Name)) {
  17748. Representing.setValue(parts.field1(), value[detail.field1Name]);
  17749. }
  17750. if (hasNonNullableKey(value, detail.field2Name)) {
  17751. Representing.setValue(parts.field2(), value[detail.field2Name]);
  17752. }
  17753. }
  17754. }
  17755. })
  17756. ]),
  17757. apis: {
  17758. getField1: function (component) {
  17759. return getPart(component, detail, 'field1');
  17760. },
  17761. getField2: function (component) {
  17762. return getPart(component, detail, 'field2');
  17763. },
  17764. getLock: function (component) {
  17765. return getPart(component, detail, 'lock');
  17766. }
  17767. }
  17768. };
  17769. };
  17770. var FormCoupledInputs = composite({
  17771. name: 'FormCoupledInputs',
  17772. configFields: schema$h(),
  17773. partFields: parts$c(),
  17774. factory: factory$f,
  17775. apis: {
  17776. getField1: function (apis, component) {
  17777. return apis.getField1(component);
  17778. },
  17779. getField2: function (apis, component) {
  17780. return apis.getField2(component);
  17781. },
  17782. getLock: function (apis, component) {
  17783. return apis.getLock(component);
  17784. }
  17785. }
  17786. });
  17787. var formatSize = function (size) {
  17788. var unitDec = {
  17789. '': 0,
  17790. 'px': 0,
  17791. 'pt': 1,
  17792. 'mm': 1,
  17793. 'pc': 2,
  17794. 'ex': 2,
  17795. 'em': 2,
  17796. 'ch': 2,
  17797. 'rem': 2,
  17798. 'cm': 3,
  17799. 'in': 4,
  17800. '%': 4
  17801. };
  17802. var maxDecimal = function (unit) {
  17803. return unit in unitDec ? unitDec[unit] : 1;
  17804. };
  17805. var numText = size.value.toFixed(maxDecimal(size.unit));
  17806. if (numText.indexOf('.') !== -1) {
  17807. numText = numText.replace(/\.?0*$/, '');
  17808. }
  17809. return numText + size.unit;
  17810. };
  17811. var parseSize = function (sizeText) {
  17812. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  17813. var match = numPattern.exec(sizeText);
  17814. if (match !== null) {
  17815. var value = parseFloat(match[1]);
  17816. var unit = match[2];
  17817. return Result.value({
  17818. value: value,
  17819. unit: unit
  17820. });
  17821. } else {
  17822. return Result.error(sizeText);
  17823. }
  17824. };
  17825. var convertUnit = function (size, unit) {
  17826. var inInch = {
  17827. '': 96,
  17828. 'px': 96,
  17829. 'pt': 72,
  17830. 'cm': 2.54,
  17831. 'pc': 12,
  17832. 'mm': 25.4,
  17833. 'in': 1
  17834. };
  17835. var supported = function (u) {
  17836. return has$2(inInch, u);
  17837. };
  17838. if (size.unit === unit) {
  17839. return Optional.some(size.value);
  17840. } else if (supported(size.unit) && supported(unit)) {
  17841. if (inInch[size.unit] === inInch[unit]) {
  17842. return Optional.some(size.value);
  17843. } else {
  17844. return Optional.some(size.value / inInch[size.unit] * inInch[unit]);
  17845. }
  17846. } else {
  17847. return Optional.none();
  17848. }
  17849. };
  17850. var noSizeConversion = function (_input) {
  17851. return Optional.none();
  17852. };
  17853. var ratioSizeConversion = function (scale, unit) {
  17854. return function (size) {
  17855. return convertUnit(size, unit).map(function (value) {
  17856. return {
  17857. value: value * scale,
  17858. unit: unit
  17859. };
  17860. });
  17861. };
  17862. };
  17863. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  17864. var cValue = parseSize(currentFieldText).toOptional();
  17865. var oValue = parseSize(otherFieldText).toOptional();
  17866. return lift2(cValue, oValue, function (cSize, oSize) {
  17867. return convertUnit(cSize, oSize.unit).map(function (val) {
  17868. return oSize.value / val;
  17869. }).map(function (r) {
  17870. return ratioSizeConversion(r, oSize.unit);
  17871. }).getOr(noSizeConversion);
  17872. }).getOr(noSizeConversion);
  17873. };
  17874. var renderSizeInput = function (spec, providersBackstage) {
  17875. var converter = noSizeConversion;
  17876. var ratioEvent = generate$6('ratio-event');
  17877. var makeIcon = function (iconName) {
  17878. return render$3(iconName, {
  17879. tag: 'span',
  17880. classes: [
  17881. 'tox-icon',
  17882. 'tox-lock-icon__' + iconName
  17883. ]
  17884. }, providersBackstage.icons);
  17885. };
  17886. var pLock = FormCoupledInputs.parts.lock({
  17887. dom: {
  17888. tag: 'button',
  17889. classes: [
  17890. 'tox-lock',
  17891. 'tox-button',
  17892. 'tox-button--naked',
  17893. 'tox-button--icon'
  17894. ],
  17895. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  17896. },
  17897. components: [
  17898. makeIcon('lock'),
  17899. makeIcon('unlock')
  17900. ],
  17901. buttonBehaviours: derive$1([
  17902. Disabling.config({
  17903. disabled: function () {
  17904. return spec.disabled || providersBackstage.isDisabled();
  17905. }
  17906. }),
  17907. receivingConfig(),
  17908. Tabstopping.config({})
  17909. ])
  17910. });
  17911. var formGroup = function (components) {
  17912. return {
  17913. dom: {
  17914. tag: 'div',
  17915. classes: ['tox-form__group']
  17916. },
  17917. components: components
  17918. };
  17919. };
  17920. var getFieldPart = function (isField1) {
  17921. return FormField.parts.field({
  17922. factory: Input,
  17923. inputClasses: ['tox-textfield'],
  17924. inputBehaviours: derive$1([
  17925. Disabling.config({
  17926. disabled: function () {
  17927. return spec.disabled || providersBackstage.isDisabled();
  17928. }
  17929. }),
  17930. receivingConfig(),
  17931. Tabstopping.config({}),
  17932. config('size-input-events', [
  17933. run$1(focusin(), function (component, _simulatedEvent) {
  17934. emitWith(component, ratioEvent, { isField1: isField1 });
  17935. }),
  17936. run$1(change(), function (component, _simulatedEvent) {
  17937. emitWith(component, formChangeEvent, { name: spec.name });
  17938. })
  17939. ])
  17940. ]),
  17941. selectOnFocus: false
  17942. });
  17943. };
  17944. var getLabel = function (label) {
  17945. return {
  17946. dom: {
  17947. tag: 'label',
  17948. classes: ['tox-label'],
  17949. innerHtml: providersBackstage.translate(label)
  17950. }
  17951. };
  17952. };
  17953. var widthField = FormCoupledInputs.parts.field1(formGroup([
  17954. FormField.parts.label(getLabel('Width')),
  17955. getFieldPart(true)
  17956. ]));
  17957. var heightField = FormCoupledInputs.parts.field2(formGroup([
  17958. FormField.parts.label(getLabel('Height')),
  17959. getFieldPart(false)
  17960. ]));
  17961. return FormCoupledInputs.sketch({
  17962. dom: {
  17963. tag: 'div',
  17964. classes: ['tox-form__group']
  17965. },
  17966. components: [{
  17967. dom: {
  17968. tag: 'div',
  17969. classes: ['tox-form__controls-h-stack']
  17970. },
  17971. components: [
  17972. widthField,
  17973. heightField,
  17974. formGroup([
  17975. getLabel('&nbsp;'),
  17976. pLock
  17977. ])
  17978. ]
  17979. }],
  17980. field1Name: 'width',
  17981. field2Name: 'height',
  17982. locked: true,
  17983. markers: { lockClass: 'tox-locked' },
  17984. onLockedChange: function (current, other, _lock) {
  17985. parseSize(Representing.getValue(current)).each(function (size) {
  17986. converter(size).each(function (newSize) {
  17987. Representing.setValue(other, formatSize(newSize));
  17988. });
  17989. });
  17990. },
  17991. coupledFieldBehaviours: derive$1([
  17992. Disabling.config({
  17993. disabled: function () {
  17994. return spec.disabled || providersBackstage.isDisabled();
  17995. },
  17996. onDisabled: function (comp) {
  17997. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  17998. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  17999. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  18000. },
  18001. onEnabled: function (comp) {
  18002. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  18003. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  18004. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  18005. }
  18006. }),
  18007. receivingConfig(),
  18008. config('size-input-events2', [run$1(ratioEvent, function (component, simulatedEvent) {
  18009. var isField1 = simulatedEvent.event.isField1;
  18010. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  18011. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  18012. var value1 = optCurrent.map(Representing.getValue).getOr('');
  18013. var value2 = optOther.map(Representing.getValue).getOr('');
  18014. converter = makeRatioConverter(value1, value2);
  18015. })])
  18016. ])
  18017. });
  18018. };
  18019. var undo = constant$1(generate$6('undo'));
  18020. var redo = constant$1(generate$6('redo'));
  18021. var zoom = constant$1(generate$6('zoom'));
  18022. var back = constant$1(generate$6('back'));
  18023. var apply = constant$1(generate$6('apply'));
  18024. var swap = constant$1(generate$6('swap'));
  18025. var transform$1 = constant$1(generate$6('transform'));
  18026. var tempTransform = constant$1(generate$6('temp-transform'));
  18027. var transformApply = constant$1(generate$6('transform-apply'));
  18028. var internal = {
  18029. undo: undo,
  18030. redo: redo,
  18031. zoom: zoom,
  18032. back: back,
  18033. apply: apply,
  18034. swap: swap,
  18035. transform: transform$1,
  18036. tempTransform: tempTransform,
  18037. transformApply: transformApply
  18038. };
  18039. var saveState = constant$1('save-state');
  18040. var disable = constant$1('disable');
  18041. var enable = constant$1('enable');
  18042. var external = {
  18043. formActionEvent: formActionEvent,
  18044. saveState: saveState,
  18045. disable: disable,
  18046. enable: enable
  18047. };
  18048. var renderEditPanel = function (imagePanel, providersBackstage) {
  18049. var createButton = function (text, action, disabled, primary) {
  18050. return record(renderButton({
  18051. name: text,
  18052. text: text,
  18053. disabled: disabled,
  18054. primary: primary,
  18055. icon: Optional.none(),
  18056. borderless: false
  18057. }, action, providersBackstage));
  18058. };
  18059. var createIconButton = function (icon, tooltip, action, disabled) {
  18060. return record(renderIconButton({
  18061. name: icon,
  18062. icon: Optional.some(icon),
  18063. tooltip: Optional.some(tooltip),
  18064. disabled: disabled,
  18065. primary: false,
  18066. borderless: false
  18067. }, action, providersBackstage));
  18068. };
  18069. var disableAllComponents = function (comps, eventcomp) {
  18070. comps.map(function (mem) {
  18071. var component = mem.get(eventcomp);
  18072. if (component.hasConfigured(Disabling)) {
  18073. Disabling.disable(component);
  18074. }
  18075. });
  18076. };
  18077. var enableAllComponents = function (comps, eventcomp) {
  18078. comps.map(function (mem) {
  18079. var component = mem.get(eventcomp);
  18080. if (component.hasConfigured(Disabling)) {
  18081. Disabling.enable(component);
  18082. }
  18083. });
  18084. };
  18085. var panelDom = {
  18086. tag: 'div',
  18087. classes: [
  18088. 'tox-image-tools__toolbar',
  18089. 'tox-image-tools-edit-panel'
  18090. ]
  18091. };
  18092. var noop$1 = noop;
  18093. var emit$1 = function (comp, event, data) {
  18094. emitWith(comp, event, data);
  18095. };
  18096. var emitDisable = function (component) {
  18097. return emit(component, external.disable());
  18098. };
  18099. var emitEnable = function (component) {
  18100. return emit(component, external.enable());
  18101. };
  18102. var emitTransform = function (comp, transform) {
  18103. emitDisable(comp);
  18104. emit$1(comp, internal.transform(), { transform: transform });
  18105. emitEnable(comp);
  18106. };
  18107. var emitTempTransform = function (comp, transform) {
  18108. emitDisable(comp);
  18109. emit$1(comp, internal.tempTransform(), { transform: transform });
  18110. emitEnable(comp);
  18111. };
  18112. var getBackSwap = function (anyInSystem) {
  18113. return function () {
  18114. memContainer.getOpt(anyInSystem).each(function (container) {
  18115. Replacing.set(container, [ButtonPanel]);
  18116. });
  18117. };
  18118. };
  18119. var emitTransformApply = function (comp, transform) {
  18120. emitDisable(comp);
  18121. emit$1(comp, internal.transformApply(), {
  18122. transform: transform,
  18123. swap: getBackSwap(comp)
  18124. });
  18125. emitEnable(comp);
  18126. };
  18127. var createBackButton = function () {
  18128. return createButton('Back', function (button) {
  18129. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  18130. }, false, false);
  18131. };
  18132. var createSpacer = function () {
  18133. return record({
  18134. dom: {
  18135. tag: 'div',
  18136. classes: ['tox-spacer']
  18137. },
  18138. behaviours: derive$1([Disabling.config({})])
  18139. });
  18140. };
  18141. var createApplyButton = function () {
  18142. return createButton('Apply', function (button) {
  18143. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  18144. }, true, true);
  18145. };
  18146. var makeCropTransform = function () {
  18147. return function (ir) {
  18148. var rect = imagePanel.getRect();
  18149. return crop(ir, rect.x, rect.y, rect.w, rect.h);
  18150. };
  18151. };
  18152. var cropPanelComponents = [
  18153. createBackButton(),
  18154. createSpacer(),
  18155. createButton('Apply', function (button) {
  18156. var transform = makeCropTransform();
  18157. emitTransformApply(button, transform);
  18158. imagePanel.hideCrop();
  18159. }, false, true)
  18160. ];
  18161. var CropPanel = Container.sketch({
  18162. dom: panelDom,
  18163. components: cropPanelComponents.map(function (mem) {
  18164. return mem.asSpec();
  18165. }),
  18166. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  18167. run$1(external.disable(), function (comp, _se) {
  18168. disableAllComponents(cropPanelComponents, comp);
  18169. }),
  18170. run$1(external.enable(), function (comp, _se) {
  18171. enableAllComponents(cropPanelComponents, comp);
  18172. })
  18173. ])])
  18174. });
  18175. var memSize = record(renderSizeInput({
  18176. name: 'size',
  18177. label: Optional.none(),
  18178. constrain: true,
  18179. disabled: false
  18180. }, providersBackstage));
  18181. var makeResizeTransform = function (width, height) {
  18182. return function (ir) {
  18183. return resize$1(ir, width, height);
  18184. };
  18185. };
  18186. var resizePanelComponents = [
  18187. createBackButton(),
  18188. createSpacer(),
  18189. memSize,
  18190. createSpacer(),
  18191. createButton('Apply', function (button) {
  18192. memSize.getOpt(button).each(function (sizeInput) {
  18193. var value = Representing.getValue(sizeInput);
  18194. var width = parseInt(value.width, 10);
  18195. var height = parseInt(value.height, 10);
  18196. var transform = makeResizeTransform(width, height);
  18197. emitTransformApply(button, transform);
  18198. });
  18199. }, false, true)
  18200. ];
  18201. var ResizePanel = Container.sketch({
  18202. dom: panelDom,
  18203. components: resizePanelComponents.map(function (mem) {
  18204. return mem.asSpec();
  18205. }),
  18206. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  18207. run$1(external.disable(), function (comp, _se) {
  18208. disableAllComponents(resizePanelComponents, comp);
  18209. }),
  18210. run$1(external.enable(), function (comp, _se) {
  18211. enableAllComponents(resizePanelComponents, comp);
  18212. })
  18213. ])])
  18214. });
  18215. var makeValueTransform = function (transform, value) {
  18216. return function (ir) {
  18217. return transform(ir, value);
  18218. };
  18219. };
  18220. var horizontalFlip = makeValueTransform(flip, 'h');
  18221. var verticalFlip = makeValueTransform(flip, 'v');
  18222. var counterclockwiseRotate = makeValueTransform(rotate, -90);
  18223. var clockwiseRotate = makeValueTransform(rotate, 90);
  18224. var flipRotateOnAction = function (comp, operation) {
  18225. emitTempTransform(comp, operation);
  18226. };
  18227. var flipRotateComponents = [
  18228. createBackButton(),
  18229. createSpacer(),
  18230. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  18231. flipRotateOnAction(button, horizontalFlip);
  18232. }, false),
  18233. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  18234. flipRotateOnAction(button, verticalFlip);
  18235. }, false),
  18236. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  18237. flipRotateOnAction(button, counterclockwiseRotate);
  18238. }, false),
  18239. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  18240. flipRotateOnAction(button, clockwiseRotate);
  18241. }, false),
  18242. createSpacer(),
  18243. createApplyButton()
  18244. ];
  18245. var FlipRotatePanel = Container.sketch({
  18246. dom: panelDom,
  18247. components: flipRotateComponents.map(function (mem) {
  18248. return mem.asSpec();
  18249. }),
  18250. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  18251. run$1(external.disable(), function (comp, _se) {
  18252. disableAllComponents(flipRotateComponents, comp);
  18253. }),
  18254. run$1(external.enable(), function (comp, _se) {
  18255. enableAllComponents(flipRotateComponents, comp);
  18256. })
  18257. ])])
  18258. });
  18259. var makeSlider = function (label, onChoose, min, value, max) {
  18260. var labelPart = Slider.parts.label({
  18261. dom: {
  18262. tag: 'label',
  18263. classes: ['tox-label'],
  18264. innerHtml: providersBackstage.translate(label)
  18265. }
  18266. });
  18267. var spectrum = Slider.parts.spectrum({
  18268. dom: {
  18269. tag: 'div',
  18270. classes: ['tox-slider__rail'],
  18271. attributes: { role: 'presentation' }
  18272. }
  18273. });
  18274. var thumb = Slider.parts.thumb({
  18275. dom: {
  18276. tag: 'div',
  18277. classes: ['tox-slider__handle'],
  18278. attributes: { role: 'presentation' }
  18279. }
  18280. });
  18281. return record(Slider.sketch({
  18282. dom: {
  18283. tag: 'div',
  18284. classes: ['tox-slider'],
  18285. attributes: { role: 'presentation' }
  18286. },
  18287. model: {
  18288. mode: 'x',
  18289. minX: min,
  18290. maxX: max,
  18291. getInitialValue: constant$1({ x: value })
  18292. },
  18293. components: [
  18294. labelPart,
  18295. spectrum,
  18296. thumb
  18297. ],
  18298. sliderBehaviours: derive$1([Focusing.config({})]),
  18299. onChoose: onChoose
  18300. }));
  18301. };
  18302. var makeVariableSlider = function (label, transform, min, value, max) {
  18303. var onChoose = function (slider, _thumb, value) {
  18304. var valTransform = makeValueTransform(transform, value.x / 100);
  18305. emitTransform(slider, valTransform);
  18306. };
  18307. return makeSlider(label, onChoose, min, value, max);
  18308. };
  18309. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  18310. return [
  18311. createBackButton(),
  18312. makeVariableSlider(label, transform, min, value, max),
  18313. createApplyButton()
  18314. ];
  18315. };
  18316. var createVariableFilterPanel = function (label, transform, min, value, max) {
  18317. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  18318. return Container.sketch({
  18319. dom: panelDom,
  18320. components: filterPanelComponents.map(function (mem) {
  18321. return mem.asSpec();
  18322. }),
  18323. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  18324. run$1(external.disable(), function (comp, _se) {
  18325. disableAllComponents(filterPanelComponents, comp);
  18326. }),
  18327. run$1(external.enable(), function (comp, _se) {
  18328. enableAllComponents(filterPanelComponents, comp);
  18329. })
  18330. ])])
  18331. });
  18332. };
  18333. var filterPanelComponents = [
  18334. createBackButton(),
  18335. createSpacer(),
  18336. createApplyButton()
  18337. ];
  18338. var FilterPanel = Container.sketch({
  18339. dom: panelDom,
  18340. components: filterPanelComponents.map(function (mem) {
  18341. return mem.asSpec();
  18342. })
  18343. });
  18344. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness, -100, 0, 100);
  18345. var ContrastPanel = createVariableFilterPanel('Contrast', contrast, -100, 0, 100);
  18346. var GammaPanel = createVariableFilterPanel('Gamma', gamma, -100, 0, 100);
  18347. var makeColorTransform = function (red, green, blue) {
  18348. return function (ir) {
  18349. return colorize(ir, red, green, blue);
  18350. };
  18351. };
  18352. var makeColorSlider = function (label) {
  18353. var onChoose = function (slider, _thumb, _value) {
  18354. var redOpt = memRed.getOpt(slider);
  18355. var blueOpt = memBlue.getOpt(slider);
  18356. var greenOpt = memGreen.getOpt(slider);
  18357. redOpt.each(function (red) {
  18358. blueOpt.each(function (blue) {
  18359. greenOpt.each(function (green) {
  18360. var r = Representing.getValue(red).x / 100;
  18361. var g = Representing.getValue(green).x / 100;
  18362. var b = Representing.getValue(blue).x / 100;
  18363. var transform = makeColorTransform(r, g, b);
  18364. emitTransform(slider, transform);
  18365. });
  18366. });
  18367. });
  18368. };
  18369. return makeSlider(label, onChoose, 0, 100, 200);
  18370. };
  18371. var memRed = makeColorSlider('R');
  18372. var memGreen = makeColorSlider('G');
  18373. var memBlue = makeColorSlider('B');
  18374. var colorizePanelComponents = [
  18375. createBackButton(),
  18376. memRed,
  18377. memGreen,
  18378. memBlue,
  18379. createApplyButton()
  18380. ];
  18381. var ColorizePanel = Container.sketch({
  18382. dom: panelDom,
  18383. components: colorizePanelComponents.map(function (mem) {
  18384. return mem.asSpec();
  18385. })
  18386. });
  18387. var getTransformPanelEvent = function (panel, transform, update) {
  18388. return function (button) {
  18389. var swap = function () {
  18390. memContainer.getOpt(button).each(function (container) {
  18391. Replacing.set(container, [panel]);
  18392. update(container);
  18393. });
  18394. };
  18395. emit$1(button, internal.swap(), {
  18396. transform: transform,
  18397. swap: swap
  18398. });
  18399. };
  18400. };
  18401. var cropPanelUpdate = function (_anyInSystem) {
  18402. imagePanel.showCrop();
  18403. };
  18404. var resizePanelUpdate = function (anyInSystem) {
  18405. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  18406. var measurements = imagePanel.getMeasurements();
  18407. var width = measurements.width;
  18408. var height = measurements.height;
  18409. Representing.setValue(sizeInput, {
  18410. width: width,
  18411. height: height
  18412. });
  18413. });
  18414. };
  18415. var sharpenTransform = Optional.some(sharpen);
  18416. var invertTransform = Optional.some(invert);
  18417. var buttonPanelComponents = [
  18418. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false),
  18419. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false),
  18420. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false),
  18421. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false),
  18422. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  18423. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false),
  18424. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false),
  18425. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false),
  18426. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  18427. ];
  18428. var ButtonPanel = Container.sketch({
  18429. dom: panelDom,
  18430. components: buttonPanelComponents.map(function (mem) {
  18431. return mem.asSpec();
  18432. })
  18433. });
  18434. var container = Container.sketch({
  18435. dom: { tag: 'div' },
  18436. components: [ButtonPanel],
  18437. containerBehaviours: derive$1([Replacing.config({})])
  18438. });
  18439. var memContainer = record(container);
  18440. var getApplyButton = function (anyInSystem) {
  18441. return memContainer.getOpt(anyInSystem).map(function (container) {
  18442. var panel = container.components()[0];
  18443. return panel.components()[panel.components().length - 1];
  18444. });
  18445. };
  18446. return {
  18447. memContainer: memContainer,
  18448. getApplyButton: getApplyButton
  18449. };
  18450. };
  18451. var global$4 = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  18452. var global$3 = tinymce.util.Tools.resolve('tinymce.util.Observable');
  18453. var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK');
  18454. var getDocumentSize = function (doc) {
  18455. var max = Math.max;
  18456. var documentElement = doc.documentElement;
  18457. var body = doc.body;
  18458. var scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  18459. var clientWidth = max(documentElement.clientWidth, body.clientWidth);
  18460. var offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  18461. var scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  18462. var clientHeight = max(documentElement.clientHeight, body.clientHeight);
  18463. var offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  18464. return {
  18465. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  18466. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  18467. };
  18468. };
  18469. var isTouchEvent$1 = function (e) {
  18470. return isNonNullable(e.changedTouches);
  18471. };
  18472. var updateWithTouchData = function (e) {
  18473. if (isTouchEvent$1(e)) {
  18474. var keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  18475. for (var i = 0; i < keys.length; i++) {
  18476. e[keys[i]] = e.changedTouches[0][keys[i]];
  18477. }
  18478. }
  18479. };
  18480. function DragHelper (id, settings) {
  18481. var _a, _b, _c;
  18482. var eventOverlay;
  18483. var handleEvents = [];
  18484. var overlayEvents = [];
  18485. var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document;
  18486. var root = (_b = settings.root) !== null && _b !== void 0 ? _b : doc;
  18487. var sugarDoc = SugarElement.fromDom(doc);
  18488. var downButton;
  18489. var startX;
  18490. var startY;
  18491. var handleElement = SugarElement.fromDom(root.getElementById((_c = settings.handle) !== null && _c !== void 0 ? _c : id));
  18492. var start = function (e) {
  18493. var rawEvent = e.raw;
  18494. var docSize = getDocumentSize(doc);
  18495. updateWithTouchData(rawEvent);
  18496. e.prevent();
  18497. downButton = rawEvent.button;
  18498. startX = rawEvent.screenX;
  18499. startY = rawEvent.screenY;
  18500. var cursor = get$c(handleElement, 'cursor');
  18501. eventOverlay = SugarElement.fromTag('div', doc);
  18502. setAll(eventOverlay, {
  18503. 'position': 'absolute',
  18504. 'top': '0',
  18505. 'left': '0',
  18506. 'width': docSize.width + 'px',
  18507. 'height': docSize.height + 'px',
  18508. 'z-index': 2147483647 + '',
  18509. 'opacity': '0.0001',
  18510. cursor: cursor
  18511. });
  18512. append$2(getBody(sugarDoc), eventOverlay);
  18513. overlayEvents.push(bind(sugarDoc, 'mousemove', drag), bind(sugarDoc, 'touchmove', drag), bind(sugarDoc, 'mouseup', stop), bind(sugarDoc, 'touchend', stop));
  18514. settings.start(rawEvent);
  18515. };
  18516. var drag = function (e) {
  18517. var rawEvent = e.raw;
  18518. updateWithTouchData(rawEvent);
  18519. if (rawEvent.button !== downButton) {
  18520. return stop(e);
  18521. }
  18522. rawEvent.deltaX = rawEvent.screenX - startX;
  18523. rawEvent.deltaY = rawEvent.screenY - startY;
  18524. e.prevent();
  18525. settings.drag(rawEvent);
  18526. };
  18527. var stop = function (e) {
  18528. updateWithTouchData(e.raw);
  18529. each$1(overlayEvents, function (e) {
  18530. return e.unbind();
  18531. });
  18532. overlayEvents = [];
  18533. remove$5(eventOverlay);
  18534. if (settings.stop) {
  18535. settings.stop(e.raw);
  18536. }
  18537. };
  18538. var destroy = function () {
  18539. each$1(overlayEvents.concat(handleEvents), function (e) {
  18540. return e.unbind();
  18541. });
  18542. overlayEvents = [];
  18543. handleEvents = [];
  18544. if (isNonNullable(eventOverlay)) {
  18545. remove$5(eventOverlay);
  18546. }
  18547. };
  18548. handleEvents.push(bind(handleElement, 'mousedown', start), bind(handleElement, 'touchstart', start));
  18549. return { destroy: destroy };
  18550. }
  18551. var count = 0;
  18552. var create$1 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18553. var dragHelpers;
  18554. var events = [];
  18555. var prefix = 'tox-';
  18556. var id = prefix + 'crid-' + count++;
  18557. var container = SugarElement.fromDom(containerElm);
  18558. var handles = [
  18559. {
  18560. name: 'move',
  18561. xMul: 0,
  18562. yMul: 0,
  18563. deltaX: 1,
  18564. deltaY: 1,
  18565. deltaW: 0,
  18566. deltaH: 0,
  18567. label: 'Crop Mask'
  18568. },
  18569. {
  18570. name: 'nw',
  18571. xMul: 0,
  18572. yMul: 0,
  18573. deltaX: 1,
  18574. deltaY: 1,
  18575. deltaW: -1,
  18576. deltaH: -1,
  18577. label: 'Top Left Crop Handle'
  18578. },
  18579. {
  18580. name: 'ne',
  18581. xMul: 1,
  18582. yMul: 0,
  18583. deltaX: 0,
  18584. deltaY: 1,
  18585. deltaW: 1,
  18586. deltaH: -1,
  18587. label: 'Top Right Crop Handle'
  18588. },
  18589. {
  18590. name: 'sw',
  18591. xMul: 0,
  18592. yMul: 1,
  18593. deltaX: 1,
  18594. deltaY: 0,
  18595. deltaW: -1,
  18596. deltaH: 1,
  18597. label: 'Bottom Left Crop Handle'
  18598. },
  18599. {
  18600. name: 'se',
  18601. xMul: 1,
  18602. yMul: 1,
  18603. deltaX: 0,
  18604. deltaY: 0,
  18605. deltaW: 1,
  18606. deltaH: 1,
  18607. label: 'Bottom Right Crop Handle'
  18608. }
  18609. ];
  18610. var blockers = [
  18611. 'top',
  18612. 'right',
  18613. 'bottom',
  18614. 'left'
  18615. ];
  18616. var getAbsoluteRect = function (outerRect, relativeRect) {
  18617. return {
  18618. x: relativeRect.x + outerRect.x,
  18619. y: relativeRect.y + outerRect.y,
  18620. w: relativeRect.w,
  18621. h: relativeRect.h
  18622. };
  18623. };
  18624. var getRelativeRect = function (outerRect, innerRect) {
  18625. return {
  18626. x: innerRect.x - outerRect.x,
  18627. y: innerRect.y - outerRect.y,
  18628. w: innerRect.w,
  18629. h: innerRect.h
  18630. };
  18631. };
  18632. var getInnerRect = function () {
  18633. return getRelativeRect(clampRect, currentRect);
  18634. };
  18635. var moveRect = function (handle, startRect, deltaX, deltaY) {
  18636. var x = startRect.x + deltaX * handle.deltaX;
  18637. var y = startRect.y + deltaY * handle.deltaY;
  18638. var w = Math.max(20, startRect.w + deltaX * handle.deltaW);
  18639. var h = Math.max(20, startRect.h + deltaY * handle.deltaH);
  18640. var rect = currentRect = global$4.clamp({
  18641. x: x,
  18642. y: y,
  18643. w: w,
  18644. h: h
  18645. }, clampRect, handle.name === 'move');
  18646. rect = getRelativeRect(clampRect, rect);
  18647. instance.fire('updateRect', { rect: rect });
  18648. setInnerRect(rect);
  18649. };
  18650. var render = function () {
  18651. var createDragHelper = function (handle) {
  18652. var startRect;
  18653. return DragHelper(id, {
  18654. document: containerElm.ownerDocument,
  18655. root: getRootNode(container).dom,
  18656. handle: id + '-' + handle.name,
  18657. start: function () {
  18658. startRect = currentRect;
  18659. },
  18660. drag: function (e) {
  18661. moveRect(handle, startRect, e.deltaX, e.deltaY);
  18662. }
  18663. });
  18664. };
  18665. var cropContainer = SugarElement.fromTag('div');
  18666. setAll$1(cropContainer, {
  18667. id: id,
  18668. 'class': prefix + 'croprect-container',
  18669. 'role': 'grid',
  18670. 'aria-dropeffect': 'execute'
  18671. });
  18672. append$2(container, cropContainer);
  18673. each$1(blockers, function (blocker) {
  18674. descendant(container, '#' + id).each(function (blockerElm) {
  18675. var cropBlocker = SugarElement.fromTag('div');
  18676. setAll$1(cropBlocker, {
  18677. 'id': id + '-' + blocker,
  18678. 'class': prefix + 'croprect-block',
  18679. 'data-mce-bogus': 'all'
  18680. });
  18681. set$7(cropBlocker, 'display', 'none');
  18682. append$2(blockerElm, cropBlocker);
  18683. });
  18684. });
  18685. each$1(handles, function (handle) {
  18686. descendant(container, '#' + id).each(function (handleElm) {
  18687. var cropHandle = SugarElement.fromTag('div');
  18688. setAll$1(cropHandle, {
  18689. 'id': id + '-' + handle.name,
  18690. 'aria-label': handle.label,
  18691. 'aria-grabbed': 'false',
  18692. 'data-mce-bogus': 'all',
  18693. 'role': 'gridcell',
  18694. 'tabindex': '-1',
  18695. 'title': handle.label
  18696. });
  18697. add$1(cropHandle, [
  18698. prefix + 'croprect-handle',
  18699. prefix + 'croprect-handle-' + handle.name
  18700. ]);
  18701. set$7(cropHandle, 'display', 'none');
  18702. append$2(handleElm, cropHandle);
  18703. });
  18704. });
  18705. dragHelpers = map$2(handles, createDragHelper);
  18706. repaint(currentRect);
  18707. var handleFocus = function (e) {
  18708. set$8(e.target, 'aria-grabbed', e.raw.type === 'focus' ? 'true' : 'false');
  18709. };
  18710. var handleKeydown = function (e) {
  18711. var activeHandle;
  18712. each$1(handles, function (handle) {
  18713. if (get$d(e.target, 'id') === id + '-' + handle.name) {
  18714. activeHandle = handle;
  18715. return false;
  18716. }
  18717. });
  18718. var moveAndBlock = function (evt, handle, startRect, deltaX, deltaY) {
  18719. evt.stopPropagation();
  18720. evt.preventDefault();
  18721. moveRect(activeHandle, startRect, deltaX, deltaY);
  18722. };
  18723. switch (e.raw.keyCode) {
  18724. case global$2.LEFT:
  18725. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  18726. break;
  18727. case global$2.RIGHT:
  18728. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  18729. break;
  18730. case global$2.UP:
  18731. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  18732. break;
  18733. case global$2.DOWN:
  18734. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  18735. break;
  18736. case global$2.ENTER:
  18737. case global$2.SPACEBAR:
  18738. e.prevent();
  18739. action();
  18740. break;
  18741. }
  18742. };
  18743. events.push(bind(container, 'focusin', handleFocus), bind(container, 'focusout', handleFocus), bind(container, 'keydown', handleKeydown));
  18744. };
  18745. var toggleVisibility = function (state) {
  18746. var selectors = __spreadArray(__spreadArray([], map$2(handles, function (handle) {
  18747. return '#' + id + '-' + handle.name;
  18748. }), true), map$2(blockers, function (blocker) {
  18749. return '#' + id + '-' + blocker;
  18750. }), true).join(',');
  18751. var elems = descendants(container, selectors);
  18752. if (state) {
  18753. each$1(elems, function (elm) {
  18754. return remove$6(elm, 'display');
  18755. });
  18756. } else {
  18757. each$1(elems, function (elm) {
  18758. return set$7(elm, 'display', 'none');
  18759. });
  18760. }
  18761. };
  18762. var repaint = function (rect) {
  18763. var updateElementRect = function (name, newRect) {
  18764. descendant(container, '#' + id + '-' + name).each(function (elm) {
  18765. setAll(elm, {
  18766. left: newRect.x + 'px',
  18767. top: newRect.y + 'px',
  18768. width: Math.max(0, newRect.w) + 'px',
  18769. height: Math.max(0, newRect.h) + 'px'
  18770. });
  18771. });
  18772. };
  18773. each$1(handles, function (handle) {
  18774. descendant(container, '#' + id + '-' + handle.name).each(function (elm) {
  18775. setAll(elm, {
  18776. left: rect.w * handle.xMul + rect.x + 'px',
  18777. top: rect.h * handle.yMul + rect.y + 'px'
  18778. });
  18779. });
  18780. });
  18781. updateElementRect('top', {
  18782. x: viewPortRect.x,
  18783. y: viewPortRect.y,
  18784. w: viewPortRect.w,
  18785. h: rect.y - viewPortRect.y
  18786. });
  18787. updateElementRect('right', {
  18788. x: rect.x + rect.w,
  18789. y: rect.y,
  18790. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  18791. h: rect.h
  18792. });
  18793. updateElementRect('bottom', {
  18794. x: viewPortRect.x,
  18795. y: rect.y + rect.h,
  18796. w: viewPortRect.w,
  18797. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  18798. });
  18799. updateElementRect('left', {
  18800. x: viewPortRect.x,
  18801. y: rect.y,
  18802. w: rect.x - viewPortRect.x,
  18803. h: rect.h
  18804. });
  18805. updateElementRect('move', rect);
  18806. };
  18807. var setRect = function (rect) {
  18808. currentRect = rect;
  18809. repaint(currentRect);
  18810. };
  18811. var setViewPortRect = function (rect) {
  18812. viewPortRect = rect;
  18813. repaint(currentRect);
  18814. };
  18815. var setInnerRect = function (rect) {
  18816. setRect(getAbsoluteRect(clampRect, rect));
  18817. };
  18818. var setClampRect = function (rect) {
  18819. clampRect = rect;
  18820. repaint(currentRect);
  18821. };
  18822. var destroy = function () {
  18823. each$1(dragHelpers, function (helper) {
  18824. return helper.destroy();
  18825. });
  18826. dragHelpers = [];
  18827. each$1(events, function (e) {
  18828. return e.unbind();
  18829. });
  18830. events = [];
  18831. };
  18832. render();
  18833. var instance = __assign(__assign({}, global$3), {
  18834. toggleVisibility: toggleVisibility,
  18835. setClampRect: setClampRect,
  18836. setRect: setRect,
  18837. getInnerRect: getInnerRect,
  18838. setInnerRect: setInnerRect,
  18839. setViewPortRect: setViewPortRect,
  18840. destroy: destroy
  18841. });
  18842. return instance;
  18843. };
  18844. var CropRect = { create: create$1 };
  18845. var loadImage = function (image) {
  18846. return new global$c(function (resolve) {
  18847. var loaded = function () {
  18848. image.removeEventListener('load', loaded);
  18849. resolve(image);
  18850. };
  18851. if (image.complete) {
  18852. resolve(image);
  18853. } else {
  18854. image.addEventListener('load', loaded);
  18855. }
  18856. });
  18857. };
  18858. var renderImagePanel = function (initialUrl) {
  18859. var memBg = record({
  18860. dom: {
  18861. tag: 'div',
  18862. classes: ['tox-image-tools__image-bg'],
  18863. attributes: { role: 'presentation' }
  18864. }
  18865. });
  18866. var zoomState = Cell(1);
  18867. var cropRect = api$1();
  18868. var rectState = Cell({
  18869. x: 0,
  18870. y: 0,
  18871. w: 1,
  18872. h: 1
  18873. });
  18874. var viewRectState = Cell({
  18875. x: 0,
  18876. y: 0,
  18877. w: 1,
  18878. h: 1
  18879. });
  18880. var repaintImg = function (anyInSystem, img) {
  18881. memContainer.getOpt(anyInSystem).each(function (panel) {
  18882. var zoom = zoomState.get();
  18883. var panelW = get$a(panel.element);
  18884. var panelH = get$b(panel.element);
  18885. var width = img.dom.naturalWidth * zoom;
  18886. var height = img.dom.naturalHeight * zoom;
  18887. var left = Math.max(0, panelW / 2 - width / 2);
  18888. var top = Math.max(0, panelH / 2 - height / 2);
  18889. var css = {
  18890. left: left.toString() + 'px',
  18891. top: top.toString() + 'px',
  18892. width: width.toString() + 'px',
  18893. height: height.toString() + 'px',
  18894. position: 'absolute'
  18895. };
  18896. setAll(img, css);
  18897. memBg.getOpt(panel).each(function (bg) {
  18898. setAll(bg.element, css);
  18899. });
  18900. cropRect.run(function (cRect) {
  18901. var rect = rectState.get();
  18902. cRect.setRect({
  18903. x: rect.x * zoom + left,
  18904. y: rect.y * zoom + top,
  18905. w: rect.w * zoom,
  18906. h: rect.h * zoom
  18907. });
  18908. cRect.setClampRect({
  18909. x: left,
  18910. y: top,
  18911. w: width,
  18912. h: height
  18913. });
  18914. cRect.setViewPortRect({
  18915. x: 0,
  18916. y: 0,
  18917. w: panelW,
  18918. h: panelH
  18919. });
  18920. });
  18921. });
  18922. };
  18923. var zoomFit = function (anyInSystem, img) {
  18924. memContainer.getOpt(anyInSystem).each(function (panel) {
  18925. var panelW = get$a(panel.element);
  18926. var panelH = get$b(panel.element);
  18927. var width = img.dom.naturalWidth;
  18928. var height = img.dom.naturalHeight;
  18929. var zoom = Math.min(panelW / width, panelH / height);
  18930. if (zoom >= 1) {
  18931. zoomState.set(1);
  18932. } else {
  18933. zoomState.set(zoom);
  18934. }
  18935. });
  18936. };
  18937. var updateSrc = function (anyInSystem, url) {
  18938. var img = SugarElement.fromTag('img');
  18939. set$8(img, 'src', url);
  18940. return loadImage(img.dom).then(function () {
  18941. if (anyInSystem.getSystem().isConnected()) {
  18942. memContainer.getOpt(anyInSystem).map(function (panel) {
  18943. var aImg = external$2({ element: img });
  18944. Replacing.replaceAt(panel, 1, Optional.some(aImg));
  18945. var lastViewRect = viewRectState.get();
  18946. var viewRect = {
  18947. x: 0,
  18948. y: 0,
  18949. w: img.dom.naturalWidth,
  18950. h: img.dom.naturalHeight
  18951. };
  18952. viewRectState.set(viewRect);
  18953. var rect = global$4.inflate(viewRect, -20, -20);
  18954. rectState.set(rect);
  18955. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  18956. zoomFit(panel, img);
  18957. }
  18958. repaintImg(panel, img);
  18959. });
  18960. }
  18961. });
  18962. };
  18963. var zoom = function (anyInSystem, direction) {
  18964. var currentZoom = zoomState.get();
  18965. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  18966. zoomState.set(newZoom);
  18967. memContainer.getOpt(anyInSystem).each(function (panel) {
  18968. var img = panel.components()[1].element;
  18969. repaintImg(panel, img);
  18970. });
  18971. };
  18972. var showCrop = function () {
  18973. cropRect.run(function (cRect) {
  18974. cRect.toggleVisibility(true);
  18975. });
  18976. };
  18977. var hideCrop = function () {
  18978. cropRect.run(function (cRect) {
  18979. cRect.toggleVisibility(false);
  18980. });
  18981. };
  18982. var getRect = function () {
  18983. return rectState.get();
  18984. };
  18985. var container = Container.sketch({
  18986. dom: {
  18987. tag: 'div',
  18988. classes: ['tox-image-tools__image']
  18989. },
  18990. components: [
  18991. memBg.asSpec(),
  18992. {
  18993. dom: {
  18994. tag: 'img',
  18995. attributes: { src: initialUrl }
  18996. }
  18997. },
  18998. {
  18999. dom: { tag: 'div' },
  19000. behaviours: derive$1([config('image-panel-crop-events', [
  19001. runOnAttached(function (comp) {
  19002. memContainer.getOpt(comp).each(function (container) {
  19003. var el = container.element.dom;
  19004. var cRect = CropRect.create({
  19005. x: 10,
  19006. y: 10,
  19007. w: 100,
  19008. h: 100
  19009. }, {
  19010. x: 0,
  19011. y: 0,
  19012. w: 200,
  19013. h: 200
  19014. }, {
  19015. x: 0,
  19016. y: 0,
  19017. w: 200,
  19018. h: 200
  19019. }, el, noop);
  19020. cRect.toggleVisibility(false);
  19021. cRect.on('updateRect', function (e) {
  19022. var rect = e.rect;
  19023. var zoom = zoomState.get();
  19024. var newRect = {
  19025. x: Math.round(rect.x / zoom),
  19026. y: Math.round(rect.y / zoom),
  19027. w: Math.round(rect.w / zoom),
  19028. h: Math.round(rect.h / zoom)
  19029. };
  19030. rectState.set(newRect);
  19031. });
  19032. cropRect.set(cRect);
  19033. });
  19034. }),
  19035. runOnDetached(function () {
  19036. cropRect.clear();
  19037. })
  19038. ])])
  19039. }
  19040. ],
  19041. containerBehaviours: derive$1([
  19042. Replacing.config({}),
  19043. config('image-panel-events', [runOnAttached(function (comp) {
  19044. updateSrc(comp, initialUrl);
  19045. })])
  19046. ])
  19047. });
  19048. var memContainer = record(container);
  19049. var getMeasurements = function () {
  19050. var viewRect = viewRectState.get();
  19051. return {
  19052. width: viewRect.w,
  19053. height: viewRect.h
  19054. };
  19055. };
  19056. return {
  19057. memContainer: memContainer,
  19058. updateSrc: updateSrc,
  19059. zoom: zoom,
  19060. showCrop: showCrop,
  19061. hideCrop: hideCrop,
  19062. getRect: getRect,
  19063. getMeasurements: getMeasurements
  19064. };
  19065. };
  19066. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  19067. return renderIconButton({
  19068. name: innerHtml,
  19069. icon: Optional.some(icon),
  19070. disabled: disabled,
  19071. tooltip: Optional.some(innerHtml),
  19072. primary: false,
  19073. borderless: false
  19074. }, action, providersBackstage);
  19075. };
  19076. var setButtonEnabled = function (button, enabled) {
  19077. if (enabled) {
  19078. Disabling.enable(button);
  19079. } else {
  19080. Disabling.disable(button);
  19081. }
  19082. };
  19083. var renderSideBar = function (providersBackstage) {
  19084. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  19085. memUndo.getOpt(anyInSystem).each(function (undo) {
  19086. setButtonEnabled(undo, undoEnabled);
  19087. });
  19088. memRedo.getOpt(anyInSystem).each(function (redo) {
  19089. setButtonEnabled(redo, redoEnabled);
  19090. });
  19091. };
  19092. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  19093. emitWith(button, internal.undo(), { direction: 1 });
  19094. }, providersBackstage));
  19095. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  19096. emitWith(button, internal.redo(), { direction: 1 });
  19097. }, providersBackstage));
  19098. var container = Container.sketch({
  19099. dom: {
  19100. tag: 'div',
  19101. classes: [
  19102. 'tox-image-tools__toolbar',
  19103. 'tox-image-tools__sidebar'
  19104. ]
  19105. },
  19106. components: [
  19107. memUndo.asSpec(),
  19108. memRedo.asSpec(),
  19109. createButton('Zoom in', 'zoom-in', false, function (button) {
  19110. emitWith(button, internal.zoom(), { direction: 1 });
  19111. }, providersBackstage),
  19112. createButton('Zoom out', 'zoom-out', false, function (button) {
  19113. emitWith(button, internal.zoom(), { direction: -1 });
  19114. }, providersBackstage)
  19115. ]
  19116. });
  19117. return {
  19118. container: container,
  19119. updateButtonUndoStates: updateButtonUndoStates
  19120. };
  19121. };
  19122. function UndoStack () {
  19123. var data = [];
  19124. var index = -1;
  19125. var add = function (state) {
  19126. var removed = data.splice(++index);
  19127. data.push(state);
  19128. return {
  19129. state: state,
  19130. removed: removed
  19131. };
  19132. };
  19133. var undo = function () {
  19134. if (canUndo()) {
  19135. return data[--index];
  19136. }
  19137. };
  19138. var redo = function () {
  19139. if (canRedo()) {
  19140. return data[++index];
  19141. }
  19142. };
  19143. var canUndo = function () {
  19144. return index > 0;
  19145. };
  19146. var canRedo = function () {
  19147. return index !== -1 && index < data.length - 1;
  19148. };
  19149. return {
  19150. data: data,
  19151. add: add,
  19152. undo: undo,
  19153. redo: redo,
  19154. canUndo: canUndo,
  19155. canRedo: canRedo
  19156. };
  19157. }
  19158. var makeState = function (initialState) {
  19159. var blobState = Cell(initialState);
  19160. var tempState = value$1();
  19161. var undoStack = UndoStack();
  19162. undoStack.add(initialState);
  19163. var getBlobState = function () {
  19164. return blobState.get();
  19165. };
  19166. var setBlobState = function (state) {
  19167. blobState.set(state);
  19168. };
  19169. var getTempState = function () {
  19170. return tempState.get().getOrThunk(blobState.get);
  19171. };
  19172. var updateTempState = function (blob) {
  19173. var newTempState = createState(blob);
  19174. destroyTempState();
  19175. tempState.set(newTempState);
  19176. return newTempState.url;
  19177. };
  19178. var createState = function (blob) {
  19179. return {
  19180. blob: blob,
  19181. url: URL.createObjectURL(blob)
  19182. };
  19183. };
  19184. var destroyState = function (state) {
  19185. URL.revokeObjectURL(state.url);
  19186. };
  19187. var destroyStates = function (states) {
  19188. global$5.each(states, destroyState);
  19189. };
  19190. var destroyTempState = function () {
  19191. tempState.on(destroyState);
  19192. tempState.clear();
  19193. };
  19194. var addBlobState = function (blob) {
  19195. var newState = createState(blob);
  19196. setBlobState(newState);
  19197. var removed = undoStack.add(newState).removed;
  19198. destroyStates(removed);
  19199. return newState.url;
  19200. };
  19201. var addTempState = function (blob) {
  19202. var newState = createState(blob);
  19203. tempState.set(newState);
  19204. return newState.url;
  19205. };
  19206. var applyTempState = function (postApply) {
  19207. return tempState.get().fold(noop, function (temp) {
  19208. addBlobState(temp.blob);
  19209. postApply();
  19210. });
  19211. };
  19212. var undo = function () {
  19213. var currentState = undoStack.undo();
  19214. setBlobState(currentState);
  19215. return currentState.url;
  19216. };
  19217. var redo = function () {
  19218. var currentState = undoStack.redo();
  19219. setBlobState(currentState);
  19220. return currentState.url;
  19221. };
  19222. var getHistoryStates = function () {
  19223. var undoEnabled = undoStack.canUndo();
  19224. var redoEnabled = undoStack.canRedo();
  19225. return {
  19226. undoEnabled: undoEnabled,
  19227. redoEnabled: redoEnabled
  19228. };
  19229. };
  19230. return {
  19231. getBlobState: getBlobState,
  19232. setBlobState: setBlobState,
  19233. addBlobState: addBlobState,
  19234. getTempState: getTempState,
  19235. updateTempState: updateTempState,
  19236. addTempState: addTempState,
  19237. applyTempState: applyTempState,
  19238. destroyTempState: destroyTempState,
  19239. undo: undo,
  19240. redo: redo,
  19241. getHistoryStates: getHistoryStates
  19242. };
  19243. };
  19244. var renderImageTools = function (detail, providersBackstage) {
  19245. var state = makeState(detail.currentState);
  19246. var zoom = function (anyInSystem, simulatedEvent) {
  19247. var direction = simulatedEvent.event.direction;
  19248. imagePanel.zoom(anyInSystem, direction);
  19249. };
  19250. var updateButtonUndoStates = function (anyInSystem) {
  19251. var historyStates = state.getHistoryStates();
  19252. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  19253. emitWith(anyInSystem, external.formActionEvent, {
  19254. name: external.saveState(),
  19255. value: historyStates.undoEnabled
  19256. });
  19257. };
  19258. var disableUndoRedo = function (anyInSystem) {
  19259. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  19260. };
  19261. var undo = function (anyInSystem, _simulatedEvent) {
  19262. var url = state.undo();
  19263. updateSrc(anyInSystem, url).then(function (_oImg) {
  19264. unblock(anyInSystem);
  19265. updateButtonUndoStates(anyInSystem);
  19266. });
  19267. };
  19268. var redo = function (anyInSystem, _simulatedEvent) {
  19269. var url = state.redo();
  19270. updateSrc(anyInSystem, url).then(function (_oImg) {
  19271. unblock(anyInSystem);
  19272. updateButtonUndoStates(anyInSystem);
  19273. });
  19274. };
  19275. var imageResultToBlob = function (ir) {
  19276. return ir.toBlob();
  19277. };
  19278. var block = function (anyInSystem) {
  19279. emitWith(anyInSystem, external.formActionEvent, {
  19280. name: external.disable(),
  19281. value: {}
  19282. });
  19283. };
  19284. var unblock = function (anyInSystem) {
  19285. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  19286. Disabling.enable(applyButton);
  19287. });
  19288. emitWith(anyInSystem, external.formActionEvent, {
  19289. name: external.enable(),
  19290. value: {}
  19291. });
  19292. };
  19293. var updateSrc = function (anyInSystem, src) {
  19294. block(anyInSystem);
  19295. return imagePanel.updateSrc(anyInSystem, src);
  19296. };
  19297. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  19298. block(anyInSystem);
  19299. blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  19300. return updateSrc(anyInSystem, url);
  19301. }).then(function () {
  19302. updateButtonUndoStates(anyInSystem);
  19303. swap();
  19304. unblock(anyInSystem);
  19305. }).catch(function (err) {
  19306. console.log(err);
  19307. if (anyInSystem.getSystem().isConnected()) {
  19308. unblock(anyInSystem);
  19309. }
  19310. });
  19311. };
  19312. var manipulate = function (anyInSystem, filter, swap) {
  19313. var blob = state.getBlobState().blob;
  19314. var action = function (blob) {
  19315. return state.updateTempState(blob);
  19316. };
  19317. blobManipulate(anyInSystem, blob, filter, action, swap);
  19318. };
  19319. var tempManipulate = function (anyInSystem, filter) {
  19320. var blob = state.getTempState().blob;
  19321. var action = function (blob) {
  19322. return state.addTempState(blob);
  19323. };
  19324. blobManipulate(anyInSystem, blob, filter, action, noop);
  19325. };
  19326. var manipulateApply = function (anyInSystem, filter, swap) {
  19327. var blob = state.getBlobState().blob;
  19328. var action = function (blob) {
  19329. var url = state.addBlobState(blob);
  19330. destroyTempState(anyInSystem);
  19331. return url;
  19332. };
  19333. blobManipulate(anyInSystem, blob, filter, action, swap);
  19334. };
  19335. var apply = function (anyInSystem, simulatedEvent) {
  19336. var postApply = function () {
  19337. destroyTempState(anyInSystem);
  19338. var swap = simulatedEvent.event.swap;
  19339. swap();
  19340. };
  19341. state.applyTempState(postApply);
  19342. };
  19343. var destroyTempState = function (anyInSystem) {
  19344. var currentUrl = state.getBlobState().url;
  19345. state.destroyTempState();
  19346. updateButtonUndoStates(anyInSystem);
  19347. return currentUrl;
  19348. };
  19349. var cancel = function (anyInSystem) {
  19350. var currentUrl = destroyTempState(anyInSystem);
  19351. updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
  19352. unblock(anyInSystem);
  19353. });
  19354. };
  19355. var back = function (anyInSystem, simulatedEvent) {
  19356. cancel(anyInSystem);
  19357. var swap = simulatedEvent.event.swap;
  19358. swap();
  19359. imagePanel.hideCrop();
  19360. };
  19361. var transform = function (anyInSystem, simulatedEvent) {
  19362. return manipulate(anyInSystem, simulatedEvent.event.transform, noop);
  19363. };
  19364. var tempTransform = function (anyInSystem, simulatedEvent) {
  19365. return tempManipulate(anyInSystem, simulatedEvent.event.transform);
  19366. };
  19367. var transformApply = function (anyInSystem, simulatedEvent) {
  19368. return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap);
  19369. };
  19370. var imagePanel = renderImagePanel(detail.currentState.url);
  19371. var sideBar = renderSideBar(providersBackstage);
  19372. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  19373. var swap = function (anyInSystem, simulatedEvent) {
  19374. disableUndoRedo(anyInSystem);
  19375. var transform = simulatedEvent.event.transform;
  19376. var swap = simulatedEvent.event.swap;
  19377. transform.fold(function () {
  19378. swap();
  19379. }, function (transform) {
  19380. manipulate(anyInSystem, transform, swap);
  19381. });
  19382. };
  19383. return {
  19384. dom: {
  19385. tag: 'div',
  19386. attributes: { role: 'presentation' }
  19387. },
  19388. components: [
  19389. editPanel.memContainer.asSpec(),
  19390. imagePanel.memContainer.asSpec(),
  19391. sideBar.container
  19392. ],
  19393. behaviours: derive$1([
  19394. Representing.config({
  19395. store: {
  19396. mode: 'manual',
  19397. getValue: function () {
  19398. return state.getBlobState();
  19399. }
  19400. }
  19401. }),
  19402. config('image-tools-events', [
  19403. run$1(internal.undo(), undo),
  19404. run$1(internal.redo(), redo),
  19405. run$1(internal.zoom(), zoom),
  19406. run$1(internal.back(), back),
  19407. run$1(internal.apply(), apply),
  19408. run$1(internal.transform(), transform),
  19409. run$1(internal.tempTransform(), tempTransform),
  19410. run$1(internal.transformApply(), transformApply),
  19411. run$1(internal.swap(), swap)
  19412. ]),
  19413. ComposingConfigs.self()
  19414. ])
  19415. };
  19416. };
  19417. var renderLabel = function (spec, backstageShared) {
  19418. var label = {
  19419. dom: {
  19420. tag: 'label',
  19421. innerHtml: backstageShared.providers.translate(spec.label),
  19422. classes: ['tox-label']
  19423. }
  19424. };
  19425. var comps = map$2(spec.items, backstageShared.interpreter);
  19426. return {
  19427. dom: {
  19428. tag: 'div',
  19429. classes: ['tox-form__group']
  19430. },
  19431. components: [label].concat(comps),
  19432. behaviours: derive$1([
  19433. ComposingConfigs.self(),
  19434. Replacing.config({}),
  19435. RepresentingConfigs.domHtml(Optional.none()),
  19436. Keying.config({ mode: 'acyclic' })
  19437. ])
  19438. };
  19439. };
  19440. var isSingleListItem = function (item) {
  19441. return !has$2(item, 'items');
  19442. };
  19443. var dataAttribute = 'data-value';
  19444. var fetchItems = function (dropdownComp, name, items, selectedValue) {
  19445. return map$2(items, function (item) {
  19446. if (!isSingleListItem(item)) {
  19447. return {
  19448. type: 'nestedmenuitem',
  19449. text: item.text,
  19450. getSubmenuItems: function () {
  19451. return fetchItems(dropdownComp, name, item.items, selectedValue);
  19452. }
  19453. };
  19454. } else {
  19455. return {
  19456. type: 'togglemenuitem',
  19457. text: item.text,
  19458. value: item.value,
  19459. active: item.value === selectedValue,
  19460. onAction: function () {
  19461. Representing.setValue(dropdownComp, item.value);
  19462. emitWith(dropdownComp, formChangeEvent, { name: name });
  19463. Focusing.focus(dropdownComp);
  19464. }
  19465. };
  19466. }
  19467. });
  19468. };
  19469. var findItemByValue = function (items, value) {
  19470. return findMap(items, function (item) {
  19471. if (!isSingleListItem(item)) {
  19472. return findItemByValue(item.items, value);
  19473. } else {
  19474. return someIf(item.value === value, item);
  19475. }
  19476. });
  19477. };
  19478. var renderListBox = function (spec, backstage) {
  19479. var providersBackstage = backstage.shared.providers;
  19480. var initialItem = head(spec.items).filter(isSingleListItem);
  19481. var pLabel = spec.label.map(function (label) {
  19482. return renderLabel$2(label, providersBackstage);
  19483. });
  19484. var pField = FormField.parts.field({
  19485. dom: {},
  19486. factory: {
  19487. sketch: function (sketchSpec) {
  19488. return renderCommonDropdown({
  19489. uid: sketchSpec.uid,
  19490. text: initialItem.map(function (item) {
  19491. return item.text;
  19492. }),
  19493. icon: Optional.none(),
  19494. tooltip: spec.label,
  19495. role: Optional.none(),
  19496. fetch: function (comp, callback) {
  19497. var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp));
  19498. callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  19499. },
  19500. onSetup: constant$1(noop),
  19501. getApi: constant$1({}),
  19502. columns: 1,
  19503. presets: 'normal',
  19504. classes: [],
  19505. dropdownBehaviours: [
  19506. Tabstopping.config({}),
  19507. Representing.config({
  19508. store: {
  19509. mode: 'manual',
  19510. initialValue: initialItem.map(function (item) {
  19511. return item.value;
  19512. }).getOr(''),
  19513. getValue: function (comp) {
  19514. return get$d(comp.element, dataAttribute);
  19515. },
  19516. setValue: function (comp, data) {
  19517. findItemByValue(spec.items, data).each(function (item) {
  19518. set$8(comp.element, dataAttribute, item.value);
  19519. emitWith(comp, updateMenuText, { text: item.text });
  19520. });
  19521. }
  19522. }
  19523. })
  19524. ]
  19525. }, 'tox-listbox', backstage.shared);
  19526. }
  19527. }
  19528. });
  19529. var listBoxWrap = {
  19530. dom: {
  19531. tag: 'div',
  19532. classes: ['tox-listboxfield']
  19533. },
  19534. components: [pField]
  19535. };
  19536. return FormField.sketch({
  19537. dom: {
  19538. tag: 'div',
  19539. classes: ['tox-form__group']
  19540. },
  19541. components: flatten([
  19542. pLabel.toArray(),
  19543. [listBoxWrap]
  19544. ]),
  19545. fieldBehaviours: derive$1([Disabling.config({
  19546. disabled: constant$1(spec.disabled),
  19547. onDisabled: function (comp) {
  19548. FormField.getField(comp).each(Disabling.disable);
  19549. },
  19550. onEnabled: function (comp) {
  19551. FormField.getField(comp).each(Disabling.enable);
  19552. }
  19553. })])
  19554. });
  19555. };
  19556. var renderPanel = function (spec, backstage) {
  19557. return {
  19558. dom: {
  19559. tag: 'div',
  19560. classes: spec.classes
  19561. },
  19562. components: map$2(spec.items, backstage.shared.interpreter)
  19563. };
  19564. };
  19565. var factory$e = function (detail, _spec) {
  19566. var options = map$2(detail.options, function (option) {
  19567. return {
  19568. dom: {
  19569. tag: 'option',
  19570. value: option.value,
  19571. innerHtml: option.text
  19572. }
  19573. };
  19574. });
  19575. var initialValues = detail.data.map(function (v) {
  19576. return wrap$1('initialValue', v);
  19577. }).getOr({});
  19578. return {
  19579. uid: detail.uid,
  19580. dom: {
  19581. tag: 'select',
  19582. classes: detail.selectClasses,
  19583. attributes: detail.selectAttributes
  19584. },
  19585. components: options,
  19586. behaviours: augment(detail.selectBehaviours, [
  19587. Focusing.config({}),
  19588. Representing.config({
  19589. store: __assign({
  19590. mode: 'manual',
  19591. getValue: function (select) {
  19592. return get$5(select.element);
  19593. },
  19594. setValue: function (select, newValue) {
  19595. var found = find$5(detail.options, function (opt) {
  19596. return opt.value === newValue;
  19597. });
  19598. if (found.isSome()) {
  19599. set$4(select.element, newValue);
  19600. }
  19601. }
  19602. }, initialValues)
  19603. })
  19604. ])
  19605. };
  19606. };
  19607. var HtmlSelect = single({
  19608. name: 'HtmlSelect',
  19609. configFields: [
  19610. required$1('options'),
  19611. field('selectBehaviours', [
  19612. Focusing,
  19613. Representing
  19614. ]),
  19615. defaulted('selectClasses', []),
  19616. defaulted('selectAttributes', {}),
  19617. option('data')
  19618. ],
  19619. factory: factory$e
  19620. });
  19621. var renderSelectBox = function (spec, providersBackstage) {
  19622. var translatedOptions = map$2(spec.items, function (item) {
  19623. return {
  19624. text: providersBackstage.translate(item.text),
  19625. value: item.value
  19626. };
  19627. });
  19628. var pLabel = spec.label.map(function (label) {
  19629. return renderLabel$2(label, providersBackstage);
  19630. });
  19631. var pField = FormField.parts.field({
  19632. dom: {},
  19633. selectAttributes: { size: spec.size },
  19634. options: translatedOptions,
  19635. factory: HtmlSelect,
  19636. selectBehaviours: derive$1([
  19637. Disabling.config({
  19638. disabled: function () {
  19639. return spec.disabled || providersBackstage.isDisabled();
  19640. }
  19641. }),
  19642. Tabstopping.config({}),
  19643. config('selectbox-change', [run$1(change(), function (component, _) {
  19644. emitWith(component, formChangeEvent, { name: spec.name });
  19645. })])
  19646. ])
  19647. });
  19648. var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3('chevron-down', {
  19649. tag: 'div',
  19650. classes: ['tox-selectfield__icon-js']
  19651. }, providersBackstage.icons));
  19652. var selectWrap = {
  19653. dom: {
  19654. tag: 'div',
  19655. classes: ['tox-selectfield']
  19656. },
  19657. components: flatten([
  19658. [pField],
  19659. chevron.toArray()
  19660. ])
  19661. };
  19662. return FormField.sketch({
  19663. dom: {
  19664. tag: 'div',
  19665. classes: ['tox-form__group']
  19666. },
  19667. components: flatten([
  19668. pLabel.toArray(),
  19669. [selectWrap]
  19670. ]),
  19671. fieldBehaviours: derive$1([
  19672. Disabling.config({
  19673. disabled: function () {
  19674. return spec.disabled || providersBackstage.isDisabled();
  19675. },
  19676. onDisabled: function (comp) {
  19677. FormField.getField(comp).each(Disabling.disable);
  19678. },
  19679. onEnabled: function (comp) {
  19680. FormField.getField(comp).each(Disabling.enable);
  19681. }
  19682. }),
  19683. receivingConfig()
  19684. ])
  19685. });
  19686. };
  19687. var renderTable = function (spec, providersBackstage) {
  19688. var renderTh = function (text) {
  19689. return {
  19690. dom: {
  19691. tag: 'th',
  19692. innerHtml: providersBackstage.translate(text)
  19693. }
  19694. };
  19695. };
  19696. var renderHeader = function (header) {
  19697. return {
  19698. dom: { tag: 'thead' },
  19699. components: [{
  19700. dom: { tag: 'tr' },
  19701. components: map$2(header, renderTh)
  19702. }]
  19703. };
  19704. };
  19705. var renderTd = function (text) {
  19706. return {
  19707. dom: {
  19708. tag: 'td',
  19709. innerHtml: providersBackstage.translate(text)
  19710. }
  19711. };
  19712. };
  19713. var renderTr = function (row) {
  19714. return {
  19715. dom: { tag: 'tr' },
  19716. components: map$2(row, renderTd)
  19717. };
  19718. };
  19719. var renderRows = function (rows) {
  19720. return {
  19721. dom: { tag: 'tbody' },
  19722. components: map$2(rows, renderTr)
  19723. };
  19724. };
  19725. return {
  19726. dom: {
  19727. tag: 'table',
  19728. classes: ['tox-dialog__table']
  19729. },
  19730. components: [
  19731. renderHeader(spec.header),
  19732. renderRows(spec.cells)
  19733. ],
  19734. behaviours: derive$1([
  19735. Tabstopping.config({}),
  19736. Focusing.config({})
  19737. ])
  19738. };
  19739. };
  19740. var renderTextField = function (spec, providersBackstage) {
  19741. var pLabel = spec.label.map(function (label) {
  19742. return renderLabel$2(label, providersBackstage);
  19743. });
  19744. var baseInputBehaviours = [
  19745. Disabling.config({
  19746. disabled: function () {
  19747. return spec.disabled || providersBackstage.isDisabled();
  19748. }
  19749. }),
  19750. receivingConfig(),
  19751. Keying.config({
  19752. mode: 'execution',
  19753. useEnter: spec.multiline !== true,
  19754. useControlEnter: spec.multiline === true,
  19755. execute: function (comp) {
  19756. emit(comp, formSubmitEvent);
  19757. return Optional.some(true);
  19758. }
  19759. }),
  19760. config('textfield-change', [
  19761. run$1(input(), function (component, _) {
  19762. emitWith(component, formChangeEvent, { name: spec.name });
  19763. }),
  19764. run$1(postPaste(), function (component, _) {
  19765. emitWith(component, formChangeEvent, { name: spec.name });
  19766. })
  19767. ]),
  19768. Tabstopping.config({})
  19769. ];
  19770. var validatingBehaviours = spec.validation.map(function (vl) {
  19771. return Invalidating.config({
  19772. getRoot: function (input) {
  19773. return parent(input.element);
  19774. },
  19775. invalidClass: 'tox-invalid',
  19776. validator: {
  19777. validate: function (input) {
  19778. var v = Representing.getValue(input);
  19779. var result = vl.validator(v);
  19780. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  19781. },
  19782. validateOnLoad: vl.validateOnLoad
  19783. }
  19784. });
  19785. }).toArray();
  19786. var placeholder = spec.placeholder.fold(constant$1({}), function (p) {
  19787. return { placeholder: providersBackstage.translate(p) };
  19788. });
  19789. var inputMode = spec.inputMode.fold(constant$1({}), function (mode) {
  19790. return { inputmode: mode };
  19791. });
  19792. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  19793. var pField = FormField.parts.field({
  19794. tag: spec.multiline === true ? 'textarea' : 'input',
  19795. inputAttributes: inputAttributes,
  19796. inputClasses: [spec.classname],
  19797. inputBehaviours: derive$1(flatten([
  19798. baseInputBehaviours,
  19799. validatingBehaviours
  19800. ])),
  19801. selectOnFocus: false,
  19802. factory: Input
  19803. });
  19804. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  19805. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  19806. var extraBehaviours = [
  19807. Disabling.config({
  19808. disabled: function () {
  19809. return spec.disabled || providersBackstage.isDisabled();
  19810. },
  19811. onDisabled: function (comp) {
  19812. FormField.getField(comp).each(Disabling.disable);
  19813. },
  19814. onEnabled: function (comp) {
  19815. FormField.getField(comp).each(Disabling.enable);
  19816. }
  19817. }),
  19818. receivingConfig()
  19819. ];
  19820. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  19821. };
  19822. var renderInput = function (spec, providersBackstage) {
  19823. return renderTextField({
  19824. name: spec.name,
  19825. multiline: false,
  19826. label: spec.label,
  19827. inputMode: spec.inputMode,
  19828. placeholder: spec.placeholder,
  19829. flex: false,
  19830. disabled: spec.disabled,
  19831. classname: 'tox-textfield',
  19832. validation: Optional.none(),
  19833. maximized: spec.maximized
  19834. }, providersBackstage);
  19835. };
  19836. var renderTextarea = function (spec, providersBackstage) {
  19837. return renderTextField({
  19838. name: spec.name,
  19839. multiline: true,
  19840. label: spec.label,
  19841. inputMode: Optional.none(),
  19842. placeholder: spec.placeholder,
  19843. flex: true,
  19844. disabled: spec.disabled,
  19845. classname: 'tox-textarea',
  19846. validation: Optional.none(),
  19847. maximized: spec.maximized
  19848. }, providersBackstage);
  19849. };
  19850. var events$6 = function (streamConfig, streamState) {
  19851. var streams = streamConfig.stream.streams;
  19852. var processor = streams.setup(streamConfig, streamState);
  19853. return derive$2([
  19854. run$1(streamConfig.event, processor),
  19855. runOnDetached(function () {
  19856. return streamState.cancel();
  19857. })
  19858. ].concat(streamConfig.cancelEvent.map(function (e) {
  19859. return [run$1(e, function () {
  19860. return streamState.cancel();
  19861. })];
  19862. }).getOr([])));
  19863. };
  19864. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  19865. __proto__: null,
  19866. events: events$6
  19867. });
  19868. var throttle = function (_config) {
  19869. var state = Cell(null);
  19870. var readState = function () {
  19871. return { timer: state.get() !== null ? 'set' : 'unset' };
  19872. };
  19873. var setTimer = function (t) {
  19874. state.set(t);
  19875. };
  19876. var cancel = function () {
  19877. var t = state.get();
  19878. if (t !== null) {
  19879. t.cancel();
  19880. }
  19881. };
  19882. return nu$8({
  19883. readState: readState,
  19884. setTimer: setTimer,
  19885. cancel: cancel
  19886. });
  19887. };
  19888. var init$9 = function (spec) {
  19889. return spec.stream.streams.state(spec);
  19890. };
  19891. var StreamingState = /*#__PURE__*/Object.freeze({
  19892. __proto__: null,
  19893. throttle: throttle,
  19894. init: init$9
  19895. });
  19896. var setup$c = function (streamInfo, streamState) {
  19897. var sInfo = streamInfo.stream;
  19898. var throttler = last(streamInfo.onStream, sInfo.delay);
  19899. streamState.setTimer(throttler);
  19900. return function (component, simulatedEvent) {
  19901. throttler.throttle(component, simulatedEvent);
  19902. if (sInfo.stopEvent) {
  19903. simulatedEvent.stop();
  19904. }
  19905. };
  19906. };
  19907. var StreamingSchema = [
  19908. requiredOf('stream', choose$1('mode', {
  19909. throttle: [
  19910. required$1('delay'),
  19911. defaulted('stopEvent', true),
  19912. output$1('streams', {
  19913. setup: setup$c,
  19914. state: throttle
  19915. })
  19916. ]
  19917. })),
  19918. defaulted('event', 'input'),
  19919. option('cancelEvent'),
  19920. onStrictHandler('onStream')
  19921. ];
  19922. var Streaming = create$7({
  19923. fields: StreamingSchema,
  19924. name: 'streaming',
  19925. active: ActiveStreaming,
  19926. state: StreamingState
  19927. });
  19928. var setValueFromItem = function (model, input, item) {
  19929. var itemData = Representing.getValue(item);
  19930. Representing.setValue(input, itemData);
  19931. setCursorAtEnd(input);
  19932. };
  19933. var setSelectionOn = function (input, f) {
  19934. var el = input.element;
  19935. var value = get$5(el);
  19936. var node = el.dom;
  19937. if (get$d(el, 'type') !== 'number') {
  19938. f(node, value);
  19939. }
  19940. };
  19941. var setCursorAtEnd = function (input) {
  19942. setSelectionOn(input, function (node, value) {
  19943. return node.setSelectionRange(value.length, value.length);
  19944. });
  19945. };
  19946. var setSelectionToEnd = function (input, startOffset) {
  19947. setSelectionOn(input, function (node, value) {
  19948. return node.setSelectionRange(startOffset, value.length);
  19949. });
  19950. };
  19951. var attemptSelectOver = function (model, input, item) {
  19952. if (!model.selectsOver) {
  19953. return Optional.none();
  19954. } else {
  19955. var currentValue = Representing.getValue(input);
  19956. var inputDisplay_1 = model.getDisplayText(currentValue);
  19957. var itemValue = Representing.getValue(item);
  19958. var itemDisplay = model.getDisplayText(itemValue);
  19959. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () {
  19960. setValueFromItem(model, input, item);
  19961. setSelectionToEnd(input, inputDisplay_1.length);
  19962. }) : Optional.none();
  19963. }
  19964. };
  19965. var itemExecute = constant$1('alloy.typeahead.itemexecute');
  19966. var make$3 = function (detail, components, spec, externals) {
  19967. var navigateList = function (comp, simulatedEvent, highlighter) {
  19968. detail.previewing.set(false);
  19969. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19970. if (Sandboxing.isOpen(sandbox)) {
  19971. Composing.getCurrent(sandbox).each(function (menu) {
  19972. Highlighting.getHighlighted(menu).fold(function () {
  19973. highlighter(menu);
  19974. }, function () {
  19975. dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent);
  19976. });
  19977. });
  19978. } else {
  19979. var onOpenSync = function (sandbox) {
  19980. Composing.getCurrent(sandbox).each(highlighter);
  19981. };
  19982. open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19983. }
  19984. };
  19985. var focusBehaviours$1 = focusBehaviours(detail);
  19986. var mapFetch = function (comp) {
  19987. return function (tdata) {
  19988. return tdata.map(function (data) {
  19989. var menus = values(data.menus);
  19990. var items = bind$3(menus, function (menu) {
  19991. return filter$2(menu.items, function (item) {
  19992. return item.type === 'item';
  19993. });
  19994. });
  19995. var repState = Representing.getState(comp);
  19996. repState.update(map$2(items, function (item) {
  19997. return item.data;
  19998. }));
  19999. return data;
  20000. });
  20001. };
  20002. };
  20003. var behaviours = [
  20004. Focusing.config({}),
  20005. Representing.config({
  20006. onSetValue: detail.onSetValue,
  20007. store: __assign({
  20008. mode: 'dataset',
  20009. getDataKey: function (comp) {
  20010. return get$5(comp.element);
  20011. },
  20012. getFallbackEntry: function (itemString) {
  20013. return {
  20014. value: itemString,
  20015. meta: {}
  20016. };
  20017. },
  20018. setValue: function (comp, data) {
  20019. set$4(comp.element, detail.model.getDisplayText(data));
  20020. }
  20021. }, detail.initialData.map(function (d) {
  20022. return wrap$1('initialValue', d);
  20023. }).getOr({}))
  20024. }),
  20025. Streaming.config({
  20026. stream: {
  20027. mode: 'throttle',
  20028. delay: detail.responseTime,
  20029. stopEvent: false
  20030. },
  20031. onStream: function (component, _simulatedEvent) {
  20032. var sandbox = Coupling.getCoupled(component, 'sandbox');
  20033. var focusInInput = Focusing.isFocused(component);
  20034. if (focusInInput) {
  20035. if (get$5(component.element).length >= detail.minChars) {
  20036. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  20037. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  20038. });
  20039. detail.previewing.set(true);
  20040. var onOpenSync = function (_sandbox) {
  20041. Composing.getCurrent(sandbox).each(function (menu) {
  20042. previousValue_1.fold(function () {
  20043. if (detail.model.selectsOver) {
  20044. Highlighting.highlightFirst(menu);
  20045. }
  20046. }, function (pv) {
  20047. Highlighting.highlightBy(menu, function (item) {
  20048. var itemData = Representing.getValue(item);
  20049. return itemData.value === pv.value;
  20050. });
  20051. Highlighting.getHighlighted(menu).orThunk(function () {
  20052. Highlighting.highlightFirst(menu);
  20053. return Optional.none();
  20054. });
  20055. });
  20056. });
  20057. };
  20058. open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  20059. }
  20060. }
  20061. },
  20062. cancelEvent: typeaheadCancel()
  20063. }),
  20064. Keying.config({
  20065. mode: 'special',
  20066. onDown: function (comp, simulatedEvent) {
  20067. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  20068. return Optional.some(true);
  20069. },
  20070. onEscape: function (comp) {
  20071. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20072. if (Sandboxing.isOpen(sandbox)) {
  20073. Sandboxing.close(sandbox);
  20074. return Optional.some(true);
  20075. }
  20076. return Optional.none();
  20077. },
  20078. onUp: function (comp, simulatedEvent) {
  20079. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  20080. return Optional.some(true);
  20081. },
  20082. onEnter: function (comp) {
  20083. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20084. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  20085. if (sandboxIsOpen && !detail.previewing.get()) {
  20086. return Composing.getCurrent(sandbox).bind(function (menu) {
  20087. return Highlighting.getHighlighted(menu);
  20088. }).map(function (item) {
  20089. emitWith(comp, itemExecute(), { item: item });
  20090. return true;
  20091. });
  20092. } else {
  20093. var currentValue = Representing.getValue(comp);
  20094. emit(comp, typeaheadCancel());
  20095. detail.onExecute(sandbox, comp, currentValue);
  20096. if (sandboxIsOpen) {
  20097. Sandboxing.close(sandbox);
  20098. }
  20099. return Optional.some(true);
  20100. }
  20101. }
  20102. }),
  20103. Toggling.config({
  20104. toggleClass: detail.markers.openClass,
  20105. aria: { mode: 'expanded' }
  20106. }),
  20107. Coupling.config({
  20108. others: {
  20109. sandbox: function (hotspot) {
  20110. return makeSandbox$1(detail, hotspot, {
  20111. onOpen: function () {
  20112. return Toggling.on(hotspot);
  20113. },
  20114. onClose: function () {
  20115. return Toggling.off(hotspot);
  20116. }
  20117. });
  20118. }
  20119. }
  20120. }),
  20121. config('typeaheadevents', [
  20122. runOnExecute$1(function (comp) {
  20123. var onOpenSync = noop;
  20124. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  20125. }),
  20126. run$1(itemExecute(), function (comp, se) {
  20127. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  20128. setValueFromItem(detail.model, comp, se.event.item);
  20129. emit(comp, typeaheadCancel());
  20130. detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp));
  20131. Sandboxing.close(sandbox);
  20132. setCursorAtEnd(comp);
  20133. })
  20134. ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function (typeahead) {
  20135. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  20136. if (search(sandbox.element).isNone()) {
  20137. Sandboxing.close(sandbox);
  20138. }
  20139. })] : []))
  20140. ];
  20141. return {
  20142. uid: detail.uid,
  20143. dom: dom(deepMerge(detail, {
  20144. inputAttributes: {
  20145. 'role': 'combobox',
  20146. 'aria-autocomplete': 'list',
  20147. 'aria-haspopup': 'true'
  20148. }
  20149. })),
  20150. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  20151. eventOrder: detail.eventOrder
  20152. };
  20153. };
  20154. var schema$g = constant$1([
  20155. option('lazySink'),
  20156. required$1('fetch'),
  20157. defaulted('minChars', 5),
  20158. defaulted('responseTime', 1000),
  20159. onHandler('onOpen'),
  20160. defaulted('getHotspot', Optional.some),
  20161. defaulted('getAnchorOverrides', constant$1({})),
  20162. defaulted('layouts', Optional.none()),
  20163. defaulted('eventOrder', {}),
  20164. defaultedObjOf('model', {}, [
  20165. defaulted('getDisplayText', function (itemData) {
  20166. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  20167. }),
  20168. defaulted('selectsOver', true),
  20169. defaulted('populateFromBrowse', true)
  20170. ]),
  20171. onHandler('onSetValue'),
  20172. onKeyboardHandler('onExecute'),
  20173. onHandler('onItemExecute'),
  20174. defaulted('inputClasses', []),
  20175. defaulted('inputAttributes', {}),
  20176. defaulted('inputStyles', {}),
  20177. defaulted('matchWidth', true),
  20178. defaulted('useMinWidth', false),
  20179. defaulted('dismissOnBlur', true),
  20180. markers$1(['openClass']),
  20181. option('initialData'),
  20182. field('typeaheadBehaviours', [
  20183. Focusing,
  20184. Representing,
  20185. Streaming,
  20186. Keying,
  20187. Toggling,
  20188. Coupling
  20189. ]),
  20190. customField('previewing', function () {
  20191. return Cell(true);
  20192. })
  20193. ].concat(schema$k()).concat(sandboxFields()));
  20194. var parts$b = constant$1([external$1({
  20195. schema: [tieredMenuMarkers()],
  20196. name: 'menu',
  20197. overrides: function (detail) {
  20198. return {
  20199. fakeFocus: true,
  20200. onHighlight: function (menu, item) {
  20201. if (!detail.previewing.get()) {
  20202. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20203. if (detail.model.populateFromBrowse) {
  20204. setValueFromItem(detail.model, input, item);
  20205. }
  20206. });
  20207. } else {
  20208. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20209. attemptSelectOver(detail.model, input, item).fold(function () {
  20210. return Highlighting.dehighlight(menu, item);
  20211. }, function (fn) {
  20212. return fn();
  20213. });
  20214. });
  20215. }
  20216. detail.previewing.set(false);
  20217. },
  20218. onExecute: function (menu, item) {
  20219. return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) {
  20220. emitWith(typeahead, itemExecute(), { item: item });
  20221. return true;
  20222. });
  20223. },
  20224. onHover: function (menu, item) {
  20225. detail.previewing.set(false);
  20226. menu.getSystem().getByUid(detail.uid).each(function (input) {
  20227. if (detail.model.populateFromBrowse) {
  20228. setValueFromItem(detail.model, input, item);
  20229. }
  20230. });
  20231. }
  20232. };
  20233. }
  20234. })]);
  20235. var Typeahead = composite({
  20236. name: 'Typeahead',
  20237. configFields: schema$g(),
  20238. partFields: parts$b(),
  20239. factory: make$3
  20240. });
  20241. var wrap = function (delegate) {
  20242. var toCached = function () {
  20243. return wrap(delegate.toCached());
  20244. };
  20245. var bindFuture = function (f) {
  20246. return wrap(delegate.bind(function (resA) {
  20247. return resA.fold(function (err) {
  20248. return Future.pure(Result.error(err));
  20249. }, function (a) {
  20250. return f(a);
  20251. });
  20252. }));
  20253. };
  20254. var bindResult = function (f) {
  20255. return wrap(delegate.map(function (resA) {
  20256. return resA.bind(f);
  20257. }));
  20258. };
  20259. var mapResult = function (f) {
  20260. return wrap(delegate.map(function (resA) {
  20261. return resA.map(f);
  20262. }));
  20263. };
  20264. var mapError = function (f) {
  20265. return wrap(delegate.map(function (resA) {
  20266. return resA.mapError(f);
  20267. }));
  20268. };
  20269. var foldResult = function (whenError, whenValue) {
  20270. return delegate.map(function (res) {
  20271. return res.fold(whenError, whenValue);
  20272. });
  20273. };
  20274. var withTimeout = function (timeout, errorThunk) {
  20275. return wrap(Future.nu(function (callback) {
  20276. var timedOut = false;
  20277. var timer = setTimeout(function () {
  20278. timedOut = true;
  20279. callback(Result.error(errorThunk()));
  20280. }, timeout);
  20281. delegate.get(function (result) {
  20282. if (!timedOut) {
  20283. clearTimeout(timer);
  20284. callback(result);
  20285. }
  20286. });
  20287. }));
  20288. };
  20289. return __assign(__assign({}, delegate), {
  20290. toCached: toCached,
  20291. bindFuture: bindFuture,
  20292. bindResult: bindResult,
  20293. mapResult: mapResult,
  20294. mapError: mapError,
  20295. foldResult: foldResult,
  20296. withTimeout: withTimeout
  20297. });
  20298. };
  20299. var nu$1 = function (worker) {
  20300. return wrap(Future.nu(worker));
  20301. };
  20302. var value = function (value) {
  20303. return wrap(Future.pure(Result.value(value)));
  20304. };
  20305. var error = function (error) {
  20306. return wrap(Future.pure(Result.error(error)));
  20307. };
  20308. var fromResult = function (result) {
  20309. return wrap(Future.pure(result));
  20310. };
  20311. var fromFuture = function (future) {
  20312. return wrap(future.map(Result.value));
  20313. };
  20314. var fromPromise = function (promise) {
  20315. return nu$1(function (completer) {
  20316. promise.then(function (value) {
  20317. completer(Result.value(value));
  20318. }, function (error) {
  20319. completer(Result.error(error));
  20320. });
  20321. });
  20322. };
  20323. var FutureResult = {
  20324. nu: nu$1,
  20325. wrap: wrap,
  20326. pure: value,
  20327. value: value,
  20328. error: error,
  20329. fromResult: fromResult,
  20330. fromFuture: fromFuture,
  20331. fromPromise: fromPromise
  20332. };
  20333. var separator$1 = { type: 'separator' };
  20334. var toMenuItem = function (target) {
  20335. return {
  20336. type: 'menuitem',
  20337. value: target.url,
  20338. text: target.title,
  20339. meta: { attach: target.attach },
  20340. onAction: noop
  20341. };
  20342. };
  20343. var staticMenuItem = function (title, url) {
  20344. return {
  20345. type: 'menuitem',
  20346. value: url,
  20347. text: title,
  20348. meta: { attach: undefined },
  20349. onAction: noop
  20350. };
  20351. };
  20352. var toMenuItems = function (targets) {
  20353. return map$2(targets, toMenuItem);
  20354. };
  20355. var filterLinkTargets = function (type, targets) {
  20356. return filter$2(targets, function (target) {
  20357. return target.type === type;
  20358. });
  20359. };
  20360. var filteredTargets = function (type, targets) {
  20361. return toMenuItems(filterLinkTargets(type, targets));
  20362. };
  20363. var headerTargets = function (linkInfo) {
  20364. return filteredTargets('header', linkInfo.targets);
  20365. };
  20366. var anchorTargets = function (linkInfo) {
  20367. return filteredTargets('anchor', linkInfo.targets);
  20368. };
  20369. var anchorTargetTop = function (linkInfo) {
  20370. return Optional.from(linkInfo.anchorTop).map(function (url) {
  20371. return staticMenuItem('<top>', url);
  20372. }).toArray();
  20373. };
  20374. var anchorTargetBottom = function (linkInfo) {
  20375. return Optional.from(linkInfo.anchorBottom).map(function (url) {
  20376. return staticMenuItem('<bottom>', url);
  20377. }).toArray();
  20378. };
  20379. var historyTargets = function (history) {
  20380. return map$2(history, function (url) {
  20381. return staticMenuItem(url, url);
  20382. });
  20383. };
  20384. var joinMenuLists = function (items) {
  20385. return foldl(items, function (a, b) {
  20386. var bothEmpty = a.length === 0 || b.length === 0;
  20387. return bothEmpty ? a.concat(b) : a.concat(separator$1, b);
  20388. }, []);
  20389. };
  20390. var filterByQuery = function (term, menuItems) {
  20391. var lowerCaseTerm = term.toLowerCase();
  20392. return filter$2(menuItems, function (item) {
  20393. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  20394. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  20395. });
  20396. };
  20397. var getItems = function (fileType, input, urlBackstage) {
  20398. var urlInputValue = Representing.getValue(input);
  20399. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  20400. var info = urlBackstage.getLinkInformation();
  20401. return info.fold(function () {
  20402. return [];
  20403. }, function (linkInfo) {
  20404. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  20405. return fileType === 'file' ? joinMenuLists([
  20406. history,
  20407. filterByQuery(term, headerTargets(linkInfo)),
  20408. filterByQuery(term, flatten([
  20409. anchorTargetTop(linkInfo),
  20410. anchorTargets(linkInfo),
  20411. anchorTargetBottom(linkInfo)
  20412. ]))
  20413. ]) : history;
  20414. });
  20415. };
  20416. var errorId = generate$6('aria-invalid');
  20417. var renderUrlInput = function (spec, backstage, urlBackstage) {
  20418. var _a;
  20419. var providersBackstage = backstage.shared.providers;
  20420. var updateHistory = function (component) {
  20421. var urlEntry = Representing.getValue(component);
  20422. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  20423. };
  20424. var pField = FormField.parts.field({
  20425. factory: Typeahead,
  20426. dismissOnBlur: true,
  20427. inputClasses: ['tox-textfield'],
  20428. sandboxClasses: ['tox-dialog__popups'],
  20429. inputAttributes: {
  20430. 'aria-errormessage': errorId,
  20431. 'type': 'url'
  20432. },
  20433. minChars: 0,
  20434. responseTime: 0,
  20435. fetch: function (input) {
  20436. var items = getItems(spec.filetype, input, urlBackstage);
  20437. var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  20438. return Future.pure(tdata);
  20439. },
  20440. getHotspot: function (comp) {
  20441. return memUrlBox.getOpt(comp);
  20442. },
  20443. onSetValue: function (comp, _newValue) {
  20444. if (comp.hasConfigured(Invalidating)) {
  20445. Invalidating.run(comp).get(noop);
  20446. }
  20447. },
  20448. typeaheadBehaviours: derive$1(flatten([
  20449. urlBackstage.getValidationHandler().map(function (handler) {
  20450. return Invalidating.config({
  20451. getRoot: function (comp) {
  20452. return parent(comp.element);
  20453. },
  20454. invalidClass: 'tox-control-wrap--status-invalid',
  20455. notify: {
  20456. onInvalid: function (comp, err) {
  20457. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  20458. set$8(invalidComp.element, 'title', providersBackstage.translate(err));
  20459. });
  20460. }
  20461. },
  20462. validator: {
  20463. validate: function (input) {
  20464. var urlEntry = Representing.getValue(input);
  20465. return FutureResult.nu(function (completer) {
  20466. handler({
  20467. type: spec.filetype,
  20468. url: urlEntry.value
  20469. }, function (validation) {
  20470. if (validation.status === 'invalid') {
  20471. var err = Result.error(validation.message);
  20472. completer(err);
  20473. } else {
  20474. var val = Result.value(validation.message);
  20475. completer(val);
  20476. }
  20477. });
  20478. });
  20479. },
  20480. validateOnLoad: false
  20481. }
  20482. });
  20483. }).toArray(),
  20484. [
  20485. Disabling.config({
  20486. disabled: function () {
  20487. return spec.disabled || providersBackstage.isDisabled();
  20488. }
  20489. }),
  20490. Tabstopping.config({}),
  20491. config('urlinput-events', flatten([
  20492. spec.filetype === 'file' ? [run$1(input(), function (comp) {
  20493. emitWith(comp, formChangeEvent, { name: spec.name });
  20494. })] : [],
  20495. [
  20496. run$1(change(), function (comp) {
  20497. emitWith(comp, formChangeEvent, { name: spec.name });
  20498. updateHistory(comp);
  20499. }),
  20500. run$1(postPaste(), function (comp) {
  20501. emitWith(comp, formChangeEvent, { name: spec.name });
  20502. updateHistory(comp);
  20503. })
  20504. ]
  20505. ]))
  20506. ]
  20507. ])),
  20508. eventOrder: (_a = {}, _a[input()] = [
  20509. 'streaming',
  20510. 'urlinput-events',
  20511. 'invalidating'
  20512. ], _a),
  20513. model: {
  20514. getDisplayText: function (itemData) {
  20515. return itemData.value;
  20516. },
  20517. selectsOver: false,
  20518. populateFromBrowse: false
  20519. },
  20520. markers: { openClass: 'tox-textfield--popup-open' },
  20521. lazySink: backstage.shared.getSink,
  20522. parts: { menu: part(false, 1, 'normal') },
  20523. onExecute: function (_menu, component, _entry) {
  20524. emitWith(component, formSubmitEvent, {});
  20525. },
  20526. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  20527. updateHistory(typeahead);
  20528. emitWith(typeahead, formChangeEvent, { name: spec.name });
  20529. }
  20530. });
  20531. var pLabel = spec.label.map(function (label) {
  20532. return renderLabel$2(label, providersBackstage);
  20533. });
  20534. var makeIcon = function (name, errId, icon, label) {
  20535. if (icon === void 0) {
  20536. icon = name;
  20537. }
  20538. if (label === void 0) {
  20539. label = name;
  20540. }
  20541. return render$3(icon, {
  20542. tag: 'div',
  20543. classes: [
  20544. 'tox-icon',
  20545. 'tox-control-wrap__status-icon-' + name
  20546. ],
  20547. attributes: __assign({
  20548. 'title': providersBackstage.translate(label),
  20549. 'aria-live': 'polite'
  20550. }, errId.fold(function () {
  20551. return {};
  20552. }, function (id) {
  20553. return { id: id };
  20554. }))
  20555. }, providersBackstage.icons);
  20556. };
  20557. var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning'));
  20558. var memStatus = record({
  20559. dom: {
  20560. tag: 'div',
  20561. classes: ['tox-control-wrap__status-icon-wrap']
  20562. },
  20563. components: [memInvalidIcon.asSpec()]
  20564. });
  20565. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  20566. var browseUrlEvent = generate$6('browser.url.event');
  20567. var memUrlBox = record({
  20568. dom: {
  20569. tag: 'div',
  20570. classes: ['tox-control-wrap']
  20571. },
  20572. components: [
  20573. pField,
  20574. memStatus.asSpec()
  20575. ],
  20576. behaviours: derive$1([Disabling.config({
  20577. disabled: function () {
  20578. return spec.disabled || providersBackstage.isDisabled();
  20579. }
  20580. })])
  20581. });
  20582. var memUrlPickerButton = record(renderButton({
  20583. name: spec.name,
  20584. icon: Optional.some('browse'),
  20585. text: spec.label.getOr(''),
  20586. disabled: spec.disabled,
  20587. primary: false,
  20588. borderless: true
  20589. }, function (component) {
  20590. return emit(component, browseUrlEvent);
  20591. }, providersBackstage, [], ['tox-browse-url']));
  20592. var controlHWrapper = function () {
  20593. return {
  20594. dom: {
  20595. tag: 'div',
  20596. classes: ['tox-form__controls-h-stack']
  20597. },
  20598. components: flatten([
  20599. [memUrlBox.asSpec()],
  20600. optUrlPicker.map(function () {
  20601. return memUrlPickerButton.asSpec();
  20602. }).toArray()
  20603. ])
  20604. };
  20605. };
  20606. var openUrlPicker = function (comp) {
  20607. Composing.getCurrent(comp).each(function (field) {
  20608. var componentData = Representing.getValue(field);
  20609. var urlData = __assign({ fieldname: spec.name }, componentData);
  20610. optUrlPicker.each(function (picker) {
  20611. picker(urlData).get(function (chosenData) {
  20612. Representing.setValue(field, chosenData);
  20613. emitWith(comp, formChangeEvent, { name: spec.name });
  20614. });
  20615. });
  20616. });
  20617. };
  20618. return FormField.sketch({
  20619. dom: renderFormFieldDom(),
  20620. components: pLabel.toArray().concat([controlHWrapper()]),
  20621. fieldBehaviours: derive$1([
  20622. Disabling.config({
  20623. disabled: function () {
  20624. return spec.disabled || providersBackstage.isDisabled();
  20625. },
  20626. onDisabled: function (comp) {
  20627. FormField.getField(comp).each(Disabling.disable);
  20628. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  20629. },
  20630. onEnabled: function (comp) {
  20631. FormField.getField(comp).each(Disabling.enable);
  20632. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  20633. }
  20634. }),
  20635. receivingConfig(),
  20636. config('url-input-events', [run$1(browseUrlEvent, openUrlPicker)])
  20637. ])
  20638. });
  20639. };
  20640. var renderAlertBanner = function (spec, providersBackstage) {
  20641. return Container.sketch({
  20642. dom: {
  20643. tag: 'div',
  20644. attributes: { role: 'alert' },
  20645. classes: [
  20646. 'tox-notification',
  20647. 'tox-notification--in',
  20648. 'tox-notification--' + spec.level
  20649. ]
  20650. },
  20651. components: [
  20652. {
  20653. dom: {
  20654. tag: 'div',
  20655. classes: ['tox-notification__icon']
  20656. },
  20657. components: [Button.sketch({
  20658. dom: {
  20659. tag: 'button',
  20660. classes: [
  20661. 'tox-button',
  20662. 'tox-button--naked',
  20663. 'tox-button--icon'
  20664. ],
  20665. innerHtml: get$1(spec.icon, providersBackstage.icons),
  20666. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  20667. },
  20668. action: function (comp) {
  20669. emitWith(comp, formActionEvent, {
  20670. name: 'alert-banner',
  20671. value: spec.url
  20672. });
  20673. },
  20674. buttonBehaviours: derive$1([addFocusableBehaviour()])
  20675. })]
  20676. },
  20677. {
  20678. dom: {
  20679. tag: 'div',
  20680. classes: ['tox-notification__body'],
  20681. innerHtml: providersBackstage.translate(spec.text)
  20682. }
  20683. }
  20684. ]
  20685. });
  20686. };
  20687. var renderCheckbox = function (spec, providerBackstage) {
  20688. var repBehaviour = Representing.config({
  20689. store: {
  20690. mode: 'manual',
  20691. getValue: function (comp) {
  20692. var el = comp.element.dom;
  20693. return el.checked;
  20694. },
  20695. setValue: function (comp, value) {
  20696. var el = comp.element.dom;
  20697. el.checked = value;
  20698. }
  20699. }
  20700. });
  20701. var toggleCheckboxHandler = function (comp) {
  20702. comp.element.dom.click();
  20703. return Optional.some(true);
  20704. };
  20705. var pField = FormField.parts.field({
  20706. factory: { sketch: identity$1 },
  20707. dom: {
  20708. tag: 'input',
  20709. classes: ['tox-checkbox__input'],
  20710. attributes: { type: 'checkbox' }
  20711. },
  20712. behaviours: derive$1([
  20713. ComposingConfigs.self(),
  20714. Disabling.config({
  20715. disabled: function () {
  20716. return spec.disabled || providerBackstage.isDisabled();
  20717. }
  20718. }),
  20719. Tabstopping.config({}),
  20720. Focusing.config({}),
  20721. repBehaviour,
  20722. Keying.config({
  20723. mode: 'special',
  20724. onEnter: toggleCheckboxHandler,
  20725. onSpace: toggleCheckboxHandler,
  20726. stopSpaceKeyup: true
  20727. }),
  20728. config('checkbox-events', [run$1(change(), function (component, _) {
  20729. emitWith(component, formChangeEvent, { name: spec.name });
  20730. })])
  20731. ])
  20732. });
  20733. var pLabel = FormField.parts.label({
  20734. dom: {
  20735. tag: 'span',
  20736. classes: ['tox-checkbox__label'],
  20737. innerHtml: providerBackstage.translate(spec.label)
  20738. },
  20739. behaviours: derive$1([Unselecting.config({})])
  20740. });
  20741. var makeIcon = function (className) {
  20742. var iconName = className === 'checked' ? 'selected' : 'unselected';
  20743. return render$3(iconName, {
  20744. tag: 'span',
  20745. classes: [
  20746. 'tox-icon',
  20747. 'tox-checkbox-icon__' + className
  20748. ]
  20749. }, providerBackstage.icons);
  20750. };
  20751. var memIcons = record({
  20752. dom: {
  20753. tag: 'div',
  20754. classes: ['tox-checkbox__icons']
  20755. },
  20756. components: [
  20757. makeIcon('checked'),
  20758. makeIcon('unchecked')
  20759. ]
  20760. });
  20761. return FormField.sketch({
  20762. dom: {
  20763. tag: 'label',
  20764. classes: ['tox-checkbox']
  20765. },
  20766. components: [
  20767. pField,
  20768. memIcons.asSpec(),
  20769. pLabel
  20770. ],
  20771. fieldBehaviours: derive$1([
  20772. Disabling.config({
  20773. disabled: function () {
  20774. return spec.disabled || providerBackstage.isDisabled();
  20775. },
  20776. disableClass: 'tox-checkbox--disabled',
  20777. onDisabled: function (comp) {
  20778. FormField.getField(comp).each(Disabling.disable);
  20779. },
  20780. onEnabled: function (comp) {
  20781. FormField.getField(comp).each(Disabling.enable);
  20782. }
  20783. }),
  20784. receivingConfig()
  20785. ])
  20786. });
  20787. };
  20788. var renderHtmlPanel = function (spec) {
  20789. if (spec.presets === 'presentation') {
  20790. return Container.sketch({
  20791. dom: {
  20792. tag: 'div',
  20793. classes: ['tox-form__group'],
  20794. innerHtml: spec.html
  20795. }
  20796. });
  20797. } else {
  20798. return Container.sketch({
  20799. dom: {
  20800. tag: 'div',
  20801. classes: ['tox-form__group'],
  20802. innerHtml: spec.html,
  20803. attributes: { role: 'document' }
  20804. },
  20805. containerBehaviours: derive$1([
  20806. Tabstopping.config({}),
  20807. Focusing.config({})
  20808. ])
  20809. });
  20810. }
  20811. };
  20812. var make$2 = function (render) {
  20813. return function (parts, spec, backstage) {
  20814. return get$e(spec, 'name').fold(function () {
  20815. return render(spec, backstage);
  20816. }, function (fieldName) {
  20817. return parts.field(fieldName, render(spec, backstage));
  20818. });
  20819. };
  20820. };
  20821. var makeIframe = function (render) {
  20822. return function (parts, spec, backstage) {
  20823. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  20824. return make$2(render)(parts, iframeSpec, backstage);
  20825. };
  20826. };
  20827. var factories = {
  20828. bar: make$2(function (spec, backstage) {
  20829. return renderBar(spec, backstage.shared);
  20830. }),
  20831. collection: make$2(function (spec, backstage) {
  20832. return renderCollection(spec, backstage.shared.providers);
  20833. }),
  20834. alertbanner: make$2(function (spec, backstage) {
  20835. return renderAlertBanner(spec, backstage.shared.providers);
  20836. }),
  20837. input: make$2(function (spec, backstage) {
  20838. return renderInput(spec, backstage.shared.providers);
  20839. }),
  20840. textarea: make$2(function (spec, backstage) {
  20841. return renderTextarea(spec, backstage.shared.providers);
  20842. }),
  20843. label: make$2(function (spec, backstage) {
  20844. return renderLabel(spec, backstage.shared);
  20845. }),
  20846. iframe: makeIframe(function (spec, backstage) {
  20847. return renderIFrame(spec, backstage.shared.providers);
  20848. }),
  20849. button: make$2(function (spec, backstage) {
  20850. return renderDialogButton(spec, backstage.shared.providers);
  20851. }),
  20852. checkbox: make$2(function (spec, backstage) {
  20853. return renderCheckbox(spec, backstage.shared.providers);
  20854. }),
  20855. colorinput: make$2(function (spec, backstage) {
  20856. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  20857. }),
  20858. colorpicker: make$2(renderColorPicker),
  20859. dropzone: make$2(function (spec, backstage) {
  20860. return renderDropZone(spec, backstage.shared.providers);
  20861. }),
  20862. grid: make$2(function (spec, backstage) {
  20863. return renderGrid(spec, backstage.shared);
  20864. }),
  20865. listbox: make$2(function (spec, backstage) {
  20866. return renderListBox(spec, backstage);
  20867. }),
  20868. selectbox: make$2(function (spec, backstage) {
  20869. return renderSelectBox(spec, backstage.shared.providers);
  20870. }),
  20871. sizeinput: make$2(function (spec, backstage) {
  20872. return renderSizeInput(spec, backstage.shared.providers);
  20873. }),
  20874. urlinput: make$2(function (spec, backstage) {
  20875. return renderUrlInput(spec, backstage, backstage.urlinput);
  20876. }),
  20877. customeditor: make$2(renderCustomEditor),
  20878. htmlpanel: make$2(renderHtmlPanel),
  20879. imagetools: make$2(function (spec, backstage) {
  20880. return renderImageTools(spec, backstage.shared.providers);
  20881. }),
  20882. table: make$2(function (spec, backstage) {
  20883. return renderTable(spec, backstage.shared.providers);
  20884. }),
  20885. panel: make$2(function (spec, backstage) {
  20886. return renderPanel(spec, backstage);
  20887. })
  20888. };
  20889. var noFormParts = {
  20890. field: function (_name, spec) {
  20891. return spec;
  20892. }
  20893. };
  20894. var interpretInForm = function (parts, spec, oldBackstage) {
  20895. var newBackstage = deepMerge(oldBackstage, {
  20896. shared: {
  20897. interpreter: function (childSpec) {
  20898. return interpretParts(parts, childSpec, newBackstage);
  20899. }
  20900. }
  20901. });
  20902. return interpretParts(parts, spec, newBackstage);
  20903. };
  20904. var interpretParts = function (parts, spec, backstage) {
  20905. return get$e(factories, spec.type).fold(function () {
  20906. console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  20907. return spec;
  20908. }, function (factory) {
  20909. return factory(parts, spec, backstage);
  20910. });
  20911. };
  20912. var interpretWithoutForm = function (spec, backstage) {
  20913. var parts = noFormParts;
  20914. return interpretParts(parts, spec, backstage);
  20915. };
  20916. var bubbleAlignments$2 = {
  20917. valignCentre: [],
  20918. alignCentre: [],
  20919. alignLeft: [],
  20920. alignRight: [],
  20921. right: [],
  20922. left: [],
  20923. bottom: [],
  20924. top: []
  20925. };
  20926. var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20927. var bubbleSize = 12;
  20928. var overrides = { maxHeightFunction: expandable$1() };
  20929. var editableAreaAnchor = function () {
  20930. return {
  20931. type: 'node',
  20932. root: getContentContainer(contentAreaElement()),
  20933. node: Optional.from(contentAreaElement()),
  20934. bubble: nu$5(bubbleSize, bubbleSize, bubbleAlignments$2),
  20935. layouts: {
  20936. onRtl: function () {
  20937. return [northeast];
  20938. },
  20939. onLtr: function () {
  20940. return [northwest];
  20941. }
  20942. },
  20943. overrides: overrides
  20944. };
  20945. };
  20946. var standardAnchor = function () {
  20947. return {
  20948. type: 'hotspot',
  20949. hotspot: lazyAnchorbar(),
  20950. bubble: nu$5(-bubbleSize, bubbleSize, bubbleAlignments$2),
  20951. layouts: {
  20952. onRtl: function () {
  20953. return [southeast$2];
  20954. },
  20955. onLtr: function () {
  20956. return [southwest$2];
  20957. }
  20958. },
  20959. overrides: overrides
  20960. };
  20961. };
  20962. return function () {
  20963. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20964. };
  20965. };
  20966. var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20967. var editableAreaAnchor = function () {
  20968. return {
  20969. type: 'node',
  20970. root: getContentContainer(contentAreaElement()),
  20971. node: Optional.from(contentAreaElement()),
  20972. layouts: {
  20973. onRtl: function () {
  20974. return [north];
  20975. },
  20976. onLtr: function () {
  20977. return [north];
  20978. }
  20979. }
  20980. };
  20981. };
  20982. var standardAnchor = function () {
  20983. return {
  20984. type: 'hotspot',
  20985. hotspot: lazyAnchorbar(),
  20986. layouts: {
  20987. onRtl: function () {
  20988. return [south$2];
  20989. },
  20990. onLtr: function () {
  20991. return [south$2];
  20992. }
  20993. }
  20994. };
  20995. };
  20996. return function () {
  20997. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20998. };
  20999. };
  21000. var getCursorAnchor = function (editor, bodyElement) {
  21001. return function () {
  21002. return {
  21003. type: 'selection',
  21004. root: bodyElement(),
  21005. getSelection: function () {
  21006. var rng = editor.selection.getRng();
  21007. return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset));
  21008. }
  21009. };
  21010. };
  21011. };
  21012. var getNodeAnchor$1 = function (bodyElement) {
  21013. return function (element) {
  21014. return {
  21015. type: 'node',
  21016. root: bodyElement(),
  21017. node: element
  21018. };
  21019. };
  21020. };
  21021. var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
  21022. var useFixedToolbarContainer = useFixedContainer(editor);
  21023. var bodyElement = function () {
  21024. return SugarElement.fromDom(editor.getBody());
  21025. };
  21026. var contentAreaElement = function () {
  21027. return SugarElement.fromDom(editor.getContentAreaContainer());
  21028. };
  21029. var lazyUseEditableAreaAnchor = function () {
  21030. return useFixedToolbarContainer || !isToolbarTop();
  21031. };
  21032. return {
  21033. inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  21034. banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  21035. cursor: getCursorAnchor(editor, bodyElement),
  21036. node: getNodeAnchor$1(bodyElement)
  21037. };
  21038. };
  21039. var colorPicker = function (editor) {
  21040. return function (callback, value) {
  21041. var dialog = colorPickerDialog(editor);
  21042. dialog(callback, value);
  21043. };
  21044. };
  21045. var hasCustomColors = function (editor) {
  21046. return function () {
  21047. return hasCustomColors$1(editor);
  21048. };
  21049. };
  21050. var getColors = function (editor) {
  21051. return function () {
  21052. return getColors$2(editor);
  21053. };
  21054. };
  21055. var getColorCols = function (editor) {
  21056. return function () {
  21057. return getColorCols$1(editor);
  21058. };
  21059. };
  21060. var ColorInputBackstage = function (editor) {
  21061. return {
  21062. colorPicker: colorPicker(editor),
  21063. hasCustomColors: hasCustomColors(editor),
  21064. getColors: getColors(editor),
  21065. getColorCols: getColorCols(editor)
  21066. };
  21067. };
  21068. var isDraggableModal = function (editor) {
  21069. return function () {
  21070. return isDraggableModal$1(editor);
  21071. };
  21072. };
  21073. var DialogBackstage = function (editor) {
  21074. return { isDraggableModal: isDraggableModal(editor) };
  21075. };
  21076. var HeaderBackstage = function (editor) {
  21077. var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  21078. return {
  21079. isPositionedAtTop: function () {
  21080. return mode.get() === 'top';
  21081. },
  21082. getDockingMode: mode.get,
  21083. setDockingMode: mode.set
  21084. };
  21085. };
  21086. var defaultStyleFormats = [
  21087. {
  21088. title: 'Headings',
  21089. items: [
  21090. {
  21091. title: 'Heading 1',
  21092. format: 'h1'
  21093. },
  21094. {
  21095. title: 'Heading 2',
  21096. format: 'h2'
  21097. },
  21098. {
  21099. title: 'Heading 3',
  21100. format: 'h3'
  21101. },
  21102. {
  21103. title: 'Heading 4',
  21104. format: 'h4'
  21105. },
  21106. {
  21107. title: 'Heading 5',
  21108. format: 'h5'
  21109. },
  21110. {
  21111. title: 'Heading 6',
  21112. format: 'h6'
  21113. }
  21114. ]
  21115. },
  21116. {
  21117. title: 'Inline',
  21118. items: [
  21119. {
  21120. title: 'Bold',
  21121. format: 'bold'
  21122. },
  21123. {
  21124. title: 'Italic',
  21125. format: 'italic'
  21126. },
  21127. {
  21128. title: 'Underline',
  21129. format: 'underline'
  21130. },
  21131. {
  21132. title: 'Strikethrough',
  21133. format: 'strikethrough'
  21134. },
  21135. {
  21136. title: 'Superscript',
  21137. format: 'superscript'
  21138. },
  21139. {
  21140. title: 'Subscript',
  21141. format: 'subscript'
  21142. },
  21143. {
  21144. title: 'Code',
  21145. format: 'code'
  21146. }
  21147. ]
  21148. },
  21149. {
  21150. title: 'Blocks',
  21151. items: [
  21152. {
  21153. title: 'Paragraph',
  21154. format: 'p'
  21155. },
  21156. {
  21157. title: 'Blockquote',
  21158. format: 'blockquote'
  21159. },
  21160. {
  21161. title: 'Div',
  21162. format: 'div'
  21163. },
  21164. {
  21165. title: 'Pre',
  21166. format: 'pre'
  21167. }
  21168. ]
  21169. },
  21170. {
  21171. title: 'Align',
  21172. items: [
  21173. {
  21174. title: 'Left',
  21175. format: 'alignleft'
  21176. },
  21177. {
  21178. title: 'Center',
  21179. format: 'aligncenter'
  21180. },
  21181. {
  21182. title: 'Right',
  21183. format: 'alignright'
  21184. },
  21185. {
  21186. title: 'Justify',
  21187. format: 'alignjustify'
  21188. }
  21189. ]
  21190. }
  21191. ];
  21192. var isNestedFormat = function (format) {
  21193. return has$2(format, 'items');
  21194. };
  21195. var isBlockFormat = function (format) {
  21196. return has$2(format, 'block');
  21197. };
  21198. var isInlineFormat = function (format) {
  21199. return has$2(format, 'inline');
  21200. };
  21201. var isSelectorFormat = function (format) {
  21202. return has$2(format, 'selector');
  21203. };
  21204. var mapFormats = function (userFormats) {
  21205. return foldl(userFormats, function (acc, fmt) {
  21206. if (isNestedFormat(fmt)) {
  21207. var result = mapFormats(fmt.items);
  21208. return {
  21209. customFormats: acc.customFormats.concat(result.customFormats),
  21210. formats: acc.formats.concat([{
  21211. title: fmt.title,
  21212. items: result.formats
  21213. }])
  21214. };
  21215. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  21216. var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase();
  21217. var formatNameWithPrefix = 'custom-' + formatName;
  21218. return {
  21219. customFormats: acc.customFormats.concat([{
  21220. name: formatNameWithPrefix,
  21221. format: fmt
  21222. }]),
  21223. formats: acc.formats.concat([{
  21224. title: fmt.title,
  21225. format: formatNameWithPrefix,
  21226. icon: fmt.icon
  21227. }])
  21228. };
  21229. } else {
  21230. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  21231. }
  21232. }, {
  21233. customFormats: [],
  21234. formats: []
  21235. });
  21236. };
  21237. var registerCustomFormats = function (editor, userFormats) {
  21238. var result = mapFormats(userFormats);
  21239. var registerFormats = function (customFormats) {
  21240. each$1(customFormats, function (fmt) {
  21241. if (!editor.formatter.has(fmt.name)) {
  21242. editor.formatter.register(fmt.name, fmt.format);
  21243. }
  21244. });
  21245. };
  21246. if (editor.formatter) {
  21247. registerFormats(result.customFormats);
  21248. } else {
  21249. editor.on('init', function () {
  21250. registerFormats(result.customFormats);
  21251. });
  21252. }
  21253. return result.formats;
  21254. };
  21255. var getStyleFormats = function (editor) {
  21256. return getUserStyleFormats(editor).map(function (userFormats) {
  21257. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  21258. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  21259. }).getOr(defaultStyleFormats);
  21260. };
  21261. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  21262. var formatterSpec = {
  21263. type: 'formatter',
  21264. isSelected: isSelectedFor(item.format),
  21265. getStylePreview: getPreviewFor(item.format)
  21266. };
  21267. return deepMerge(item, formatterSpec);
  21268. };
  21269. var register$8 = function (editor, formats, isSelectedFor, getPreviewFor) {
  21270. var enrichSupported = function (item) {
  21271. return processBasic(item, isSelectedFor, getPreviewFor);
  21272. };
  21273. var enrichMenu = function (item) {
  21274. var submenuSpec = { type: 'submenu' };
  21275. return deepMerge(item, submenuSpec);
  21276. };
  21277. var enrichCustom = function (item) {
  21278. var formatName = isString(item.name) ? item.name : generate$6(item.title);
  21279. var formatNameWithPrefix = 'custom-' + formatName;
  21280. var customSpec = {
  21281. type: 'formatter',
  21282. format: formatNameWithPrefix,
  21283. isSelected: isSelectedFor(formatNameWithPrefix),
  21284. getStylePreview: getPreviewFor(formatNameWithPrefix)
  21285. };
  21286. var newItem = deepMerge(item, customSpec);
  21287. editor.formatter.register(formatName, newItem);
  21288. return newItem;
  21289. };
  21290. var doEnrich = function (items) {
  21291. return map$2(items, function (item) {
  21292. var keys$1 = keys(item);
  21293. if (hasNonNullableKey(item, 'items')) {
  21294. var newItems = doEnrich(item.items);
  21295. return deepMerge(enrichMenu(item), { getStyleItems: constant$1(newItems) });
  21296. } else if (hasNonNullableKey(item, 'format')) {
  21297. return enrichSupported(item);
  21298. } else if (keys$1.length === 1 && contains$2(keys$1, 'title')) {
  21299. return deepMerge(item, { type: 'separator' });
  21300. } else {
  21301. return enrichCustom(item);
  21302. }
  21303. });
  21304. };
  21305. return doEnrich(formats);
  21306. };
  21307. var init$8 = function (editor) {
  21308. var isSelectedFor = function (format) {
  21309. return function () {
  21310. return editor.formatter.match(format);
  21311. };
  21312. };
  21313. var getPreviewFor = function (format) {
  21314. return function () {
  21315. var fmt = editor.formatter.get(format);
  21316. return fmt !== undefined ? Optional.some({
  21317. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  21318. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  21319. }) : Optional.none();
  21320. };
  21321. };
  21322. var flatten = function (fmt) {
  21323. var subs = fmt.items;
  21324. return subs !== undefined && subs.length > 0 ? bind$3(subs, flatten) : [fmt.format];
  21325. };
  21326. var settingsFormats = Cell([]);
  21327. var settingsFlattenedFormats = Cell([]);
  21328. var eventsFormats = Cell([]);
  21329. var eventsFlattenedFormats = Cell([]);
  21330. var replaceSettings = Cell(false);
  21331. editor.on('PreInit', function (_e) {
  21332. var formats = getStyleFormats(editor);
  21333. var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor);
  21334. settingsFormats.set(enriched);
  21335. settingsFlattenedFormats.set(bind$3(enriched, flatten));
  21336. });
  21337. editor.on('addStyleModifications', function (e) {
  21338. var modifications = register$8(editor, e.items, isSelectedFor, getPreviewFor);
  21339. eventsFormats.set(modifications);
  21340. replaceSettings.set(e.replace);
  21341. eventsFlattenedFormats.set(bind$3(modifications, flatten));
  21342. });
  21343. var getData = function () {
  21344. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  21345. var fromEvents = eventsFormats.get();
  21346. return fromSettings.concat(fromEvents);
  21347. };
  21348. var getFlattenedKeys = function () {
  21349. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  21350. var fromEvents = eventsFlattenedFormats.get();
  21351. return fromSettings.concat(fromEvents);
  21352. };
  21353. return {
  21354. getData: getData,
  21355. getFlattenedKeys: getFlattenedKeys
  21356. };
  21357. };
  21358. var isElement = function (node) {
  21359. return isNonNullable(node) && node.nodeType === 1;
  21360. };
  21361. var trim = global$5.trim;
  21362. var hasContentEditableState = function (value) {
  21363. return function (node) {
  21364. if (isElement(node)) {
  21365. if (node.contentEditable === value) {
  21366. return true;
  21367. }
  21368. if (node.getAttribute('data-mce-contenteditable') === value) {
  21369. return true;
  21370. }
  21371. }
  21372. return false;
  21373. };
  21374. };
  21375. var isContentEditableTrue = hasContentEditableState('true');
  21376. var isContentEditableFalse = hasContentEditableState('false');
  21377. var create = function (type, title, url, level, attach) {
  21378. return {
  21379. type: type,
  21380. title: title,
  21381. url: url,
  21382. level: level,
  21383. attach: attach
  21384. };
  21385. };
  21386. var isChildOfContentEditableTrue = function (node) {
  21387. while (node = node.parentNode) {
  21388. var value = node.contentEditable;
  21389. if (value && value !== 'inherit') {
  21390. return isContentEditableTrue(node);
  21391. }
  21392. }
  21393. return false;
  21394. };
  21395. var select = function (selector, root) {
  21396. return map$2(descendants(SugarElement.fromDom(root), selector), function (element) {
  21397. return element.dom;
  21398. });
  21399. };
  21400. var getElementText = function (elm) {
  21401. return elm.innerText || elm.textContent;
  21402. };
  21403. var getOrGenerateId = function (elm) {
  21404. return elm.id ? elm.id : generate$6('h');
  21405. };
  21406. var isAnchor = function (elm) {
  21407. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  21408. };
  21409. var isValidAnchor = function (elm) {
  21410. return isAnchor(elm) && isEditable(elm);
  21411. };
  21412. var isHeader = function (elm) {
  21413. return elm && /^(H[1-6])$/.test(elm.nodeName);
  21414. };
  21415. var isEditable = function (elm) {
  21416. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  21417. };
  21418. var isValidHeader = function (elm) {
  21419. return isHeader(elm) && isEditable(elm);
  21420. };
  21421. var getLevel = function (elm) {
  21422. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  21423. };
  21424. var headerTarget = function (elm) {
  21425. var headerId = getOrGenerateId(elm);
  21426. var attach = function () {
  21427. elm.id = headerId;
  21428. };
  21429. return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  21430. };
  21431. var anchorTarget = function (elm) {
  21432. var anchorId = elm.id || elm.name;
  21433. var anchorText = getElementText(elm);
  21434. return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  21435. };
  21436. var getHeaderTargets = function (elms) {
  21437. return map$2(filter$2(elms, isValidHeader), headerTarget);
  21438. };
  21439. var getAnchorTargets = function (elms) {
  21440. return map$2(filter$2(elms, isValidAnchor), anchorTarget);
  21441. };
  21442. var getTargetElements = function (elm) {
  21443. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  21444. return elms;
  21445. };
  21446. var hasTitle = function (target) {
  21447. return trim(target.title).length > 0;
  21448. };
  21449. var find = function (elm) {
  21450. var elms = getTargetElements(elm);
  21451. return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  21452. };
  21453. var LinkTargets = { find: find };
  21454. var STORAGE_KEY = 'tinymce-url-history';
  21455. var HISTORY_LENGTH = 5;
  21456. var isHttpUrl = function (url) {
  21457. return isString(url) && /^https?/.test(url);
  21458. };
  21459. var isArrayOfUrl = function (a) {
  21460. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  21461. };
  21462. var isRecordOfUrlArray = function (r) {
  21463. return isObject(r) && find$4(r, function (value) {
  21464. return !isArrayOfUrl(value);
  21465. }).isNone();
  21466. };
  21467. var getAllHistory = function () {
  21468. var unparsedHistory = global$8.getItem(STORAGE_KEY);
  21469. if (unparsedHistory === null) {
  21470. return {};
  21471. }
  21472. var history;
  21473. try {
  21474. history = JSON.parse(unparsedHistory);
  21475. } catch (e) {
  21476. if (e instanceof SyntaxError) {
  21477. console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  21478. return {};
  21479. }
  21480. throw e;
  21481. }
  21482. if (!isRecordOfUrlArray(history)) {
  21483. console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  21484. return {};
  21485. }
  21486. return history;
  21487. };
  21488. var setAllHistory = function (history) {
  21489. if (!isRecordOfUrlArray(history)) {
  21490. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  21491. }
  21492. global$8.setItem(STORAGE_KEY, JSON.stringify(history));
  21493. };
  21494. var getHistory = function (fileType) {
  21495. var history = getAllHistory();
  21496. return get$e(history, fileType).getOr([]);
  21497. };
  21498. var addToHistory = function (url, fileType) {
  21499. if (!isHttpUrl(url)) {
  21500. return;
  21501. }
  21502. var history = getAllHistory();
  21503. var items = get$e(history, fileType).getOr([]);
  21504. var itemsWithoutUrl = filter$2(items, function (item) {
  21505. return item !== url;
  21506. });
  21507. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  21508. setAllHistory(history);
  21509. };
  21510. var isTruthy = function (value) {
  21511. return !!value;
  21512. };
  21513. var makeMap = function (value) {
  21514. return map$1(global$5.makeMap(value, /[, ]/), isTruthy);
  21515. };
  21516. var getPicker = function (editor) {
  21517. return Optional.from(getFilePickerCallback(editor)).filter(isFunction);
  21518. };
  21519. var getPickerTypes = function (editor) {
  21520. var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy);
  21521. var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy);
  21522. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  21523. return getPicker(editor).fold(never, function (_picker) {
  21524. return optTypes.fold(always, function (types) {
  21525. return keys(types).length > 0 ? types : false;
  21526. });
  21527. });
  21528. };
  21529. var getPickerSetting = function (editor, filetype) {
  21530. var pickerTypes = getPickerTypes(editor);
  21531. if (isBoolean(pickerTypes)) {
  21532. return pickerTypes ? getPicker(editor) : Optional.none();
  21533. } else {
  21534. return pickerTypes[filetype] ? getPicker(editor) : Optional.none();
  21535. }
  21536. };
  21537. var getUrlPicker = function (editor, filetype) {
  21538. return getPickerSetting(editor, filetype).map(function (picker) {
  21539. return function (entry) {
  21540. return Future.nu(function (completer) {
  21541. var handler = function (value, meta) {
  21542. if (!isString(value)) {
  21543. throw new Error('Expected value to be string');
  21544. }
  21545. if (meta !== undefined && !isObject(meta)) {
  21546. throw new Error('Expected meta to be a object');
  21547. }
  21548. var r = {
  21549. value: value,
  21550. meta: meta
  21551. };
  21552. completer(r);
  21553. };
  21554. var meta = __assign({
  21555. filetype: filetype,
  21556. fieldname: entry.fieldname
  21557. }, Optional.from(entry.meta).getOr({}));
  21558. picker.call(editor, handler, entry.value, meta);
  21559. });
  21560. };
  21561. });
  21562. };
  21563. var getTextSetting = function (value) {
  21564. return Optional.from(value).filter(isString).getOrUndefined();
  21565. };
  21566. var getLinkInformation = function (editor) {
  21567. if (noTypeaheadUrls(editor)) {
  21568. return Optional.none();
  21569. }
  21570. return Optional.some({
  21571. targets: LinkTargets.find(editor.getBody()),
  21572. anchorTop: getTextSetting(getAnchorTop(editor)),
  21573. anchorBottom: getTextSetting(getAnchorBottom(editor))
  21574. });
  21575. };
  21576. var getValidationHandler = function (editor) {
  21577. return Optional.from(getFilePickerValidatorHandler(editor));
  21578. };
  21579. var UrlInputBackstage = function (editor) {
  21580. return {
  21581. getHistory: getHistory,
  21582. addToHistory: addToHistory,
  21583. getLinkInformation: function () {
  21584. return getLinkInformation(editor);
  21585. },
  21586. getValidationHandler: function () {
  21587. return getValidationHandler(editor);
  21588. },
  21589. getUrlPicker: function (filetype) {
  21590. return getUrlPicker(editor, filetype);
  21591. }
  21592. };
  21593. };
  21594. var init$7 = function (sink, editor, lazyAnchorbar) {
  21595. var contextMenuState = Cell(false);
  21596. var toolbar = HeaderBackstage(editor);
  21597. var backstage = {
  21598. shared: {
  21599. providers: {
  21600. icons: function () {
  21601. return editor.ui.registry.getAll().icons;
  21602. },
  21603. menuItems: function () {
  21604. return editor.ui.registry.getAll().menuItems;
  21605. },
  21606. translate: global$e.translate,
  21607. isDisabled: function () {
  21608. return editor.mode.isReadOnly() || editor.ui.isDisabled();
  21609. },
  21610. getSetting: editor.getParam.bind(editor)
  21611. },
  21612. interpreter: function (s) {
  21613. return interpretWithoutForm(s, backstage);
  21614. },
  21615. anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  21616. header: toolbar,
  21617. getSink: function () {
  21618. return Result.value(sink);
  21619. }
  21620. },
  21621. urlinput: UrlInputBackstage(editor),
  21622. styleselect: init$8(editor),
  21623. colorinput: ColorInputBackstage(editor),
  21624. dialog: DialogBackstage(editor),
  21625. isContextMenuOpen: function () {
  21626. return contextMenuState.get();
  21627. },
  21628. setContextMenuState: function (state) {
  21629. return contextMenuState.set(state);
  21630. }
  21631. };
  21632. return backstage;
  21633. };
  21634. var setup$b = function (editor, mothership, uiMothership) {
  21635. var broadcastEvent = function (name, evt) {
  21636. each$1([
  21637. mothership,
  21638. uiMothership
  21639. ], function (ship) {
  21640. ship.broadcastEvent(name, evt);
  21641. });
  21642. };
  21643. var broadcastOn = function (channel, message) {
  21644. each$1([
  21645. mothership,
  21646. uiMothership
  21647. ], function (ship) {
  21648. ship.broadcastOn([channel], message);
  21649. });
  21650. };
  21651. var fireDismissPopups = function (evt) {
  21652. return broadcastOn(dismissPopups(), { target: evt.target });
  21653. };
  21654. var doc = getDocument();
  21655. var onTouchstart = bind(doc, 'touchstart', fireDismissPopups);
  21656. var onTouchmove = bind(doc, 'touchmove', function (evt) {
  21657. return broadcastEvent(documentTouchmove(), evt);
  21658. });
  21659. var onTouchend = bind(doc, 'touchend', function (evt) {
  21660. return broadcastEvent(documentTouchend(), evt);
  21661. });
  21662. var onMousedown = bind(doc, 'mousedown', fireDismissPopups);
  21663. var onMouseup = bind(doc, 'mouseup', function (evt) {
  21664. if (evt.raw.button === 0) {
  21665. broadcastOn(mouseReleased(), { target: evt.target });
  21666. }
  21667. });
  21668. var onContentClick = function (raw) {
  21669. return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) });
  21670. };
  21671. var onContentMouseup = function (raw) {
  21672. if (raw.button === 0) {
  21673. broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) });
  21674. }
  21675. };
  21676. var onContentMousedown = function () {
  21677. each$1(editor.editorManager.get(), function (loopEditor) {
  21678. if (editor !== loopEditor) {
  21679. loopEditor.fire('DismissPopups', { relatedTarget: editor });
  21680. }
  21681. });
  21682. };
  21683. var onWindowScroll = function (evt) {
  21684. return broadcastEvent(windowScroll(), fromRawEvent(evt));
  21685. };
  21686. var onWindowResize = function (evt) {
  21687. broadcastOn(repositionPopups(), {});
  21688. broadcastEvent(windowResize(), fromRawEvent(evt));
  21689. };
  21690. var onEditorResize = function () {
  21691. return broadcastOn(repositionPopups(), {});
  21692. };
  21693. var onEditorProgress = function (evt) {
  21694. if (evt.state) {
  21695. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) });
  21696. }
  21697. };
  21698. var onDismissPopups = function (event) {
  21699. broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) });
  21700. };
  21701. editor.on('PostRender', function () {
  21702. editor.on('click', onContentClick);
  21703. editor.on('tap', onContentClick);
  21704. editor.on('mouseup', onContentMouseup);
  21705. editor.on('mousedown', onContentMousedown);
  21706. editor.on('ScrollWindow', onWindowScroll);
  21707. editor.on('ResizeWindow', onWindowResize);
  21708. editor.on('ResizeEditor', onEditorResize);
  21709. editor.on('AfterProgressState', onEditorProgress);
  21710. editor.on('DismissPopups', onDismissPopups);
  21711. });
  21712. editor.on('remove', function () {
  21713. editor.off('click', onContentClick);
  21714. editor.off('tap', onContentClick);
  21715. editor.off('mouseup', onContentMouseup);
  21716. editor.off('mousedown', onContentMousedown);
  21717. editor.off('ScrollWindow', onWindowScroll);
  21718. editor.off('ResizeWindow', onWindowResize);
  21719. editor.off('ResizeEditor', onEditorResize);
  21720. editor.off('AfterProgressState', onEditorProgress);
  21721. editor.off('DismissPopups', onDismissPopups);
  21722. onMousedown.unbind();
  21723. onTouchstart.unbind();
  21724. onTouchmove.unbind();
  21725. onTouchend.unbind();
  21726. onMouseup.unbind();
  21727. });
  21728. editor.on('detach', function () {
  21729. detachSystem(mothership);
  21730. detachSystem(uiMothership);
  21731. mothership.destroy();
  21732. uiMothership.destroy();
  21733. });
  21734. };
  21735. var parts$a = AlloyParts;
  21736. var partType = PartType;
  21737. var schema$f = constant$1([
  21738. defaulted('shell', false),
  21739. required$1('makeItem'),
  21740. defaulted('setupItem', noop),
  21741. SketchBehaviours.field('listBehaviours', [Replacing])
  21742. ]);
  21743. var customListDetail = function () {
  21744. return { behaviours: derive$1([Replacing.config({})]) };
  21745. };
  21746. var itemsPart = optional({
  21747. name: 'items',
  21748. overrides: customListDetail
  21749. });
  21750. var parts$9 = constant$1([itemsPart]);
  21751. var name = constant$1('CustomList');
  21752. var factory$d = function (detail, components, _spec, _external) {
  21753. var setItems = function (list, items) {
  21754. getListContainer(list).fold(function () {
  21755. console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  21756. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  21757. }, function (container) {
  21758. var itemComps = Replacing.contents(container);
  21759. var numListsRequired = items.length;
  21760. var numListsToAdd = numListsRequired - itemComps.length;
  21761. var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function () {
  21762. return detail.makeItem();
  21763. }) : [];
  21764. var itemsToRemove = itemComps.slice(numListsRequired);
  21765. each$1(itemsToRemove, function (item) {
  21766. return Replacing.remove(container, item);
  21767. });
  21768. each$1(itemsToAdd, function (item) {
  21769. return Replacing.append(container, item);
  21770. });
  21771. var builtLists = Replacing.contents(container);
  21772. each$1(builtLists, function (item, i) {
  21773. detail.setupItem(list, item, items[i], i);
  21774. });
  21775. });
  21776. };
  21777. var extra = detail.shell ? {
  21778. behaviours: [Replacing.config({})],
  21779. components: []
  21780. } : {
  21781. behaviours: [],
  21782. components: components
  21783. };
  21784. var getListContainer = function (component) {
  21785. return detail.shell ? Optional.some(component) : getPart(component, detail, 'items');
  21786. };
  21787. return {
  21788. uid: detail.uid,
  21789. dom: detail.dom,
  21790. components: extra.components,
  21791. behaviours: augment(detail.listBehaviours, extra.behaviours),
  21792. apis: { setItems: setItems }
  21793. };
  21794. };
  21795. var CustomList = composite({
  21796. name: name(),
  21797. configFields: schema$f(),
  21798. partFields: parts$9(),
  21799. factory: factory$d,
  21800. apis: {
  21801. setItems: function (apis, list, items) {
  21802. apis.setItems(list, items);
  21803. }
  21804. }
  21805. });
  21806. var schema$e = constant$1([
  21807. required$1('dom'),
  21808. defaulted('shell', true),
  21809. field('toolbarBehaviours', [Replacing])
  21810. ]);
  21811. var enhanceGroups = function () {
  21812. return { behaviours: derive$1([Replacing.config({})]) };
  21813. };
  21814. var parts$8 = constant$1([optional({
  21815. name: 'groups',
  21816. overrides: enhanceGroups
  21817. })]);
  21818. var factory$c = function (detail, components, _spec, _externals) {
  21819. var setGroups = function (toolbar, groups) {
  21820. getGroupContainer(toolbar).fold(function () {
  21821. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21822. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21823. }, function (container) {
  21824. Replacing.set(container, groups);
  21825. });
  21826. };
  21827. var getGroupContainer = function (component) {
  21828. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  21829. };
  21830. var extra = detail.shell ? {
  21831. behaviours: [Replacing.config({})],
  21832. components: []
  21833. } : {
  21834. behaviours: [],
  21835. components: components
  21836. };
  21837. return {
  21838. uid: detail.uid,
  21839. dom: detail.dom,
  21840. components: extra.components,
  21841. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  21842. apis: { setGroups: setGroups },
  21843. domModification: { attributes: { role: 'group' } }
  21844. };
  21845. };
  21846. var Toolbar = composite({
  21847. name: 'Toolbar',
  21848. configFields: schema$e(),
  21849. partFields: parts$8(),
  21850. factory: factory$c,
  21851. apis: {
  21852. setGroups: function (apis, toolbar, groups) {
  21853. apis.setGroups(toolbar, groups);
  21854. }
  21855. }
  21856. });
  21857. var setup$a = noop;
  21858. var isDocked$2 = never;
  21859. var getBehaviours$1 = constant$1([]);
  21860. var StaticHeader = /*#__PURE__*/Object.freeze({
  21861. __proto__: null,
  21862. setup: setup$a,
  21863. isDocked: isDocked$2,
  21864. getBehaviours: getBehaviours$1
  21865. });
  21866. var getOffsetParent = function (element) {
  21867. var isFixed = is$1(getRaw(element, 'position'), 'fixed');
  21868. var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element);
  21869. return offsetParent$1.orThunk(function () {
  21870. var marker = SugarElement.fromTag('span');
  21871. return parent(element).bind(function (parent) {
  21872. append$2(parent, marker);
  21873. var offsetParent$1 = offsetParent(marker);
  21874. remove$5(marker);
  21875. return offsetParent$1;
  21876. });
  21877. });
  21878. };
  21879. var getOrigin = function (element) {
  21880. return getOffsetParent(element).map(absolute$3).getOrThunk(function () {
  21881. return SugarPosition(0, 0);
  21882. });
  21883. };
  21884. var morphAdt = Adt.generate([
  21885. { static: [] },
  21886. { absolute: ['positionCss'] },
  21887. { fixed: ['positionCss'] }
  21888. ]);
  21889. var appear = function (component, contextualInfo) {
  21890. var elem = component.element;
  21891. add$2(elem, contextualInfo.transitionClass);
  21892. remove$2(elem, contextualInfo.fadeOutClass);
  21893. add$2(elem, contextualInfo.fadeInClass);
  21894. contextualInfo.onShow(component);
  21895. };
  21896. var disappear = function (component, contextualInfo) {
  21897. var elem = component.element;
  21898. add$2(elem, contextualInfo.transitionClass);
  21899. remove$2(elem, contextualInfo.fadeInClass);
  21900. add$2(elem, contextualInfo.fadeOutClass);
  21901. contextualInfo.onHide(component);
  21902. };
  21903. var isPartiallyVisible = function (box, viewport) {
  21904. return box.y < viewport.bottom && box.bottom > viewport.y;
  21905. };
  21906. var isTopCompletelyVisible = function (box, viewport) {
  21907. return box.y >= viewport.y;
  21908. };
  21909. var isBottomCompletelyVisible = function (box, viewport) {
  21910. return box.bottom <= viewport.bottom;
  21911. };
  21912. var isVisibleForModes = function (modes, box, viewport) {
  21913. return forall(modes, function (mode) {
  21914. switch (mode) {
  21915. case 'bottom':
  21916. return isBottomCompletelyVisible(box, viewport);
  21917. case 'top':
  21918. return isTopCompletelyVisible(box, viewport);
  21919. }
  21920. });
  21921. };
  21922. var getPrior = function (elem, state) {
  21923. return state.getInitialPos().map(function (pos) {
  21924. return bounds(pos.bounds.x, pos.bounds.y, get$a(elem), get$b(elem));
  21925. });
  21926. };
  21927. var storePrior = function (elem, box, state) {
  21928. state.setInitialPos({
  21929. style: getAllRaw(elem),
  21930. position: get$c(elem, 'position') || 'static',
  21931. bounds: box
  21932. });
  21933. };
  21934. var revertToOriginal = function (elem, box, state) {
  21935. return state.getInitialPos().bind(function (position) {
  21936. state.clearInitialPos();
  21937. switch (position.position) {
  21938. case 'static':
  21939. return Optional.some(morphAdt.static());
  21940. case 'absolute':
  21941. var offsetBox_1 = getOffsetParent(elem).map(box$1).getOrThunk(function () {
  21942. return box$1(body());
  21943. });
  21944. return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$e(position.style, 'left').map(function (_left) {
  21945. return box.x - offsetBox_1.x;
  21946. }), get$e(position.style, 'top').map(function (_top) {
  21947. return box.y - offsetBox_1.y;
  21948. }), get$e(position.style, 'right').map(function (_right) {
  21949. return offsetBox_1.right - box.right;
  21950. }), get$e(position.style, 'bottom').map(function (_bottom) {
  21951. return offsetBox_1.bottom - box.bottom;
  21952. }))));
  21953. default:
  21954. return Optional.none();
  21955. }
  21956. });
  21957. };
  21958. var morphToOriginal = function (elem, viewport, state) {
  21959. return getPrior(elem, state).filter(function (box) {
  21960. return isVisibleForModes(state.getModes(), box, viewport);
  21961. }).bind(function (box) {
  21962. return revertToOriginal(elem, box, state);
  21963. });
  21964. };
  21965. var morphToFixed = function (elem, viewport, state) {
  21966. var box = box$1(elem);
  21967. if (!isVisibleForModes(state.getModes(), box, viewport)) {
  21968. storePrior(elem, box, state);
  21969. var winBox = win();
  21970. var left = box.x - winBox.x;
  21971. var top_1 = viewport.y - winBox.y;
  21972. var bottom = winBox.bottom - viewport.bottom;
  21973. var isTop = box.y <= viewport.y;
  21974. 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())));
  21975. } else {
  21976. return Optional.none();
  21977. }
  21978. };
  21979. var getMorph = function (component, viewport, state) {
  21980. var elem = component.element;
  21981. var isDocked = is$1(getRaw(elem, 'position'), 'fixed');
  21982. return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  21983. };
  21984. var getMorphToOriginal = function (component, state) {
  21985. var elem = component.element;
  21986. return getPrior(elem, state).bind(function (box) {
  21987. return revertToOriginal(elem, box, state);
  21988. });
  21989. };
  21990. var morphToStatic = function (component, config, state) {
  21991. state.setDocked(false);
  21992. each$1([
  21993. 'left',
  21994. 'right',
  21995. 'top',
  21996. 'bottom',
  21997. 'position'
  21998. ], function (prop) {
  21999. return remove$6(component.element, prop);
  22000. });
  22001. config.onUndocked(component);
  22002. };
  22003. var morphToCoord = function (component, config, state, position) {
  22004. var isDocked = position.position === 'fixed';
  22005. state.setDocked(isDocked);
  22006. applyPositionCss(component.element, position);
  22007. var method = isDocked ? config.onDocked : config.onUndocked;
  22008. method(component);
  22009. };
  22010. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  22011. if (morphToDocked === void 0) {
  22012. morphToDocked = false;
  22013. }
  22014. config.contextual.each(function (contextInfo) {
  22015. contextInfo.lazyContext(component).each(function (box) {
  22016. var isVisible = isPartiallyVisible(box, viewport);
  22017. if (isVisible !== state.isVisible()) {
  22018. state.setVisible(isVisible);
  22019. if (morphToDocked && !isVisible) {
  22020. add$1(component.element, [contextInfo.fadeOutClass]);
  22021. contextInfo.onHide(component);
  22022. } else {
  22023. var method = isVisible ? appear : disappear;
  22024. method(component, contextInfo);
  22025. }
  22026. }
  22027. });
  22028. });
  22029. };
  22030. var refreshInternal = function (component, config, state) {
  22031. var viewport = config.lazyViewport(component);
  22032. var isDocked = state.isDocked();
  22033. if (isDocked) {
  22034. updateVisibility(component, config, state, viewport);
  22035. }
  22036. getMorph(component, viewport, state).each(function (morph) {
  22037. morph.fold(function () {
  22038. return morphToStatic(component, config, state);
  22039. }, function (position) {
  22040. return morphToCoord(component, config, state, position);
  22041. }, function (position) {
  22042. updateVisibility(component, config, state, viewport, true);
  22043. morphToCoord(component, config, state, position);
  22044. });
  22045. });
  22046. };
  22047. var resetInternal = function (component, config, state) {
  22048. var elem = component.element;
  22049. state.setDocked(false);
  22050. getMorphToOriginal(component, state).each(function (morph) {
  22051. morph.fold(function () {
  22052. return morphToStatic(component, config, state);
  22053. }, function (position) {
  22054. return morphToCoord(component, config, state, position);
  22055. }, noop);
  22056. });
  22057. state.setVisible(true);
  22058. config.contextual.each(function (contextInfo) {
  22059. remove$1(elem, [
  22060. contextInfo.fadeInClass,
  22061. contextInfo.fadeOutClass,
  22062. contextInfo.transitionClass
  22063. ]);
  22064. contextInfo.onShow(component);
  22065. });
  22066. refresh$4(component, config, state);
  22067. };
  22068. var refresh$4 = function (component, config, state) {
  22069. if (component.getSystem().isConnected()) {
  22070. refreshInternal(component, config, state);
  22071. }
  22072. };
  22073. var reset = function (component, config, state) {
  22074. if (state.isDocked()) {
  22075. resetInternal(component, config, state);
  22076. }
  22077. };
  22078. var isDocked$1 = function (component, config, state) {
  22079. return state.isDocked();
  22080. };
  22081. var setModes = function (component, config, state, modes) {
  22082. return state.setModes(modes);
  22083. };
  22084. var getModes = function (component, config, state) {
  22085. return state.getModes();
  22086. };
  22087. var DockingApis = /*#__PURE__*/Object.freeze({
  22088. __proto__: null,
  22089. refresh: refresh$4,
  22090. reset: reset,
  22091. isDocked: isDocked$1,
  22092. getModes: getModes,
  22093. setModes: setModes
  22094. });
  22095. var events$5 = function (dockInfo, dockState) {
  22096. return derive$2([
  22097. runOnSource(transitionend(), function (component, simulatedEvent) {
  22098. dockInfo.contextual.each(function (contextInfo) {
  22099. if (has(component.element, contextInfo.transitionClass)) {
  22100. remove$1(component.element, [
  22101. contextInfo.transitionClass,
  22102. contextInfo.fadeInClass
  22103. ]);
  22104. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  22105. notify(component);
  22106. }
  22107. simulatedEvent.stop();
  22108. });
  22109. }),
  22110. run$1(windowScroll(), function (component, _) {
  22111. refresh$4(component, dockInfo, dockState);
  22112. }),
  22113. run$1(windowResize(), function (component, _) {
  22114. reset(component, dockInfo, dockState);
  22115. })
  22116. ]);
  22117. };
  22118. var ActiveDocking = /*#__PURE__*/Object.freeze({
  22119. __proto__: null,
  22120. events: events$5
  22121. });
  22122. var DockingSchema = [
  22123. optionObjOf('contextual', [
  22124. requiredString('fadeInClass'),
  22125. requiredString('fadeOutClass'),
  22126. requiredString('transitionClass'),
  22127. requiredFunction('lazyContext'),
  22128. onHandler('onShow'),
  22129. onHandler('onShown'),
  22130. onHandler('onHide'),
  22131. onHandler('onHidden')
  22132. ]),
  22133. defaultedFunction('lazyViewport', win),
  22134. defaultedArrayOf('modes', [
  22135. 'top',
  22136. 'bottom'
  22137. ], string),
  22138. onHandler('onDocked'),
  22139. onHandler('onUndocked')
  22140. ];
  22141. var init$6 = function (spec) {
  22142. var docked = Cell(false);
  22143. var visible = Cell(true);
  22144. var initialBounds = value$1();
  22145. var modes = Cell(spec.modes);
  22146. var readState = function () {
  22147. return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
  22148. };
  22149. return nu$8({
  22150. isDocked: docked.get,
  22151. setDocked: docked.set,
  22152. getInitialPos: initialBounds.get,
  22153. setInitialPos: initialBounds.set,
  22154. clearInitialPos: initialBounds.clear,
  22155. isVisible: visible.get,
  22156. setVisible: visible.set,
  22157. getModes: modes.get,
  22158. setModes: modes.set,
  22159. readState: readState
  22160. });
  22161. };
  22162. var DockingState = /*#__PURE__*/Object.freeze({
  22163. __proto__: null,
  22164. init: init$6
  22165. });
  22166. var Docking = create$7({
  22167. fields: DockingSchema,
  22168. name: 'docking',
  22169. active: ActiveDocking,
  22170. apis: DockingApis,
  22171. state: DockingState
  22172. });
  22173. var toolbarHeightChange = constant$1(generate$6('toolbar-height-change'));
  22174. var visibility = {
  22175. fadeInClass: 'tox-editor-dock-fadein',
  22176. fadeOutClass: 'tox-editor-dock-fadeout',
  22177. transitionClass: 'tox-editor-dock-transition'
  22178. };
  22179. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  22180. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  22181. var scrollFromBehindHeader = function (e, containerHeader) {
  22182. var doc = owner$4(containerHeader);
  22183. var viewHeight = doc.dom.defaultView.innerHeight;
  22184. var scrollPos = get$9(doc);
  22185. var markerElement = SugarElement.fromDom(e.elm);
  22186. var markerPos = absolute$2(markerElement);
  22187. var markerHeight = get$b(markerElement);
  22188. var markerTop = markerPos.y;
  22189. var markerBottom = markerTop + markerHeight;
  22190. var editorHeaderPos = absolute$3(containerHeader);
  22191. var editorHeaderHeight = get$b(containerHeader);
  22192. var editorHeaderTop = editorHeaderPos.top;
  22193. var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  22194. var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2;
  22195. var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2;
  22196. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  22197. to(scrollPos.left, markerTop - editorHeaderHeight, doc);
  22198. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  22199. var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  22200. to(scrollPos.left, y, doc);
  22201. }
  22202. };
  22203. var isDockedMode = function (header, mode) {
  22204. return contains$2(Docking.getModes(header), mode);
  22205. };
  22206. var updateIframeContentFlow = function (header) {
  22207. var getOccupiedHeight = function (elm) {
  22208. return getOuter$2(elm) + (parseInt(get$c(elm, 'margin-top'), 10) || 0) + (parseInt(get$c(elm, 'margin-bottom'), 10) || 0);
  22209. };
  22210. var elm = header.element;
  22211. parent(elm).each(function (parentElem) {
  22212. var padding = 'padding-' + Docking.getModes(header)[0];
  22213. if (Docking.isDocked(header)) {
  22214. var parentWidth = get$a(parentElem);
  22215. set$7(elm, 'width', parentWidth + 'px');
  22216. set$7(parentElem, padding, getOccupiedHeight(elm) + 'px');
  22217. } else {
  22218. remove$6(elm, 'width');
  22219. remove$6(parentElem, padding);
  22220. }
  22221. });
  22222. };
  22223. var updateSinkVisibility = function (sinkElem, visible) {
  22224. if (visible) {
  22225. remove$2(sinkElem, visibility.fadeOutClass);
  22226. add$1(sinkElem, [
  22227. visibility.transitionClass,
  22228. visibility.fadeInClass
  22229. ]);
  22230. } else {
  22231. remove$2(sinkElem, visibility.fadeInClass);
  22232. add$1(sinkElem, [
  22233. visibility.fadeOutClass,
  22234. visibility.transitionClass
  22235. ]);
  22236. }
  22237. };
  22238. var updateEditorClasses = function (editor, docked) {
  22239. var editorContainer = SugarElement.fromDom(editor.getContainer());
  22240. if (docked) {
  22241. add$2(editorContainer, editorStickyOnClass);
  22242. remove$2(editorContainer, editorStickyOffClass);
  22243. } else {
  22244. add$2(editorContainer, editorStickyOffClass);
  22245. remove$2(editorContainer, editorStickyOnClass);
  22246. }
  22247. };
  22248. var restoreFocus = function (headerElem, focusedElem) {
  22249. var ownerDoc = owner$4(focusedElem);
  22250. active(ownerDoc).filter(function (activeElm) {
  22251. return !eq(focusedElem, activeElm);
  22252. }).filter(function (activeElm) {
  22253. return eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm);
  22254. }).each(function () {
  22255. return focus$3(focusedElem);
  22256. });
  22257. };
  22258. var findFocusedElem = function (rootElm, lazySink) {
  22259. return search(rootElm).orThunk(function () {
  22260. return lazySink().toOptional().bind(function (sink) {
  22261. return search(sink.element);
  22262. });
  22263. });
  22264. };
  22265. var setup$9 = function (editor, sharedBackstage, lazyHeader) {
  22266. if (!editor.inline) {
  22267. if (!sharedBackstage.header.isPositionedAtTop()) {
  22268. editor.on('ResizeEditor', function () {
  22269. lazyHeader().each(Docking.reset);
  22270. });
  22271. }
  22272. editor.on('ResizeWindow ResizeEditor', function () {
  22273. lazyHeader().each(updateIframeContentFlow);
  22274. });
  22275. editor.on('SkinLoaded', function () {
  22276. lazyHeader().each(function (comp) {
  22277. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  22278. });
  22279. });
  22280. editor.on('FullscreenStateChanged', function () {
  22281. lazyHeader().each(Docking.reset);
  22282. });
  22283. }
  22284. editor.on('AfterScrollIntoView', function (e) {
  22285. lazyHeader().each(function (header) {
  22286. Docking.refresh(header);
  22287. var headerElem = header.element;
  22288. if (isVisible(headerElem)) {
  22289. scrollFromBehindHeader(e, headerElem);
  22290. }
  22291. });
  22292. });
  22293. editor.on('PostRender', function () {
  22294. updateEditorClasses(editor, false);
  22295. });
  22296. };
  22297. var isDocked = function (lazyHeader) {
  22298. return lazyHeader().map(Docking.isDocked).getOr(false);
  22299. };
  22300. var getIframeBehaviours = function () {
  22301. var _a;
  22302. return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
  22303. };
  22304. var getBehaviours = function (editor, sharedBackstage) {
  22305. var focusedElm = value$1();
  22306. var lazySink = sharedBackstage.getSink;
  22307. var runOnSinkElement = function (f) {
  22308. lazySink().each(function (sink) {
  22309. return f(sink.element);
  22310. });
  22311. };
  22312. var onDockingSwitch = function (comp) {
  22313. if (!editor.inline) {
  22314. updateIframeContentFlow(comp);
  22315. }
  22316. updateEditorClasses(editor, Docking.isDocked(comp));
  22317. comp.getSystem().broadcastOn([repositionPopups()], {});
  22318. lazySink().each(function (sink) {
  22319. return sink.getSystem().broadcastOn([repositionPopups()], {});
  22320. });
  22321. };
  22322. var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  22323. return __spreadArray([
  22324. Focusing.config({}),
  22325. Docking.config({
  22326. contextual: __assign({
  22327. lazyContext: function (comp) {
  22328. var headerHeight = getOuter$2(comp.element);
  22329. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  22330. var box = box$1(SugarElement.fromDom(container));
  22331. var boxHeight = box.height - headerHeight;
  22332. var topBound = box.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  22333. return Optional.some(bounds(box.x, topBound, box.width, boxHeight));
  22334. },
  22335. onShow: function () {
  22336. runOnSinkElement(function (elem) {
  22337. return updateSinkVisibility(elem, true);
  22338. });
  22339. },
  22340. onShown: function (comp) {
  22341. runOnSinkElement(function (elem) {
  22342. return remove$1(elem, [
  22343. visibility.transitionClass,
  22344. visibility.fadeInClass
  22345. ]);
  22346. });
  22347. focusedElm.get().each(function (elem) {
  22348. restoreFocus(comp.element, elem);
  22349. focusedElm.clear();
  22350. });
  22351. },
  22352. onHide: function (comp) {
  22353. findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set);
  22354. runOnSinkElement(function (elem) {
  22355. return updateSinkVisibility(elem, false);
  22356. });
  22357. },
  22358. onHidden: function () {
  22359. runOnSinkElement(function (elem) {
  22360. return remove$1(elem, [visibility.transitionClass]);
  22361. });
  22362. }
  22363. }, visibility),
  22364. lazyViewport: function (comp) {
  22365. var win$1 = win();
  22366. var offset = getStickyToolbarOffset(editor);
  22367. var top = win$1.y + (isDockedMode(comp, 'top') ? offset : 0);
  22368. var height = win$1.height - (isDockedMode(comp, 'bottom') ? offset : 0);
  22369. return bounds(win$1.x, top, win$1.width, height);
  22370. },
  22371. modes: [sharedBackstage.header.getDockingMode()],
  22372. onDocked: onDockingSwitch,
  22373. onUndocked: onDockingSwitch
  22374. })
  22375. ], additionalBehaviours, true);
  22376. };
  22377. var StickyHeader = /*#__PURE__*/Object.freeze({
  22378. __proto__: null,
  22379. setup: setup$9,
  22380. isDocked: isDocked,
  22381. getBehaviours: getBehaviours
  22382. });
  22383. var renderHeader = function (spec) {
  22384. var editor = spec.editor;
  22385. var getBehaviours$2 = spec.sticky ? getBehaviours : getBehaviours$1;
  22386. return {
  22387. uid: spec.uid,
  22388. dom: spec.dom,
  22389. components: spec.components,
  22390. behaviours: derive$1(getBehaviours$2(editor, spec.sharedBackstage))
  22391. };
  22392. };
  22393. var groupToolbarButtonSchema = objOf([
  22394. requiredString('type'),
  22395. requiredOf('items', oneOf([
  22396. arrOfObj([
  22397. requiredString('name'),
  22398. requiredArrayOf('items', string)
  22399. ]),
  22400. string
  22401. ]))
  22402. ].concat(baseToolbarButtonFields));
  22403. var createGroupToolbarButton = function (spec) {
  22404. return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  22405. };
  22406. var baseMenuButtonFields = [
  22407. optionString('text'),
  22408. optionString('tooltip'),
  22409. optionString('icon'),
  22410. requiredFunction('fetch'),
  22411. defaultedFunction('onSetup', function () {
  22412. return noop;
  22413. })
  22414. ];
  22415. var MenuButtonSchema = objOf(__spreadArray([requiredString('type')], baseMenuButtonFields, true));
  22416. var createMenuButton = function (spec) {
  22417. return asRaw('menubutton', MenuButtonSchema, spec);
  22418. };
  22419. var splitButtonSchema = objOf([
  22420. requiredString('type'),
  22421. optionString('tooltip'),
  22422. optionString('icon'),
  22423. optionString('text'),
  22424. optionFunction('select'),
  22425. requiredFunction('fetch'),
  22426. defaultedFunction('onSetup', function () {
  22427. return noop;
  22428. }),
  22429. defaultedStringEnum('presets', 'normal', [
  22430. 'normal',
  22431. 'color',
  22432. 'listpreview'
  22433. ]),
  22434. defaulted('columns', 1),
  22435. requiredFunction('onAction'),
  22436. requiredFunction('onItemAction')
  22437. ]);
  22438. var createSplitButton = function (spec) {
  22439. return asRaw('SplitButton', splitButtonSchema, spec);
  22440. };
  22441. var factory$b = function (detail, spec) {
  22442. var setMenus = function (comp, menus) {
  22443. var newMenus = map$2(menus, function (m) {
  22444. var buttonSpec = {
  22445. type: 'menubutton',
  22446. text: m.text,
  22447. fetch: function (callback) {
  22448. callback(m.getItems());
  22449. }
  22450. };
  22451. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  22452. return formatError(errInfo);
  22453. }).getOrDie();
  22454. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem'));
  22455. });
  22456. Replacing.set(comp, newMenus);
  22457. };
  22458. var apis = {
  22459. focus: Keying.focusIn,
  22460. setMenus: setMenus
  22461. };
  22462. return {
  22463. uid: detail.uid,
  22464. dom: detail.dom,
  22465. components: [],
  22466. behaviours: derive$1([
  22467. Replacing.config({}),
  22468. config('menubar-events', [
  22469. runOnAttached(function (component) {
  22470. detail.onSetup(component);
  22471. }),
  22472. run$1(mouseover(), function (comp, se) {
  22473. descendant(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) {
  22474. closest$1(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) {
  22475. if (!eq(activeButton, hoveredButton)) {
  22476. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  22477. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  22478. Dropdown.expand(hoveredComp);
  22479. Dropdown.close(activeComp);
  22480. Focusing.focus(hoveredComp);
  22481. });
  22482. });
  22483. }
  22484. });
  22485. });
  22486. }),
  22487. run$1(focusShifted(), function (comp, se) {
  22488. se.event.prevFocus.bind(function (prev) {
  22489. return comp.getSystem().getByDom(prev).toOptional();
  22490. }).each(function (prev) {
  22491. se.event.newFocus.bind(function (nu) {
  22492. return comp.getSystem().getByDom(nu).toOptional();
  22493. }).each(function (nu) {
  22494. if (Dropdown.isOpen(prev)) {
  22495. Dropdown.expand(nu);
  22496. Dropdown.close(prev);
  22497. }
  22498. });
  22499. });
  22500. })
  22501. ]),
  22502. Keying.config({
  22503. mode: 'flow',
  22504. selector: '.' + 'tox-mbtn',
  22505. onEscape: function (comp) {
  22506. detail.onEscape(comp);
  22507. return Optional.some(true);
  22508. }
  22509. }),
  22510. Tabstopping.config({})
  22511. ]),
  22512. apis: apis,
  22513. domModification: { attributes: { role: 'menubar' } }
  22514. };
  22515. };
  22516. var SilverMenubar = single({
  22517. factory: factory$b,
  22518. name: 'silver.Menubar',
  22519. configFields: [
  22520. required$1('dom'),
  22521. required$1('uid'),
  22522. required$1('onEscape'),
  22523. required$1('backstage'),
  22524. defaulted('onSetup', noop)
  22525. ],
  22526. apis: {
  22527. focus: function (apis, comp) {
  22528. apis.focus(comp);
  22529. },
  22530. setMenus: function (apis, comp, menus) {
  22531. apis.setMenus(comp, menus);
  22532. }
  22533. }
  22534. });
  22535. var getAnimationRoot = function (component, slideConfig) {
  22536. return slideConfig.getAnimationRoot.fold(function () {
  22537. return component.element;
  22538. }, function (get) {
  22539. return get(component);
  22540. });
  22541. };
  22542. var getDimensionProperty = function (slideConfig) {
  22543. return slideConfig.dimension.property;
  22544. };
  22545. var getDimension = function (slideConfig, elem) {
  22546. return slideConfig.dimension.getDimension(elem);
  22547. };
  22548. var disableTransitions = function (component, slideConfig) {
  22549. var root = getAnimationRoot(component, slideConfig);
  22550. remove$1(root, [
  22551. slideConfig.shrinkingClass,
  22552. slideConfig.growingClass
  22553. ]);
  22554. };
  22555. var setShrunk = function (component, slideConfig) {
  22556. remove$2(component.element, slideConfig.openClass);
  22557. add$2(component.element, slideConfig.closedClass);
  22558. set$7(component.element, getDimensionProperty(slideConfig), '0px');
  22559. reflow(component.element);
  22560. };
  22561. var setGrown = function (component, slideConfig) {
  22562. remove$2(component.element, slideConfig.closedClass);
  22563. add$2(component.element, slideConfig.openClass);
  22564. remove$6(component.element, getDimensionProperty(slideConfig));
  22565. };
  22566. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  22567. slideState.setCollapsed();
  22568. set$7(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  22569. reflow(component.element);
  22570. disableTransitions(component, slideConfig);
  22571. setShrunk(component, slideConfig);
  22572. slideConfig.onStartShrink(component);
  22573. slideConfig.onShrunk(component);
  22574. };
  22575. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  22576. var size = calculatedSize.getOrThunk(function () {
  22577. return getDimension(slideConfig, component.element);
  22578. });
  22579. slideState.setCollapsed();
  22580. set$7(component.element, getDimensionProperty(slideConfig), size);
  22581. reflow(component.element);
  22582. var root = getAnimationRoot(component, slideConfig);
  22583. remove$2(root, slideConfig.growingClass);
  22584. add$2(root, slideConfig.shrinkingClass);
  22585. setShrunk(component, slideConfig);
  22586. slideConfig.onStartShrink(component);
  22587. };
  22588. var doStartSmartShrink = function (component, slideConfig, slideState) {
  22589. var size = getDimension(slideConfig, component.element);
  22590. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  22591. shrinker(component, slideConfig, slideState, Optional.some(size));
  22592. };
  22593. var doStartGrow = function (component, slideConfig, slideState) {
  22594. var root = getAnimationRoot(component, slideConfig);
  22595. var wasShrinking = has(root, slideConfig.shrinkingClass);
  22596. var beforeSize = getDimension(slideConfig, component.element);
  22597. setGrown(component, slideConfig);
  22598. var fullSize = getDimension(slideConfig, component.element);
  22599. var startPartialGrow = function () {
  22600. set$7(component.element, getDimensionProperty(slideConfig), beforeSize);
  22601. reflow(component.element);
  22602. };
  22603. var startCompleteGrow = function () {
  22604. setShrunk(component, slideConfig);
  22605. };
  22606. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  22607. setStartSize();
  22608. remove$2(root, slideConfig.shrinkingClass);
  22609. add$2(root, slideConfig.growingClass);
  22610. setGrown(component, slideConfig);
  22611. set$7(component.element, getDimensionProperty(slideConfig), fullSize);
  22612. slideState.setExpanded();
  22613. slideConfig.onStartGrow(component);
  22614. };
  22615. var refresh$3 = function (component, slideConfig, slideState) {
  22616. if (slideState.isExpanded()) {
  22617. remove$6(component.element, getDimensionProperty(slideConfig));
  22618. var fullSize = getDimension(slideConfig, component.element);
  22619. set$7(component.element, getDimensionProperty(slideConfig), fullSize);
  22620. }
  22621. };
  22622. var grow = function (component, slideConfig, slideState) {
  22623. if (!slideState.isExpanded()) {
  22624. doStartGrow(component, slideConfig, slideState);
  22625. }
  22626. };
  22627. var shrink = function (component, slideConfig, slideState) {
  22628. if (slideState.isExpanded()) {
  22629. doStartSmartShrink(component, slideConfig, slideState);
  22630. }
  22631. };
  22632. var immediateShrink = function (component, slideConfig, slideState) {
  22633. if (slideState.isExpanded()) {
  22634. doImmediateShrink(component, slideConfig, slideState);
  22635. }
  22636. };
  22637. var hasGrown = function (component, slideConfig, slideState) {
  22638. return slideState.isExpanded();
  22639. };
  22640. var hasShrunk = function (component, slideConfig, slideState) {
  22641. return slideState.isCollapsed();
  22642. };
  22643. var isGrowing = function (component, slideConfig, _slideState) {
  22644. var root = getAnimationRoot(component, slideConfig);
  22645. return has(root, slideConfig.growingClass) === true;
  22646. };
  22647. var isShrinking = function (component, slideConfig, _slideState) {
  22648. var root = getAnimationRoot(component, slideConfig);
  22649. return has(root, slideConfig.shrinkingClass) === true;
  22650. };
  22651. var isTransitioning = function (component, slideConfig, slideState) {
  22652. return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  22653. };
  22654. var toggleGrow = function (component, slideConfig, slideState) {
  22655. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  22656. f(component, slideConfig, slideState);
  22657. };
  22658. var SlidingApis = /*#__PURE__*/Object.freeze({
  22659. __proto__: null,
  22660. refresh: refresh$3,
  22661. grow: grow,
  22662. shrink: shrink,
  22663. immediateShrink: immediateShrink,
  22664. hasGrown: hasGrown,
  22665. hasShrunk: hasShrunk,
  22666. isGrowing: isGrowing,
  22667. isShrinking: isShrinking,
  22668. isTransitioning: isTransitioning,
  22669. toggleGrow: toggleGrow,
  22670. disableTransitions: disableTransitions
  22671. });
  22672. var exhibit = function (base, slideConfig, _slideState) {
  22673. var expanded = slideConfig.expanded;
  22674. return expanded ? nu$7({
  22675. classes: [slideConfig.openClass],
  22676. styles: {}
  22677. }) : nu$7({
  22678. classes: [slideConfig.closedClass],
  22679. styles: wrap$1(slideConfig.dimension.property, '0px')
  22680. });
  22681. };
  22682. var events$4 = function (slideConfig, slideState) {
  22683. return derive$2([runOnSource(transitionend(), function (component, simulatedEvent) {
  22684. var raw = simulatedEvent.event.raw;
  22685. if (raw.propertyName === slideConfig.dimension.property) {
  22686. disableTransitions(component, slideConfig);
  22687. if (slideState.isExpanded()) {
  22688. remove$6(component.element, slideConfig.dimension.property);
  22689. }
  22690. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  22691. notify(component);
  22692. }
  22693. })]);
  22694. };
  22695. var ActiveSliding = /*#__PURE__*/Object.freeze({
  22696. __proto__: null,
  22697. exhibit: exhibit,
  22698. events: events$4
  22699. });
  22700. var SlidingSchema = [
  22701. required$1('closedClass'),
  22702. required$1('openClass'),
  22703. required$1('shrinkingClass'),
  22704. required$1('growingClass'),
  22705. option('getAnimationRoot'),
  22706. onHandler('onShrunk'),
  22707. onHandler('onStartShrink'),
  22708. onHandler('onGrown'),
  22709. onHandler('onStartGrow'),
  22710. defaulted('expanded', false),
  22711. requiredOf('dimension', choose$1('property', {
  22712. width: [
  22713. output$1('property', 'width'),
  22714. output$1('getDimension', function (elem) {
  22715. return get$a(elem) + 'px';
  22716. })
  22717. ],
  22718. height: [
  22719. output$1('property', 'height'),
  22720. output$1('getDimension', function (elem) {
  22721. return get$b(elem) + 'px';
  22722. })
  22723. ]
  22724. }))
  22725. ];
  22726. var init$5 = function (spec) {
  22727. var state = Cell(spec.expanded);
  22728. var readState = function () {
  22729. return 'expanded: ' + state.get();
  22730. };
  22731. return nu$8({
  22732. isExpanded: function () {
  22733. return state.get() === true;
  22734. },
  22735. isCollapsed: function () {
  22736. return state.get() === false;
  22737. },
  22738. setCollapsed: curry(state.set, false),
  22739. setExpanded: curry(state.set, true),
  22740. readState: readState
  22741. });
  22742. };
  22743. var SlidingState = /*#__PURE__*/Object.freeze({
  22744. __proto__: null,
  22745. init: init$5
  22746. });
  22747. var Sliding = create$7({
  22748. fields: SlidingSchema,
  22749. name: 'sliding',
  22750. active: ActiveSliding,
  22751. apis: SlidingApis,
  22752. state: SlidingState
  22753. });
  22754. var owner = 'container';
  22755. var schema$d = [field('slotBehaviours', [])];
  22756. var getPartName = function (name) {
  22757. return '<alloy.field.' + name + '>';
  22758. };
  22759. var sketch = function (sSpec) {
  22760. var parts = function () {
  22761. var record = [];
  22762. var slot = function (name, config) {
  22763. record.push(name);
  22764. return generateOne$1(owner, getPartName(name), config);
  22765. };
  22766. return {
  22767. slot: slot,
  22768. record: constant$1(record)
  22769. };
  22770. }();
  22771. var spec = sSpec(parts);
  22772. var partNames = parts.record();
  22773. var fieldParts = map$2(partNames, function (n) {
  22774. return required({
  22775. name: n,
  22776. pname: getPartName(n)
  22777. });
  22778. });
  22779. return composite$1(owner, schema$d, fieldParts, make$1, spec);
  22780. };
  22781. var make$1 = function (detail, components) {
  22782. var getSlotNames = function (_) {
  22783. return getAllPartNames(detail);
  22784. };
  22785. var getSlot = function (container, key) {
  22786. return getPart(container, detail, key);
  22787. };
  22788. var onSlot = function (f, def) {
  22789. return function (container, key) {
  22790. return getPart(container, detail, key).map(function (slot) {
  22791. return f(slot, key);
  22792. }).getOr(def);
  22793. };
  22794. };
  22795. var onSlots = function (f) {
  22796. return function (container, keys) {
  22797. each$1(keys, function (key) {
  22798. return f(container, key);
  22799. });
  22800. };
  22801. };
  22802. var doShowing = function (comp, _key) {
  22803. return get$d(comp.element, 'aria-hidden') !== 'true';
  22804. };
  22805. var doShow = function (comp, key) {
  22806. if (!doShowing(comp)) {
  22807. var element = comp.element;
  22808. remove$6(element, 'display');
  22809. remove$7(element, 'aria-hidden');
  22810. emitWith(comp, slotVisibility(), {
  22811. name: key,
  22812. visible: true
  22813. });
  22814. }
  22815. };
  22816. var doHide = function (comp, key) {
  22817. if (doShowing(comp)) {
  22818. var element = comp.element;
  22819. set$7(element, 'display', 'none');
  22820. set$8(element, 'aria-hidden', 'true');
  22821. emitWith(comp, slotVisibility(), {
  22822. name: key,
  22823. visible: false
  22824. });
  22825. }
  22826. };
  22827. var isShowing = onSlot(doShowing, false);
  22828. var hideSlot = onSlot(doHide);
  22829. var hideSlots = onSlots(hideSlot);
  22830. var hideAllSlots = function (container) {
  22831. return hideSlots(container, getSlotNames());
  22832. };
  22833. var showSlot = onSlot(doShow);
  22834. var apis = {
  22835. getSlotNames: getSlotNames,
  22836. getSlot: getSlot,
  22837. isShowing: isShowing,
  22838. hideSlot: hideSlot,
  22839. hideAllSlots: hideAllSlots,
  22840. showSlot: showSlot
  22841. };
  22842. return {
  22843. uid: detail.uid,
  22844. dom: detail.dom,
  22845. components: components,
  22846. behaviours: get$2(detail.slotBehaviours),
  22847. apis: apis
  22848. };
  22849. };
  22850. var slotApis = map$1({
  22851. getSlotNames: function (apis, c) {
  22852. return apis.getSlotNames(c);
  22853. },
  22854. getSlot: function (apis, c, key) {
  22855. return apis.getSlot(c, key);
  22856. },
  22857. isShowing: function (apis, c, key) {
  22858. return apis.isShowing(c, key);
  22859. },
  22860. hideSlot: function (apis, c, key) {
  22861. return apis.hideSlot(c, key);
  22862. },
  22863. hideAllSlots: function (apis, c) {
  22864. return apis.hideAllSlots(c);
  22865. },
  22866. showSlot: function (apis, c, key) {
  22867. return apis.showSlot(c, key);
  22868. }
  22869. }, function (value) {
  22870. return makeApi(value);
  22871. });
  22872. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch });
  22873. var sidebarSchema = objOf([
  22874. optionString('icon'),
  22875. optionString('tooltip'),
  22876. defaultedFunction('onShow', noop),
  22877. defaultedFunction('onHide', noop),
  22878. defaultedFunction('onSetup', function () {
  22879. return noop;
  22880. })
  22881. ]);
  22882. var createSidebar = function (spec) {
  22883. return asRaw('sidebar', sidebarSchema, spec);
  22884. };
  22885. var setup$8 = function (editor) {
  22886. var sidebars = editor.ui.registry.getAll().sidebars;
  22887. each$1(keys(sidebars), function (name) {
  22888. var spec = sidebars[name];
  22889. var isActive = function () {
  22890. return is$1(Optional.from(editor.queryCommandValue('ToggleSidebar')), name);
  22891. };
  22892. editor.ui.registry.addToggleButton(name, {
  22893. icon: spec.icon,
  22894. tooltip: spec.tooltip,
  22895. onAction: function (buttonApi) {
  22896. editor.execCommand('ToggleSidebar', false, name);
  22897. buttonApi.setActive(isActive());
  22898. },
  22899. onSetup: function (buttonApi) {
  22900. var handleToggle = function () {
  22901. return buttonApi.setActive(isActive());
  22902. };
  22903. editor.on('ToggleSidebar', handleToggle);
  22904. return function () {
  22905. editor.off('ToggleSidebar', handleToggle);
  22906. };
  22907. }
  22908. });
  22909. });
  22910. };
  22911. var getApi = function (comp) {
  22912. return {
  22913. element: function () {
  22914. return comp.element.dom;
  22915. }
  22916. };
  22917. };
  22918. var makePanels = function (parts, panelConfigs) {
  22919. var specs = map$2(keys(panelConfigs), function (name) {
  22920. var spec = panelConfigs[name];
  22921. var bridged = getOrDie(createSidebar(spec));
  22922. return {
  22923. name: name,
  22924. getApi: getApi,
  22925. onSetup: bridged.onSetup,
  22926. onShow: bridged.onShow,
  22927. onHide: bridged.onHide
  22928. };
  22929. });
  22930. return map$2(specs, function (spec) {
  22931. var editorOffCell = Cell(noop);
  22932. return parts.slot(spec.name, {
  22933. dom: {
  22934. tag: 'div',
  22935. classes: ['tox-sidebar__pane']
  22936. },
  22937. behaviours: SimpleBehaviours.unnamedEvents([
  22938. onControlAttached(spec, editorOffCell),
  22939. onControlDetached(spec, editorOffCell),
  22940. run$1(slotVisibility(), function (sidepanel, se) {
  22941. var data = se.event;
  22942. var optSidePanelSpec = find$5(specs, function (config) {
  22943. return config.name === data.name;
  22944. });
  22945. optSidePanelSpec.each(function (sidePanelSpec) {
  22946. var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  22947. handler(sidePanelSpec.getApi(sidepanel));
  22948. });
  22949. })
  22950. ])
  22951. });
  22952. });
  22953. };
  22954. var makeSidebar = function (panelConfigs) {
  22955. return SlotContainer.sketch(function (parts) {
  22956. return {
  22957. dom: {
  22958. tag: 'div',
  22959. classes: ['tox-sidebar__pane-container']
  22960. },
  22961. components: makePanels(parts, panelConfigs),
  22962. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  22963. return SlotContainer.hideAllSlots(slotContainer);
  22964. })])
  22965. };
  22966. });
  22967. };
  22968. var setSidebar = function (sidebar, panelConfigs) {
  22969. var optSlider = Composing.getCurrent(sidebar);
  22970. optSlider.each(function (slider) {
  22971. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  22972. });
  22973. };
  22974. var toggleSidebar = function (sidebar, name) {
  22975. var optSlider = Composing.getCurrent(sidebar);
  22976. optSlider.each(function (slider) {
  22977. var optSlotContainer = Composing.getCurrent(slider);
  22978. optSlotContainer.each(function (slotContainer) {
  22979. if (Sliding.hasGrown(slider)) {
  22980. if (SlotContainer.isShowing(slotContainer, name)) {
  22981. Sliding.shrink(slider);
  22982. } else {
  22983. SlotContainer.hideAllSlots(slotContainer);
  22984. SlotContainer.showSlot(slotContainer, name);
  22985. }
  22986. } else {
  22987. SlotContainer.hideAllSlots(slotContainer);
  22988. SlotContainer.showSlot(slotContainer, name);
  22989. Sliding.grow(slider);
  22990. }
  22991. });
  22992. });
  22993. };
  22994. var whichSidebar = function (sidebar) {
  22995. var optSlider = Composing.getCurrent(sidebar);
  22996. return optSlider.bind(function (slider) {
  22997. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  22998. if (sidebarOpen) {
  22999. var optSlotContainer = Composing.getCurrent(slider);
  23000. return optSlotContainer.bind(function (slotContainer) {
  23001. return find$5(SlotContainer.getSlotNames(slotContainer), function (name) {
  23002. return SlotContainer.isShowing(slotContainer, name);
  23003. });
  23004. });
  23005. } else {
  23006. return Optional.none();
  23007. }
  23008. });
  23009. };
  23010. var fixSize = generate$6('FixSizeEvent');
  23011. var autoSize = generate$6('AutoSizeEvent');
  23012. var renderSidebar = function (spec) {
  23013. return {
  23014. uid: spec.uid,
  23015. dom: {
  23016. tag: 'div',
  23017. classes: ['tox-sidebar'],
  23018. attributes: { role: 'complementary' }
  23019. },
  23020. components: [{
  23021. dom: {
  23022. tag: 'div',
  23023. classes: ['tox-sidebar__slider']
  23024. },
  23025. components: [],
  23026. behaviours: derive$1([
  23027. Tabstopping.config({}),
  23028. Focusing.config({}),
  23029. Sliding.config({
  23030. dimension: { property: 'width' },
  23031. closedClass: 'tox-sidebar--sliding-closed',
  23032. openClass: 'tox-sidebar--sliding-open',
  23033. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  23034. growingClass: 'tox-sidebar--sliding-growing',
  23035. onShrunk: function (slider) {
  23036. var optSlotContainer = Composing.getCurrent(slider);
  23037. optSlotContainer.each(SlotContainer.hideAllSlots);
  23038. emit(slider, autoSize);
  23039. },
  23040. onGrown: function (slider) {
  23041. emit(slider, autoSize);
  23042. },
  23043. onStartGrow: function (slider) {
  23044. emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') });
  23045. },
  23046. onStartShrink: function (slider) {
  23047. emitWith(slider, fixSize, { width: get$a(slider.element) + 'px' });
  23048. }
  23049. }),
  23050. Replacing.config({}),
  23051. Composing.config({
  23052. find: function (comp) {
  23053. var children = Replacing.contents(comp);
  23054. return head(children);
  23055. }
  23056. })
  23057. ])
  23058. }],
  23059. behaviours: derive$1([
  23060. ComposingConfigs.childAt(0),
  23061. config('sidebar-sliding-events', [
  23062. run$1(fixSize, function (comp, se) {
  23063. set$7(comp.element, 'width', se.event.width);
  23064. }),
  23065. run$1(autoSize, function (comp, _se) {
  23066. remove$6(comp.element, 'width');
  23067. })
  23068. ])
  23069. ])
  23070. };
  23071. };
  23072. var block = function (component, config, state, getBusySpec) {
  23073. set$8(component.element, 'aria-busy', true);
  23074. var root = config.getRoot(component).getOr(component);
  23075. var blockerBehaviours = derive$1([
  23076. Keying.config({
  23077. mode: 'special',
  23078. onTab: function () {
  23079. return Optional.some(true);
  23080. },
  23081. onShiftTab: function () {
  23082. return Optional.some(true);
  23083. }
  23084. }),
  23085. Focusing.config({})
  23086. ]);
  23087. var blockSpec = getBusySpec(root, blockerBehaviours);
  23088. var blocker = root.getSystem().build(blockSpec);
  23089. Replacing.append(root, premade(blocker));
  23090. if (blocker.hasConfigured(Keying) && config.focus) {
  23091. Keying.focusIn(blocker);
  23092. }
  23093. if (!state.isBlocked()) {
  23094. config.onBlock(component);
  23095. }
  23096. state.blockWith(function () {
  23097. return Replacing.remove(root, blocker);
  23098. });
  23099. };
  23100. var unblock = function (component, config, state) {
  23101. remove$7(component.element, 'aria-busy');
  23102. if (state.isBlocked()) {
  23103. config.onUnblock(component);
  23104. }
  23105. state.clear();
  23106. };
  23107. var BlockingApis = /*#__PURE__*/Object.freeze({
  23108. __proto__: null,
  23109. block: block,
  23110. unblock: unblock
  23111. });
  23112. var BlockingSchema = [
  23113. defaultedFunction('getRoot', Optional.none),
  23114. defaultedBoolean('focus', true),
  23115. onHandler('onBlock'),
  23116. onHandler('onUnblock')
  23117. ];
  23118. var init$4 = function () {
  23119. var blocker = destroyable();
  23120. var blockWith = function (destroy) {
  23121. blocker.set({ destroy: destroy });
  23122. };
  23123. return nu$8({
  23124. readState: blocker.isSet,
  23125. blockWith: blockWith,
  23126. clear: blocker.clear,
  23127. isBlocked: blocker.isSet
  23128. });
  23129. };
  23130. var BlockingState = /*#__PURE__*/Object.freeze({
  23131. __proto__: null,
  23132. init: init$4
  23133. });
  23134. var Blocking = create$7({
  23135. fields: BlockingSchema,
  23136. name: 'blocking',
  23137. apis: BlockingApis,
  23138. state: BlockingState
  23139. });
  23140. var getAttrs = function (elem) {
  23141. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  23142. return foldl(attributes, function (b, attr) {
  23143. var _a;
  23144. if (attr.name === 'class') {
  23145. return b;
  23146. } else {
  23147. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  23148. }
  23149. }, {});
  23150. };
  23151. var getClasses = function (elem) {
  23152. return Array.prototype.slice.call(elem.dom.classList, 0);
  23153. };
  23154. var fromHtml = function (html) {
  23155. var elem = SugarElement.fromHtml(html);
  23156. var children$1 = children(elem);
  23157. var attrs = getAttrs(elem);
  23158. var classes = getClasses(elem);
  23159. var contents = children$1.length === 0 ? {} : { innerHtml: get$7(elem) };
  23160. return __assign({
  23161. tag: name$2(elem),
  23162. classes: classes,
  23163. attributes: attrs
  23164. }, contents);
  23165. };
  23166. var getBusySpec$1 = function (providerBackstage) {
  23167. return function (_root, _behaviours) {
  23168. return {
  23169. dom: {
  23170. tag: 'div',
  23171. attributes: {
  23172. 'aria-label': providerBackstage.translate('Loading...'),
  23173. 'tabindex': '0'
  23174. },
  23175. classes: ['tox-throbber__busy-spinner']
  23176. },
  23177. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  23178. };
  23179. };
  23180. };
  23181. var focusBusyComponent = function (throbber) {
  23182. return Composing.getCurrent(throbber).each(function (comp) {
  23183. return focus$3(comp.element);
  23184. });
  23185. };
  23186. var toggleEditorTabIndex = function (editor, state) {
  23187. var tabIndexAttr = 'tabindex';
  23188. var dataTabIndexAttr = 'data-mce-' + tabIndexAttr;
  23189. Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function (iframe) {
  23190. if (state) {
  23191. getOpt(iframe, tabIndexAttr).each(function (tabIndex) {
  23192. return set$8(iframe, dataTabIndexAttr, tabIndex);
  23193. });
  23194. set$8(iframe, tabIndexAttr, -1);
  23195. } else {
  23196. remove$7(iframe, tabIndexAttr);
  23197. getOpt(iframe, dataTabIndexAttr).each(function (tabIndex) {
  23198. set$8(iframe, tabIndexAttr, tabIndex);
  23199. remove$7(iframe, dataTabIndexAttr);
  23200. });
  23201. }
  23202. });
  23203. };
  23204. var toggleThrobber = function (editor, comp, state, providerBackstage) {
  23205. var element = comp.element;
  23206. toggleEditorTabIndex(editor, state);
  23207. if (state) {
  23208. Blocking.block(comp, getBusySpec$1(providerBackstage));
  23209. remove$6(element, 'display');
  23210. remove$7(element, 'aria-hidden');
  23211. if (editor.hasFocus()) {
  23212. focusBusyComponent(comp);
  23213. }
  23214. } else {
  23215. var throbberFocus = Composing.getCurrent(comp).exists(function (busyComp) {
  23216. return hasFocus(busyComp.element);
  23217. });
  23218. Blocking.unblock(comp);
  23219. set$7(element, 'display', 'none');
  23220. set$8(element, 'aria-hidden', 'true');
  23221. if (throbberFocus) {
  23222. editor.focus();
  23223. }
  23224. }
  23225. };
  23226. var renderThrobber = function (spec) {
  23227. return {
  23228. uid: spec.uid,
  23229. dom: {
  23230. tag: 'div',
  23231. attributes: { 'aria-hidden': 'true' },
  23232. classes: ['tox-throbber'],
  23233. styles: { display: 'none' }
  23234. },
  23235. behaviours: derive$1([
  23236. Replacing.config({}),
  23237. Blocking.config({ focus: false }),
  23238. Composing.config({
  23239. find: function (comp) {
  23240. return head(comp.components());
  23241. }
  23242. })
  23243. ]),
  23244. components: []
  23245. };
  23246. };
  23247. var isFocusEvent = function (event) {
  23248. return event.type === 'focusin';
  23249. };
  23250. var isPasteBinTarget = function (event) {
  23251. if (isFocusEvent(event)) {
  23252. var node = event.composed ? head(event.composedPath()) : Optional.from(event.target);
  23253. return node.map(SugarElement.fromDom).filter(isElement$2).exists(function (targetElm) {
  23254. return has(targetElm, 'mce-pastebin');
  23255. });
  23256. } else {
  23257. return false;
  23258. }
  23259. };
  23260. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  23261. var throbberState = Cell(false);
  23262. var timer = value$1();
  23263. var stealFocus = function (e) {
  23264. if (throbberState.get() && !isPasteBinTarget(e)) {
  23265. e.preventDefault();
  23266. focusBusyComponent(lazyThrobber());
  23267. editor.editorManager.setActive(editor);
  23268. }
  23269. };
  23270. if (!editor.inline) {
  23271. editor.on('PreInit', function () {
  23272. editor.dom.bind(editor.getWin(), 'focusin', stealFocus);
  23273. editor.on('BeforeExecCommand', function (e) {
  23274. if (e.command.toLowerCase() === 'mcefocus' && e.value !== true) {
  23275. stealFocus(e);
  23276. }
  23277. });
  23278. });
  23279. }
  23280. var toggle = function (state) {
  23281. if (state !== throbberState.get()) {
  23282. throbberState.set(state);
  23283. toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers);
  23284. editor.fire('AfterProgressState', { state: state });
  23285. }
  23286. };
  23287. editor.on('ProgressState', function (e) {
  23288. timer.on(global$f.clearTimeout);
  23289. if (isNumber(e.time)) {
  23290. var timerId = global$f.setEditorTimeout(editor, function () {
  23291. return toggle(e.state);
  23292. }, e.time);
  23293. timer.set(timerId);
  23294. } else {
  23295. toggle(e.state);
  23296. timer.clear();
  23297. }
  23298. });
  23299. };
  23300. var generate$1 = function (xs, f) {
  23301. var init = {
  23302. len: 0,
  23303. list: []
  23304. };
  23305. var r = foldl(xs, function (b, a) {
  23306. var value = f(a, b.len);
  23307. return value.fold(constant$1(b), function (v) {
  23308. return {
  23309. len: v.finish,
  23310. list: b.list.concat([v])
  23311. };
  23312. });
  23313. }, init);
  23314. return r.list;
  23315. };
  23316. var output = function (within, extra, withinWidth) {
  23317. return {
  23318. within: within,
  23319. extra: extra,
  23320. withinWidth: withinWidth
  23321. };
  23322. };
  23323. var apportion = function (units, total, len) {
  23324. var parray = generate$1(units, function (unit, current) {
  23325. var width = len(unit);
  23326. return Optional.some({
  23327. element: unit,
  23328. start: current,
  23329. finish: current + width,
  23330. width: width
  23331. });
  23332. });
  23333. var within = filter$2(parray, function (unit) {
  23334. return unit.finish <= total;
  23335. });
  23336. var withinWidth = foldr(within, function (acc, el) {
  23337. return acc + el.width;
  23338. }, 0);
  23339. var extra = parray.slice(within.length);
  23340. return {
  23341. within: within,
  23342. extra: extra,
  23343. withinWidth: withinWidth
  23344. };
  23345. };
  23346. var toUnit = function (parray) {
  23347. return map$2(parray, function (unit) {
  23348. return unit.element;
  23349. });
  23350. };
  23351. var fitLast = function (within, extra, withinWidth) {
  23352. var fits = toUnit(within.concat(extra));
  23353. return output(fits, [], withinWidth);
  23354. };
  23355. var overflow = function (within, extra, overflower, withinWidth) {
  23356. var fits = toUnit(within).concat([overflower]);
  23357. return output(fits, toUnit(extra), withinWidth);
  23358. };
  23359. var fitAll = function (within, extra, withinWidth) {
  23360. return output(toUnit(within), [], withinWidth);
  23361. };
  23362. var tryFit = function (total, units, len) {
  23363. var divide = apportion(units, total, len);
  23364. return divide.extra.length === 0 ? Optional.some(divide) : Optional.none();
  23365. };
  23366. var partition = function (total, units, len, overflower) {
  23367. var divide = tryFit(total, units, len).getOrThunk(function () {
  23368. return apportion(units, total - len(overflower), len);
  23369. });
  23370. var within = divide.within;
  23371. var extra = divide.extra;
  23372. var withinWidth = divide.withinWidth;
  23373. if (extra.length === 1 && extra[0].width <= len(overflower)) {
  23374. return fitLast(within, extra, withinWidth);
  23375. } else if (extra.length >= 1) {
  23376. return overflow(within, extra, overflower, withinWidth);
  23377. } else {
  23378. return fitAll(within, extra, withinWidth);
  23379. }
  23380. };
  23381. var setGroups$1 = function (toolbar, storedGroups) {
  23382. var bGroups = map$2(storedGroups, function (g) {
  23383. return premade(g);
  23384. });
  23385. Toolbar.setGroups(toolbar, bGroups);
  23386. };
  23387. var findFocusedComp = function (comps) {
  23388. return findMap(comps, function (comp) {
  23389. return search(comp.element).bind(function (focusedElm) {
  23390. return comp.getSystem().getByDom(focusedElm).toOptional();
  23391. });
  23392. });
  23393. };
  23394. var refresh$2 = function (toolbar, detail, setOverflow) {
  23395. var builtGroups = detail.builtGroups.get();
  23396. if (builtGroups.length === 0) {
  23397. return;
  23398. }
  23399. var primary = getPartOrDie(toolbar, detail, 'primary');
  23400. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  23401. set$7(primary.element, 'visibility', 'hidden');
  23402. var groups = builtGroups.concat([overflowGroup]);
  23403. var focusedComp = findFocusedComp(groups);
  23404. setOverflow([]);
  23405. setGroups$1(primary, groups);
  23406. var availableWidth = get$a(primary.element);
  23407. var overflows = partition(availableWidth, detail.builtGroups.get(), function (comp) {
  23408. return get$a(comp.element);
  23409. }, overflowGroup);
  23410. if (overflows.extra.length === 0) {
  23411. Replacing.remove(primary, overflowGroup);
  23412. setOverflow([]);
  23413. } else {
  23414. setGroups$1(primary, overflows.within);
  23415. setOverflow(overflows.extra);
  23416. }
  23417. remove$6(primary.element, 'visibility');
  23418. reflow(primary.element);
  23419. focusedComp.each(Focusing.focus);
  23420. };
  23421. var schema$c = constant$1([
  23422. field('splitToolbarBehaviours', [Coupling]),
  23423. customField('builtGroups', function () {
  23424. return Cell([]);
  23425. })
  23426. ]);
  23427. var schema$b = constant$1([
  23428. markers$1(['overflowToggledClass']),
  23429. optionFunction('getOverflowBounds'),
  23430. required$1('lazySink'),
  23431. customField('overflowGroups', function () {
  23432. return Cell([]);
  23433. })
  23434. ].concat(schema$c()));
  23435. var parts$7 = constant$1([
  23436. required({
  23437. factory: Toolbar,
  23438. schema: schema$e(),
  23439. name: 'primary'
  23440. }),
  23441. external$1({
  23442. schema: schema$e(),
  23443. name: 'overflow'
  23444. }),
  23445. external$1({ name: 'overflow-button' }),
  23446. external$1({ name: 'overflow-group' })
  23447. ]);
  23448. var expandable = constant$1(function (element, available) {
  23449. setMax(element, Math.floor(available));
  23450. });
  23451. var schema$a = constant$1([
  23452. markers$1(['toggledClass']),
  23453. required$1('lazySink'),
  23454. requiredFunction('fetch'),
  23455. optionFunction('getBounds'),
  23456. optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]),
  23457. schema$y()
  23458. ]);
  23459. var parts$6 = constant$1([
  23460. external$1({
  23461. name: 'button',
  23462. overrides: function (detail) {
  23463. return {
  23464. dom: { attributes: { 'aria-haspopup': 'true' } },
  23465. buttonBehaviours: derive$1([Toggling.config({
  23466. toggleClass: detail.markers.toggledClass,
  23467. aria: { mode: 'expanded' },
  23468. toggleOnExecute: false
  23469. })])
  23470. };
  23471. }
  23472. }),
  23473. external$1({
  23474. factory: Toolbar,
  23475. schema: schema$e(),
  23476. name: 'toolbar',
  23477. overrides: function (detail) {
  23478. return {
  23479. toolbarBehaviours: derive$1([Keying.config({
  23480. mode: 'cyclic',
  23481. onEscape: function (comp) {
  23482. getPart(comp, detail, 'button').each(Focusing.focus);
  23483. return Optional.none();
  23484. }
  23485. })])
  23486. };
  23487. }
  23488. })
  23489. ]);
  23490. var toggle = function (button, externals) {
  23491. var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  23492. if (Sandboxing.isOpen(toolbarSandbox)) {
  23493. Sandboxing.close(toolbarSandbox);
  23494. } else {
  23495. Sandboxing.open(toolbarSandbox, externals.toolbar());
  23496. }
  23497. };
  23498. var position = function (button, toolbar, detail, layouts) {
  23499. var bounds = detail.getBounds.map(function (bounder) {
  23500. return bounder();
  23501. });
  23502. var sink = detail.lazySink(button).getOrDie();
  23503. Positioning.positionWithinBounds(sink, toolbar, {
  23504. anchor: {
  23505. type: 'hotspot',
  23506. hotspot: button,
  23507. layouts: layouts,
  23508. overrides: { maxWidthFunction: expandable() }
  23509. }
  23510. }, bounds);
  23511. };
  23512. var setGroups = function (button, toolbar, detail, layouts, groups) {
  23513. Toolbar.setGroups(toolbar, groups);
  23514. position(button, toolbar, detail, layouts);
  23515. Toggling.on(button);
  23516. };
  23517. var makeSandbox = function (button, spec, detail) {
  23518. var ariaOwner = manager();
  23519. var onOpen = function (sandbox, toolbar) {
  23520. detail.fetch().get(function (groups) {
  23521. setGroups(button, toolbar, detail, spec.layouts, groups);
  23522. ariaOwner.link(button.element);
  23523. Keying.focusIn(toolbar);
  23524. });
  23525. };
  23526. var onClose = function () {
  23527. Toggling.off(button);
  23528. Focusing.focus(button);
  23529. ariaOwner.unlink(button.element);
  23530. };
  23531. return {
  23532. dom: {
  23533. tag: 'div',
  23534. attributes: { id: ariaOwner.id }
  23535. },
  23536. behaviours: derive$1([
  23537. Keying.config({
  23538. mode: 'special',
  23539. onEscape: function (comp) {
  23540. Sandboxing.close(comp);
  23541. return Optional.some(true);
  23542. }
  23543. }),
  23544. Sandboxing.config({
  23545. onOpen: onOpen,
  23546. onClose: onClose,
  23547. isPartOf: function (container, data, queryElem) {
  23548. return isPartOf$1(data, queryElem) || isPartOf$1(button, queryElem);
  23549. },
  23550. getAttachPoint: function () {
  23551. return detail.lazySink(button).getOrDie();
  23552. }
  23553. }),
  23554. Receiving.config({
  23555. channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
  23556. return { fireEventInstead: { event: fe.event } };
  23557. }).getOr({})))), receivingChannel({
  23558. doReposition: function () {
  23559. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23560. position(button, toolbar, detail, spec.layouts);
  23561. });
  23562. }
  23563. }))
  23564. })
  23565. ])
  23566. };
  23567. };
  23568. var factory$a = function (detail, components, spec, externals) {
  23569. return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  23570. action: function (button) {
  23571. toggle(button, externals);
  23572. },
  23573. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  23574. others: {
  23575. toolbarSandbox: function (button) {
  23576. return makeSandbox(button, spec, detail);
  23577. }
  23578. }
  23579. })])
  23580. }))), {
  23581. apis: {
  23582. setGroups: function (button, groups) {
  23583. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23584. setGroups(button, toolbar, detail, spec.layouts, groups);
  23585. });
  23586. },
  23587. reposition: function (button) {
  23588. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  23589. position(button, toolbar, detail, spec.layouts);
  23590. });
  23591. },
  23592. toggle: function (button) {
  23593. toggle(button, externals);
  23594. },
  23595. getToolbar: function (button) {
  23596. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  23597. },
  23598. isOpen: function (button) {
  23599. return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox'));
  23600. }
  23601. }
  23602. });
  23603. };
  23604. var FloatingToolbarButton = composite({
  23605. name: 'FloatingToolbarButton',
  23606. factory: factory$a,
  23607. configFields: schema$a(),
  23608. partFields: parts$6(),
  23609. apis: {
  23610. setGroups: function (apis, button, groups) {
  23611. apis.setGroups(button, groups);
  23612. },
  23613. reposition: function (apis, button) {
  23614. apis.reposition(button);
  23615. },
  23616. toggle: function (apis, button) {
  23617. apis.toggle(button);
  23618. },
  23619. getToolbar: function (apis, button) {
  23620. return apis.getToolbar(button);
  23621. },
  23622. isOpen: function (apis, button) {
  23623. return apis.isOpen(button);
  23624. }
  23625. }
  23626. });
  23627. var schema$9 = constant$1([
  23628. required$1('items'),
  23629. markers$1(['itemSelector']),
  23630. field('tgroupBehaviours', [Keying])
  23631. ]);
  23632. var parts$5 = constant$1([group({
  23633. name: 'items',
  23634. unit: 'item'
  23635. })]);
  23636. var factory$9 = function (detail, components, _spec, _externals) {
  23637. return {
  23638. uid: detail.uid,
  23639. dom: detail.dom,
  23640. components: components,
  23641. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  23642. mode: 'flow',
  23643. selector: detail.markers.itemSelector
  23644. })]),
  23645. domModification: { attributes: { role: 'toolbar' } }
  23646. };
  23647. };
  23648. var ToolbarGroup = composite({
  23649. name: 'ToolbarGroup',
  23650. configFields: schema$9(),
  23651. partFields: parts$5(),
  23652. factory: factory$9
  23653. });
  23654. var buildGroups = function (comps) {
  23655. return map$2(comps, function (g) {
  23656. return premade(g);
  23657. });
  23658. };
  23659. var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  23660. refresh$2(toolbar, detail, function (overflowGroups) {
  23661. detail.overflowGroups.set(overflowGroups);
  23662. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  23663. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  23664. });
  23665. });
  23666. };
  23667. var factory$8 = function (detail, components, spec, externals) {
  23668. var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  23669. fetch: function () {
  23670. return Future.nu(function (resolve) {
  23671. resolve(buildGroups(detail.overflowGroups.get()));
  23672. });
  23673. },
  23674. layouts: {
  23675. onLtr: function () {
  23676. return [
  23677. southwest$2,
  23678. southeast$2
  23679. ];
  23680. },
  23681. onRtl: function () {
  23682. return [
  23683. southeast$2,
  23684. southwest$2
  23685. ];
  23686. },
  23687. onBottomLtr: function () {
  23688. return [
  23689. northwest$2,
  23690. northeast$2
  23691. ];
  23692. },
  23693. onBottomRtl: function () {
  23694. return [
  23695. northeast$2,
  23696. northwest$2
  23697. ];
  23698. }
  23699. },
  23700. getBounds: spec.getOverflowBounds,
  23701. lazySink: detail.lazySink,
  23702. fireDismissalEventInstead: {},
  23703. markers: { toggledClass: detail.markers.overflowToggledClass },
  23704. parts: {
  23705. button: externals['overflow-button'](),
  23706. toolbar: externals.overflow()
  23707. }
  23708. }));
  23709. return {
  23710. uid: detail.uid,
  23711. dom: detail.dom,
  23712. components: components,
  23713. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  23714. others: {
  23715. overflowGroup: function () {
  23716. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  23717. }
  23718. }
  23719. })]),
  23720. apis: {
  23721. setGroups: function (toolbar, groups) {
  23722. detail.builtGroups.set(map$2(groups, toolbar.getSystem().build));
  23723. refresh$1(toolbar, memFloatingToolbarButton, detail);
  23724. },
  23725. refresh: function (toolbar) {
  23726. return refresh$1(toolbar, memFloatingToolbarButton, detail);
  23727. },
  23728. toggle: function (toolbar) {
  23729. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  23730. FloatingToolbarButton.toggle(floatingToolbarButton);
  23731. });
  23732. },
  23733. isOpen: function (toolbar) {
  23734. return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false);
  23735. },
  23736. reposition: function (toolbar) {
  23737. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  23738. FloatingToolbarButton.reposition(floatingToolbarButton);
  23739. });
  23740. },
  23741. getOverflow: function (toolbar) {
  23742. return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar);
  23743. }
  23744. },
  23745. domModification: { attributes: { role: 'group' } }
  23746. };
  23747. };
  23748. var SplitFloatingToolbar = composite({
  23749. name: 'SplitFloatingToolbar',
  23750. configFields: schema$b(),
  23751. partFields: parts$7(),
  23752. factory: factory$8,
  23753. apis: {
  23754. setGroups: function (apis, toolbar, groups) {
  23755. apis.setGroups(toolbar, groups);
  23756. },
  23757. refresh: function (apis, toolbar) {
  23758. apis.refresh(toolbar);
  23759. },
  23760. reposition: function (apis, toolbar) {
  23761. apis.reposition(toolbar);
  23762. },
  23763. toggle: function (apis, toolbar) {
  23764. apis.toggle(toolbar);
  23765. },
  23766. isOpen: function (apis, toolbar) {
  23767. return apis.isOpen(toolbar);
  23768. },
  23769. getOverflow: function (apis, toolbar) {
  23770. return apis.getOverflow(toolbar);
  23771. }
  23772. }
  23773. });
  23774. var schema$8 = constant$1([
  23775. markers$1([
  23776. 'closedClass',
  23777. 'openClass',
  23778. 'shrinkingClass',
  23779. 'growingClass',
  23780. 'overflowToggledClass'
  23781. ]),
  23782. onHandler('onOpened'),
  23783. onHandler('onClosed')
  23784. ].concat(schema$c()));
  23785. var parts$4 = constant$1([
  23786. required({
  23787. factory: Toolbar,
  23788. schema: schema$e(),
  23789. name: 'primary'
  23790. }),
  23791. required({
  23792. factory: Toolbar,
  23793. schema: schema$e(),
  23794. name: 'overflow',
  23795. overrides: function (detail) {
  23796. return {
  23797. toolbarBehaviours: derive$1([
  23798. Sliding.config({
  23799. dimension: { property: 'height' },
  23800. closedClass: detail.markers.closedClass,
  23801. openClass: detail.markers.openClass,
  23802. shrinkingClass: detail.markers.shrinkingClass,
  23803. growingClass: detail.markers.growingClass,
  23804. onShrunk: function (comp) {
  23805. getPart(comp, detail, 'overflow-button').each(function (button) {
  23806. Toggling.off(button);
  23807. Focusing.focus(button);
  23808. });
  23809. detail.onClosed(comp);
  23810. },
  23811. onGrown: function (comp) {
  23812. Keying.focusIn(comp);
  23813. detail.onOpened(comp);
  23814. },
  23815. onStartGrow: function (comp) {
  23816. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  23817. }
  23818. }),
  23819. Keying.config({
  23820. mode: 'acyclic',
  23821. onEscape: function (comp) {
  23822. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  23823. return Optional.some(true);
  23824. }
  23825. })
  23826. ])
  23827. };
  23828. }
  23829. }),
  23830. external$1({
  23831. name: 'overflow-button',
  23832. overrides: function (detail) {
  23833. return {
  23834. buttonBehaviours: derive$1([Toggling.config({
  23835. toggleClass: detail.markers.overflowToggledClass,
  23836. aria: { mode: 'pressed' },
  23837. toggleOnExecute: false
  23838. })])
  23839. };
  23840. }
  23841. }),
  23842. external$1({ name: 'overflow-group' })
  23843. ]);
  23844. var isOpen = function (toolbar, detail) {
  23845. return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false);
  23846. };
  23847. var toggleToolbar = function (toolbar, detail) {
  23848. getPart(toolbar, detail, 'overflow-button').bind(function () {
  23849. return getPart(toolbar, detail, 'overflow');
  23850. }).each(function (overf) {
  23851. refresh(toolbar, detail);
  23852. Sliding.toggleGrow(overf);
  23853. });
  23854. };
  23855. var refresh = function (toolbar, detail) {
  23856. getPart(toolbar, detail, 'overflow').each(function (overflow) {
  23857. refresh$2(toolbar, detail, function (groups) {
  23858. var builtGroups = map$2(groups, function (g) {
  23859. return premade(g);
  23860. });
  23861. Toolbar.setGroups(overflow, builtGroups);
  23862. });
  23863. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  23864. if (Sliding.hasGrown(overflow)) {
  23865. Toggling.on(button);
  23866. }
  23867. });
  23868. Sliding.refresh(overflow);
  23869. });
  23870. };
  23871. var factory$7 = function (detail, components, spec, externals) {
  23872. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  23873. var doSetGroups = function (toolbar, groups) {
  23874. var built = map$2(groups, toolbar.getSystem().build);
  23875. detail.builtGroups.set(built);
  23876. };
  23877. return {
  23878. uid: detail.uid,
  23879. dom: detail.dom,
  23880. components: components,
  23881. behaviours: augment(detail.splitToolbarBehaviours, [
  23882. Coupling.config({
  23883. others: {
  23884. overflowGroup: function (toolbar) {
  23885. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  23886. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  23887. action: function (_button) {
  23888. emit(toolbar, toolbarToggleEvent);
  23889. }
  23890. }))]
  23891. }));
  23892. }
  23893. }
  23894. }),
  23895. config('toolbar-toggle-events', [run$1(toolbarToggleEvent, function (toolbar) {
  23896. toggleToolbar(toolbar, detail);
  23897. })])
  23898. ]),
  23899. apis: {
  23900. setGroups: function (toolbar, groups) {
  23901. doSetGroups(toolbar, groups);
  23902. refresh(toolbar, detail);
  23903. },
  23904. refresh: function (toolbar) {
  23905. return refresh(toolbar, detail);
  23906. },
  23907. toggle: function (toolbar) {
  23908. return toggleToolbar(toolbar, detail);
  23909. },
  23910. isOpen: function (toolbar) {
  23911. return isOpen(toolbar, detail);
  23912. }
  23913. },
  23914. domModification: { attributes: { role: 'group' } }
  23915. };
  23916. };
  23917. var SplitSlidingToolbar = composite({
  23918. name: 'SplitSlidingToolbar',
  23919. configFields: schema$8(),
  23920. partFields: parts$4(),
  23921. factory: factory$7,
  23922. apis: {
  23923. setGroups: function (apis, toolbar, groups) {
  23924. apis.setGroups(toolbar, groups);
  23925. },
  23926. refresh: function (apis, toolbar) {
  23927. apis.refresh(toolbar);
  23928. },
  23929. toggle: function (apis, toolbar) {
  23930. apis.toggle(toolbar);
  23931. },
  23932. isOpen: function (apis, toolbar) {
  23933. return apis.isOpen(toolbar);
  23934. }
  23935. }
  23936. });
  23937. var renderToolbarGroupCommon = function (toolbarGroup) {
  23938. var attributes = toolbarGroup.title.fold(function () {
  23939. return {};
  23940. }, function (title) {
  23941. return { attributes: { title: title } };
  23942. });
  23943. return {
  23944. dom: __assign({
  23945. tag: 'div',
  23946. classes: ['tox-toolbar__group']
  23947. }, attributes),
  23948. components: [ToolbarGroup.parts.items({})],
  23949. items: toolbarGroup.items,
  23950. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  23951. tgroupBehaviours: derive$1([
  23952. Tabstopping.config({}),
  23953. Focusing.config({})
  23954. ])
  23955. };
  23956. };
  23957. var renderToolbarGroup = function (toolbarGroup) {
  23958. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  23959. };
  23960. var getToolbarbehaviours = function (toolbarSpec, modeName) {
  23961. var onAttached = runOnAttached(function (component) {
  23962. var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup);
  23963. Toolbar.setGroups(component, groups);
  23964. });
  23965. return derive$1([
  23966. DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled),
  23967. receivingConfig(),
  23968. Keying.config({
  23969. mode: modeName,
  23970. onEscape: toolbarSpec.onEscape,
  23971. selector: '.tox-toolbar__group'
  23972. }),
  23973. config('toolbar-events', [onAttached])
  23974. ]);
  23975. };
  23976. var renderMoreToolbarCommon = function (toolbarSpec) {
  23977. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  23978. return {
  23979. uid: toolbarSpec.uid,
  23980. dom: {
  23981. tag: 'div',
  23982. classes: ['tox-toolbar-overlord']
  23983. },
  23984. parts: {
  23985. 'overflow-group': renderToolbarGroupCommon({
  23986. title: Optional.none(),
  23987. items: []
  23988. }),
  23989. 'overflow-button': renderIconButtonSpec({
  23990. name: 'more',
  23991. icon: Optional.some('more-drawer'),
  23992. disabled: false,
  23993. tooltip: Optional.some('More...'),
  23994. primary: false,
  23995. borderless: false
  23996. }, Optional.none(), toolbarSpec.providers)
  23997. },
  23998. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  23999. };
  24000. };
  24001. var renderFloatingMoreToolbar = function (toolbarSpec) {
  24002. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  24003. var overflowXOffset = 4;
  24004. var primary = SplitFloatingToolbar.parts.primary({
  24005. dom: {
  24006. tag: 'div',
  24007. classes: ['tox-toolbar__primary']
  24008. }
  24009. });
  24010. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  24011. lazySink: toolbarSpec.getSink,
  24012. getOverflowBounds: function () {
  24013. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element;
  24014. var headerBounds = absolute$2(headerElem);
  24015. var docElem = documentElement(headerElem);
  24016. var docBounds = absolute$2(docElem);
  24017. var height = Math.max(docElem.dom.scrollHeight, docBounds.height);
  24018. return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  24019. },
  24020. parts: __assign(__assign({}, baseSpec.parts), {
  24021. overflow: {
  24022. dom: {
  24023. tag: 'div',
  24024. classes: ['tox-toolbar__overflow'],
  24025. attributes: toolbarSpec.attributes
  24026. }
  24027. }
  24028. }),
  24029. components: [primary],
  24030. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  24031. }));
  24032. };
  24033. var renderSlidingMoreToolbar = function (toolbarSpec) {
  24034. var primary = SplitSlidingToolbar.parts.primary({
  24035. dom: {
  24036. tag: 'div',
  24037. classes: ['tox-toolbar__primary']
  24038. }
  24039. });
  24040. var overflow = SplitSlidingToolbar.parts.overflow({
  24041. dom: {
  24042. tag: 'div',
  24043. classes: ['tox-toolbar__overflow']
  24044. }
  24045. });
  24046. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  24047. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  24048. components: [
  24049. primary,
  24050. overflow
  24051. ],
  24052. markers: {
  24053. openClass: 'tox-toolbar__overflow--open',
  24054. closedClass: 'tox-toolbar__overflow--closed',
  24055. growingClass: 'tox-toolbar__overflow--growing',
  24056. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  24057. overflowToggledClass: 'tox-tbtn--enabled'
  24058. },
  24059. onOpened: function (comp) {
  24060. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  24061. },
  24062. onClosed: function (comp) {
  24063. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  24064. }
  24065. }));
  24066. };
  24067. var renderToolbar = function (toolbarSpec) {
  24068. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  24069. return Toolbar.sketch({
  24070. uid: toolbarSpec.uid,
  24071. dom: {
  24072. tag: 'div',
  24073. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  24074. },
  24075. components: [Toolbar.parts.groups({})],
  24076. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  24077. });
  24078. };
  24079. var factory$6 = function (detail, components, _spec) {
  24080. var apis = {
  24081. getSocket: function (comp) {
  24082. return parts$a.getPart(comp, detail, 'socket');
  24083. },
  24084. setSidebar: function (comp, panelConfigs) {
  24085. parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  24086. return setSidebar(sidebar, panelConfigs);
  24087. });
  24088. },
  24089. toggleSidebar: function (comp, name) {
  24090. parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  24091. return toggleSidebar(sidebar, name);
  24092. });
  24093. },
  24094. whichSidebar: function (comp) {
  24095. return parts$a.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  24096. },
  24097. getHeader: function (comp) {
  24098. return parts$a.getPart(comp, detail, 'header');
  24099. },
  24100. getToolbar: function (comp) {
  24101. return parts$a.getPart(comp, detail, 'toolbar');
  24102. },
  24103. setToolbar: function (comp, groups) {
  24104. parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  24105. toolbar.getApis().setGroups(toolbar, groups);
  24106. });
  24107. },
  24108. setToolbars: function (comp, toolbars) {
  24109. parts$a.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  24110. CustomList.setItems(mToolbar, toolbars);
  24111. });
  24112. },
  24113. refreshToolbar: function (comp) {
  24114. var toolbar = parts$a.getPart(comp, detail, 'toolbar');
  24115. toolbar.each(function (toolbar) {
  24116. return toolbar.getApis().refresh(toolbar);
  24117. });
  24118. },
  24119. toggleToolbarDrawer: function (comp) {
  24120. parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  24121. mapFrom(toolbar.getApis().toggle, function (toggle) {
  24122. return toggle(toolbar);
  24123. });
  24124. });
  24125. },
  24126. isToolbarDrawerToggled: function (comp) {
  24127. return parts$a.getPart(comp, detail, 'toolbar').bind(function (toolbar) {
  24128. return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) {
  24129. return isOpen(toolbar);
  24130. });
  24131. }).getOr(false);
  24132. },
  24133. getThrobber: function (comp) {
  24134. return parts$a.getPart(comp, detail, 'throbber');
  24135. },
  24136. focusToolbar: function (comp) {
  24137. var optToolbar = parts$a.getPart(comp, detail, 'toolbar').orThunk(function () {
  24138. return parts$a.getPart(comp, detail, 'multiple-toolbar');
  24139. });
  24140. optToolbar.each(function (toolbar) {
  24141. Keying.focusIn(toolbar);
  24142. });
  24143. },
  24144. setMenubar: function (comp, menus) {
  24145. parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  24146. SilverMenubar.setMenus(menubar, menus);
  24147. });
  24148. },
  24149. focusMenubar: function (comp) {
  24150. parts$a.getPart(comp, detail, 'menubar').each(function (menubar) {
  24151. SilverMenubar.focus(menubar);
  24152. });
  24153. }
  24154. };
  24155. return {
  24156. uid: detail.uid,
  24157. dom: detail.dom,
  24158. components: components,
  24159. apis: apis,
  24160. behaviours: detail.behaviours
  24161. };
  24162. };
  24163. var partMenubar = partType.optional({
  24164. factory: SilverMenubar,
  24165. name: 'menubar',
  24166. schema: [required$1('backstage')]
  24167. });
  24168. var toolbarFactory = function (spec) {
  24169. if (spec.type === ToolbarMode.sliding) {
  24170. return renderSlidingMoreToolbar;
  24171. } else if (spec.type === ToolbarMode.floating) {
  24172. return renderFloatingMoreToolbar;
  24173. } else {
  24174. return renderToolbar;
  24175. }
  24176. };
  24177. var partMultipleToolbar = partType.optional({
  24178. factory: {
  24179. sketch: function (spec) {
  24180. return CustomList.sketch({
  24181. uid: spec.uid,
  24182. dom: spec.dom,
  24183. listBehaviours: derive$1([Keying.config({
  24184. mode: 'acyclic',
  24185. selector: '.tox-toolbar'
  24186. })]),
  24187. makeItem: function () {
  24188. return renderToolbar({
  24189. type: spec.type,
  24190. uid: generate$6('multiple-toolbar-item'),
  24191. cyclicKeying: false,
  24192. initGroups: [],
  24193. providers: spec.providers,
  24194. onEscape: function () {
  24195. spec.onEscape();
  24196. return Optional.some(true);
  24197. }
  24198. });
  24199. },
  24200. setupItem: function (_mToolbar, tc, data, _index) {
  24201. Toolbar.setGroups(tc, data);
  24202. },
  24203. shell: true
  24204. });
  24205. }
  24206. },
  24207. name: 'multiple-toolbar',
  24208. schema: [
  24209. required$1('dom'),
  24210. required$1('onEscape')
  24211. ]
  24212. });
  24213. var partToolbar = partType.optional({
  24214. factory: {
  24215. sketch: function (spec) {
  24216. var renderer = toolbarFactory(spec);
  24217. var toolbarSpec = {
  24218. type: spec.type,
  24219. uid: spec.uid,
  24220. onEscape: function () {
  24221. spec.onEscape();
  24222. return Optional.some(true);
  24223. },
  24224. cyclicKeying: false,
  24225. initGroups: [],
  24226. getSink: spec.getSink,
  24227. providers: spec.providers,
  24228. moreDrawerData: {
  24229. lazyToolbar: spec.lazyToolbar,
  24230. lazyMoreButton: spec.lazyMoreButton,
  24231. lazyHeader: spec.lazyHeader
  24232. },
  24233. attributes: spec.attributes
  24234. };
  24235. return renderer(toolbarSpec);
  24236. }
  24237. },
  24238. name: 'toolbar',
  24239. schema: [
  24240. required$1('dom'),
  24241. required$1('onEscape'),
  24242. required$1('getSink')
  24243. ]
  24244. });
  24245. var partHeader = partType.optional({
  24246. factory: { sketch: renderHeader },
  24247. name: 'header',
  24248. schema: [required$1('dom')]
  24249. });
  24250. var partSocket = partType.optional({
  24251. name: 'socket',
  24252. schema: [required$1('dom')]
  24253. });
  24254. var partSidebar = partType.optional({
  24255. factory: { sketch: renderSidebar },
  24256. name: 'sidebar',
  24257. schema: [required$1('dom')]
  24258. });
  24259. var partThrobber = partType.optional({
  24260. factory: { sketch: renderThrobber },
  24261. name: 'throbber',
  24262. schema: [required$1('dom')]
  24263. });
  24264. var OuterContainer = composite({
  24265. name: 'OuterContainer',
  24266. factory: factory$6,
  24267. configFields: [
  24268. required$1('dom'),
  24269. required$1('behaviours')
  24270. ],
  24271. partFields: [
  24272. partHeader,
  24273. partMenubar,
  24274. partToolbar,
  24275. partMultipleToolbar,
  24276. partSocket,
  24277. partSidebar,
  24278. partThrobber
  24279. ],
  24280. apis: {
  24281. getSocket: function (apis, comp) {
  24282. return apis.getSocket(comp);
  24283. },
  24284. setSidebar: function (apis, comp, panelConfigs) {
  24285. apis.setSidebar(comp, panelConfigs);
  24286. },
  24287. toggleSidebar: function (apis, comp, name) {
  24288. apis.toggleSidebar(comp, name);
  24289. },
  24290. whichSidebar: function (apis, comp) {
  24291. return apis.whichSidebar(comp);
  24292. },
  24293. getHeader: function (apis, comp) {
  24294. return apis.getHeader(comp);
  24295. },
  24296. getToolbar: function (apis, comp) {
  24297. return apis.getToolbar(comp);
  24298. },
  24299. setToolbar: function (apis, comp, grps) {
  24300. var groups = map$2(grps, function (grp) {
  24301. return renderToolbarGroup(grp);
  24302. });
  24303. apis.setToolbar(comp, groups);
  24304. },
  24305. setToolbars: function (apis, comp, ts) {
  24306. var renderedToolbars = map$2(ts, function (g) {
  24307. return map$2(g, renderToolbarGroup);
  24308. });
  24309. apis.setToolbars(comp, renderedToolbars);
  24310. },
  24311. refreshToolbar: function (apis, comp) {
  24312. return apis.refreshToolbar(comp);
  24313. },
  24314. toggleToolbarDrawer: function (apis, comp) {
  24315. apis.toggleToolbarDrawer(comp);
  24316. },
  24317. isToolbarDrawerToggled: function (apis, comp) {
  24318. return apis.isToolbarDrawerToggled(comp);
  24319. },
  24320. getThrobber: function (apis, comp) {
  24321. return apis.getThrobber(comp);
  24322. },
  24323. setMenubar: function (apis, comp, menus) {
  24324. apis.setMenubar(comp, menus);
  24325. },
  24326. focusMenubar: function (apis, comp) {
  24327. apis.focusMenubar(comp);
  24328. },
  24329. focusToolbar: function (apis, comp) {
  24330. apis.focusToolbar(comp);
  24331. }
  24332. }
  24333. });
  24334. var defaultMenubar = 'file edit view insert format tools table help';
  24335. var defaultMenus = {
  24336. file: {
  24337. title: 'File',
  24338. items: 'newdocument restoredraft | preview | export print | deleteallconversations'
  24339. },
  24340. edit: {
  24341. title: 'Edit',
  24342. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  24343. },
  24344. view: {
  24345. title: 'View',
  24346. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  24347. },
  24348. insert: {
  24349. title: 'Insert',
  24350. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  24351. },
  24352. format: {
  24353. title: 'Format',
  24354. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat'
  24355. },
  24356. tools: {
  24357. title: 'Tools',
  24358. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  24359. },
  24360. table: {
  24361. title: 'Table',
  24362. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  24363. },
  24364. help: {
  24365. title: 'Help',
  24366. items: 'help'
  24367. }
  24368. };
  24369. var make = function (menu, registry, editor) {
  24370. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  24371. return {
  24372. text: menu.title,
  24373. getItems: function () {
  24374. return bind$3(menu.items, function (i) {
  24375. var itemName = i.toLowerCase();
  24376. if (itemName.trim().length === 0) {
  24377. return [];
  24378. } else if (exists(removedMenuItems, function (removedMenuItem) {
  24379. return removedMenuItem === itemName;
  24380. })) {
  24381. return [];
  24382. } else if (itemName === 'separator' || itemName === '|') {
  24383. return [{ type: 'separator' }];
  24384. } else if (registry.menuItems[itemName]) {
  24385. return [registry.menuItems[itemName]];
  24386. } else {
  24387. return [];
  24388. }
  24389. });
  24390. }
  24391. };
  24392. };
  24393. var parseItemsString = function (items) {
  24394. if (typeof items === 'string') {
  24395. return items.split(' ');
  24396. }
  24397. return items;
  24398. };
  24399. var identifyMenus = function (editor, registry) {
  24400. var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  24401. var userDefinedMenus = keys(registry.menus).length > 0;
  24402. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  24403. var validMenus = filter$2(menubar, function (menuName) {
  24404. var isDefaultMenu = has$2(defaultMenus, menuName);
  24405. if (userDefinedMenus) {
  24406. return isDefaultMenu || get$e(registry.menus, menuName).exists(function (menu) {
  24407. return has$2(menu, 'items');
  24408. });
  24409. } else {
  24410. return isDefaultMenu;
  24411. }
  24412. });
  24413. var menus = map$2(validMenus, function (menuName) {
  24414. var menuData = rawMenuData[menuName];
  24415. return make({
  24416. title: menuData.title,
  24417. items: parseItemsString(menuData.items)
  24418. }, registry, editor);
  24419. });
  24420. return filter$2(menus, function (menu) {
  24421. var isNotSeparator = function (item) {
  24422. return item.type !== 'separator';
  24423. };
  24424. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  24425. });
  24426. };
  24427. var fireSkinLoaded = function (editor) {
  24428. var done = function () {
  24429. editor._skinLoaded = true;
  24430. fireSkinLoaded$1(editor);
  24431. };
  24432. return function () {
  24433. if (editor.initialized) {
  24434. done();
  24435. } else {
  24436. editor.on('init', done);
  24437. }
  24438. };
  24439. };
  24440. var fireSkinLoadError = function (editor, err) {
  24441. return function () {
  24442. return fireSkinLoadError$1(editor, { message: err });
  24443. };
  24444. };
  24445. var loadStylesheet = function (editor, stylesheetUrl, styleSheetLoader) {
  24446. return new global$c(function (resolve, reject) {
  24447. styleSheetLoader.load(stylesheetUrl, resolve, reject);
  24448. editor.on('remove', function () {
  24449. return styleSheetLoader.unload(stylesheetUrl);
  24450. });
  24451. });
  24452. };
  24453. var loadUiSkins = function (editor, skinUrl) {
  24454. var skinUiCss = skinUrl + '/skin.min.css';
  24455. return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader);
  24456. };
  24457. var loadShadowDomUiSkins = function (editor, skinUrl) {
  24458. var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement()));
  24459. if (isInShadowRoot$1) {
  24460. var shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css';
  24461. return loadStylesheet(editor, shadowDomSkinCss, global$b.DOM.styleSheetLoader);
  24462. } else {
  24463. return global$c.resolve();
  24464. }
  24465. };
  24466. var loadSkin = function (isInline, editor) {
  24467. var skinUrl = getSkinUrl(editor);
  24468. if (skinUrl) {
  24469. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  24470. }
  24471. if (isSkinDisabled(editor) === false && isString(skinUrl)) {
  24472. global$c.all([
  24473. loadUiSkins(editor, skinUrl),
  24474. loadShadowDomUiSkins(editor, skinUrl)
  24475. ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, 'Skin could not be loaded'));
  24476. } else {
  24477. fireSkinLoaded(editor)();
  24478. }
  24479. };
  24480. var iframe = curry(loadSkin, false);
  24481. var inline = curry(loadSkin, true);
  24482. var onSetupFormatToggle = function (editor, name) {
  24483. return function (api) {
  24484. var boundCallback = unbindable();
  24485. var init = function () {
  24486. api.setActive(editor.formatter.match(name));
  24487. var binding = editor.formatter.formatChanged(name, api.setActive);
  24488. boundCallback.set(binding);
  24489. };
  24490. editor.initialized ? init() : editor.once('init', init);
  24491. return function () {
  24492. editor.off('init', init);
  24493. boundCallback.clear();
  24494. };
  24495. };
  24496. };
  24497. var onSetupEvent = function (editor, event, f) {
  24498. return function (api) {
  24499. var handleEvent = function () {
  24500. return f(api);
  24501. };
  24502. var init = function () {
  24503. f(api);
  24504. editor.on(event, handleEvent);
  24505. };
  24506. editor.initialized ? init() : editor.once('init', init);
  24507. return function () {
  24508. editor.off('init', init);
  24509. editor.off(event, handleEvent);
  24510. };
  24511. };
  24512. };
  24513. var onActionToggleFormat$1 = function (editor) {
  24514. return function (rawItem) {
  24515. return function () {
  24516. editor.undoManager.transact(function () {
  24517. editor.focus();
  24518. editor.execCommand('mceToggleFormat', false, rawItem.format);
  24519. });
  24520. };
  24521. };
  24522. };
  24523. var onActionExecCommand = function (editor, command) {
  24524. return function () {
  24525. return editor.execCommand(command);
  24526. };
  24527. };
  24528. var generateSelectItems = function (_editor, backstage, spec) {
  24529. var generateItem = function (rawItem, response, disabled, value) {
  24530. var translatedText = backstage.shared.providers.translate(rawItem.title);
  24531. if (rawItem.type === 'separator') {
  24532. return Optional.some({
  24533. type: 'separator',
  24534. text: translatedText
  24535. });
  24536. } else if (rawItem.type === 'submenu') {
  24537. var items = bind$3(rawItem.getStyleItems(), function (si) {
  24538. return validate(si, response, value);
  24539. });
  24540. if (response === 0 && items.length <= 0) {
  24541. return Optional.none();
  24542. } else {
  24543. return Optional.some({
  24544. type: 'nestedmenuitem',
  24545. text: translatedText,
  24546. disabled: items.length <= 0,
  24547. getSubmenuItems: function () {
  24548. return bind$3(rawItem.getStyleItems(), function (si) {
  24549. return validate(si, response, value);
  24550. });
  24551. }
  24552. });
  24553. }
  24554. } else {
  24555. return Optional.some(__assign({
  24556. type: 'togglemenuitem',
  24557. text: translatedText,
  24558. icon: rawItem.icon,
  24559. active: rawItem.isSelected(value),
  24560. disabled: disabled,
  24561. onAction: spec.onAction(rawItem)
  24562. }, rawItem.getStylePreview().fold(function () {
  24563. return {};
  24564. }, function (preview) {
  24565. return { meta: { style: preview } };
  24566. })));
  24567. }
  24568. };
  24569. var validate = function (item, response, value) {
  24570. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  24571. if (response === 0) {
  24572. return invalid ? [] : generateItem(item, response, false, value).toArray();
  24573. } else {
  24574. return generateItem(item, response, invalid, value).toArray();
  24575. }
  24576. };
  24577. var validateItems = function (preItems) {
  24578. var value = spec.getCurrentValue();
  24579. var response = spec.shouldHide ? 0 : 1;
  24580. return bind$3(preItems, function (item) {
  24581. return validate(item, response, value);
  24582. });
  24583. };
  24584. var getFetch = function (backstage, getStyleItems) {
  24585. return function (comp, callback) {
  24586. var preItems = getStyleItems();
  24587. var items = validateItems(preItems);
  24588. var menu = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  24589. callback(menu);
  24590. };
  24591. };
  24592. return {
  24593. validateItems: validateItems,
  24594. getFetch: getFetch
  24595. };
  24596. };
  24597. var createMenuItems = function (editor, backstage, spec) {
  24598. var dataset = spec.dataset;
  24599. var getStyleItems = dataset.type === 'basic' ? function () {
  24600. return map$2(dataset.data, function (d) {
  24601. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  24602. });
  24603. } : dataset.getData;
  24604. return {
  24605. items: generateSelectItems(editor, backstage, spec),
  24606. getStyleItems: getStyleItems
  24607. };
  24608. };
  24609. var createSelectButton = function (editor, backstage, spec) {
  24610. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  24611. var getApi = function (comp) {
  24612. return { getComponent: constant$1(comp) };
  24613. };
  24614. var onSetup = onSetupEvent(editor, 'NodeChange', function (api) {
  24615. var comp = api.getComponent();
  24616. spec.updateText(comp);
  24617. });
  24618. return renderCommonDropdown({
  24619. text: spec.icon.isSome() ? Optional.none() : spec.text,
  24620. icon: spec.icon,
  24621. tooltip: Optional.from(spec.tooltip),
  24622. role: Optional.none(),
  24623. fetch: items.getFetch(backstage, getStyleItems),
  24624. onSetup: onSetup,
  24625. getApi: getApi,
  24626. columns: 1,
  24627. presets: 'normal',
  24628. classes: spec.icon.isSome() ? [] : ['bespoke'],
  24629. dropdownBehaviours: []
  24630. }, 'tox-tbtn', backstage.shared);
  24631. };
  24632. var process = function (rawFormats) {
  24633. return map$2(rawFormats, function (item) {
  24634. var title = item, format = item;
  24635. var values = item.split('=');
  24636. if (values.length > 1) {
  24637. title = values[0];
  24638. format = values[1];
  24639. }
  24640. return {
  24641. title: title,
  24642. format: format
  24643. };
  24644. });
  24645. };
  24646. var buildBasicStaticDataset = function (data) {
  24647. return {
  24648. type: 'basic',
  24649. data: data
  24650. };
  24651. };
  24652. var Delimiter;
  24653. (function (Delimiter) {
  24654. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  24655. Delimiter[Delimiter['Space'] = 1] = 'Space';
  24656. }(Delimiter || (Delimiter = {})));
  24657. var split = function (rawFormats, delimiter) {
  24658. if (delimiter === Delimiter.SemiColon) {
  24659. return rawFormats.replace(/;$/, '').split(';');
  24660. } else {
  24661. return rawFormats.split(' ');
  24662. }
  24663. };
  24664. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  24665. var rawFormats = editor.getParam(settingName, defaults, 'string');
  24666. var data = process(split(rawFormats, delimiter));
  24667. return {
  24668. type: 'basic',
  24669. data: data
  24670. };
  24671. };
  24672. var alignMenuItems = [
  24673. {
  24674. title: 'Left',
  24675. icon: 'align-left',
  24676. format: 'alignleft',
  24677. command: 'JustifyLeft'
  24678. },
  24679. {
  24680. title: 'Center',
  24681. icon: 'align-center',
  24682. format: 'aligncenter',
  24683. command: 'JustifyCenter'
  24684. },
  24685. {
  24686. title: 'Right',
  24687. icon: 'align-right',
  24688. format: 'alignright',
  24689. command: 'JustifyRight'
  24690. },
  24691. {
  24692. title: 'Justify',
  24693. icon: 'align-justify',
  24694. format: 'alignjustify',
  24695. command: 'JustifyFull'
  24696. }
  24697. ];
  24698. var getSpec$4 = function (editor) {
  24699. var getMatchingValue = function () {
  24700. return find$5(alignMenuItems, function (item) {
  24701. return editor.formatter.match(item.format);
  24702. });
  24703. };
  24704. var isSelectedFor = function (format) {
  24705. return function () {
  24706. return editor.formatter.match(format);
  24707. };
  24708. };
  24709. var getPreviewFor = function (_format) {
  24710. return Optional.none;
  24711. };
  24712. var updateSelectMenuIcon = function (comp) {
  24713. var match = getMatchingValue();
  24714. var alignment = match.fold(constant$1('left'), function (item) {
  24715. return item.title.toLowerCase();
  24716. });
  24717. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  24718. };
  24719. var dataset = buildBasicStaticDataset(alignMenuItems);
  24720. var onAction = function (rawItem) {
  24721. return function () {
  24722. return find$5(alignMenuItems, function (item) {
  24723. return item.format === rawItem.format;
  24724. }).each(function (item) {
  24725. return editor.execCommand(item.command);
  24726. });
  24727. };
  24728. };
  24729. return {
  24730. tooltip: 'Align',
  24731. text: Optional.none(),
  24732. icon: Optional.some('align-left'),
  24733. isSelectedFor: isSelectedFor,
  24734. getCurrentValue: Optional.none,
  24735. getPreviewFor: getPreviewFor,
  24736. onAction: onAction,
  24737. updateText: updateSelectMenuIcon,
  24738. dataset: dataset,
  24739. shouldHide: false,
  24740. isInvalid: function (item) {
  24741. return !editor.formatter.canApply(item.format);
  24742. }
  24743. };
  24744. };
  24745. var createAlignSelect = function (editor, backstage) {
  24746. return createSelectButton(editor, backstage, getSpec$4(editor));
  24747. };
  24748. var alignSelectMenu = function (editor, backstage) {
  24749. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor));
  24750. editor.ui.registry.addNestedMenuItem('align', {
  24751. text: backstage.shared.providers.translate('Align'),
  24752. getSubmenuItems: function () {
  24753. return menuItems.items.validateItems(menuItems.getStyleItems());
  24754. }
  24755. });
  24756. };
  24757. 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';
  24758. var systemStackFonts = [
  24759. '-apple-system',
  24760. 'Segoe UI',
  24761. 'Roboto',
  24762. 'Helvetica Neue',
  24763. 'sans-serif'
  24764. ];
  24765. var splitFonts = function (fontFamily) {
  24766. var fonts = fontFamily.split(/\s*,\s*/);
  24767. return map$2(fonts, function (font) {
  24768. return font.replace(/^['"]+|['"]+$/g, '');
  24769. });
  24770. };
  24771. var isSystemFontStack = function (fontFamily) {
  24772. var matchesSystemStack = function () {
  24773. var fonts = splitFonts(fontFamily.toLowerCase());
  24774. return forall(systemStackFonts, function (font) {
  24775. return fonts.indexOf(font.toLowerCase()) > -1;
  24776. });
  24777. };
  24778. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  24779. };
  24780. var getSpec$3 = function (editor) {
  24781. var systemFont = 'System Font';
  24782. var getMatchingValue = function () {
  24783. var getFirstFont = function (fontFamily) {
  24784. return fontFamily ? splitFonts(fontFamily)[0] : '';
  24785. };
  24786. var fontFamily = editor.queryCommandValue('FontName');
  24787. var items = dataset.data;
  24788. var font = fontFamily ? fontFamily.toLowerCase() : '';
  24789. var matchOpt = find$5(items, function (item) {
  24790. var format = item.format;
  24791. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  24792. }).orThunk(function () {
  24793. return someIf(isSystemFontStack(font), {
  24794. title: systemFont,
  24795. format: font
  24796. });
  24797. });
  24798. return {
  24799. matchOpt: matchOpt,
  24800. font: fontFamily
  24801. };
  24802. };
  24803. var isSelectedFor = function (item) {
  24804. return function (valueOpt) {
  24805. return valueOpt.exists(function (value) {
  24806. return value.format === item;
  24807. });
  24808. };
  24809. };
  24810. var getCurrentValue = function () {
  24811. var matchOpt = getMatchingValue().matchOpt;
  24812. return matchOpt;
  24813. };
  24814. var getPreviewFor = function (item) {
  24815. return function () {
  24816. return Optional.some({
  24817. tag: 'div',
  24818. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  24819. });
  24820. };
  24821. };
  24822. var onAction = function (rawItem) {
  24823. return function () {
  24824. editor.undoManager.transact(function () {
  24825. editor.focus();
  24826. editor.execCommand('FontName', false, rawItem.format);
  24827. });
  24828. };
  24829. };
  24830. var updateSelectMenuText = function (comp) {
  24831. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  24832. var text = matchOpt.fold(constant$1(font), function (item) {
  24833. return item.title;
  24834. });
  24835. emitWith(comp, updateMenuText, { text: text });
  24836. };
  24837. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  24838. return {
  24839. tooltip: 'Fonts',
  24840. text: Optional.some(systemFont),
  24841. icon: Optional.none(),
  24842. isSelectedFor: isSelectedFor,
  24843. getCurrentValue: getCurrentValue,
  24844. getPreviewFor: getPreviewFor,
  24845. onAction: onAction,
  24846. updateText: updateSelectMenuText,
  24847. dataset: dataset,
  24848. shouldHide: false,
  24849. isInvalid: never
  24850. };
  24851. };
  24852. var createFontSelect = function (editor, backstage) {
  24853. return createSelectButton(editor, backstage, getSpec$3(editor));
  24854. };
  24855. var fontSelectMenu = function (editor, backstage) {
  24856. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  24857. editor.ui.registry.addNestedMenuItem('fontformats', {
  24858. text: backstage.shared.providers.translate('Fonts'),
  24859. getSubmenuItems: function () {
  24860. return menuItems.items.validateItems(menuItems.getStyleItems());
  24861. }
  24862. });
  24863. };
  24864. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  24865. var legacyFontSizes = {
  24866. '8pt': '1',
  24867. '10pt': '2',
  24868. '12pt': '3',
  24869. '14pt': '4',
  24870. '18pt': '5',
  24871. '24pt': '6',
  24872. '36pt': '7'
  24873. };
  24874. var keywordFontSizes = {
  24875. 'xx-small': '7pt',
  24876. 'x-small': '8pt',
  24877. 'small': '10pt',
  24878. 'medium': '12pt',
  24879. 'large': '14pt',
  24880. 'x-large': '18pt',
  24881. 'xx-large': '24pt'
  24882. };
  24883. var round = function (number, precision) {
  24884. var factor = Math.pow(10, precision);
  24885. return Math.round(number * factor) / factor;
  24886. };
  24887. var toPt = function (fontSize, precision) {
  24888. if (/[0-9.]+px$/.test(fontSize)) {
  24889. return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  24890. } else {
  24891. return get$e(keywordFontSizes, fontSize).getOr(fontSize);
  24892. }
  24893. };
  24894. var toLegacy = function (fontSize) {
  24895. return get$e(legacyFontSizes, fontSize).getOr('');
  24896. };
  24897. var getSpec$2 = function (editor) {
  24898. var getMatchingValue = function () {
  24899. var matchOpt = Optional.none();
  24900. var items = dataset.data;
  24901. var fontSize = editor.queryCommandValue('FontSize');
  24902. if (fontSize) {
  24903. var _loop_1 = function (precision) {
  24904. var pt = toPt(fontSize, precision);
  24905. var legacy = toLegacy(pt);
  24906. matchOpt = find$5(items, function (item) {
  24907. return item.format === fontSize || item.format === pt || item.format === legacy;
  24908. });
  24909. };
  24910. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  24911. _loop_1(precision);
  24912. }
  24913. }
  24914. return {
  24915. matchOpt: matchOpt,
  24916. size: fontSize
  24917. };
  24918. };
  24919. var isSelectedFor = function (item) {
  24920. return function (valueOpt) {
  24921. return valueOpt.exists(function (value) {
  24922. return value.format === item;
  24923. });
  24924. };
  24925. };
  24926. var getCurrentValue = function () {
  24927. var matchOpt = getMatchingValue().matchOpt;
  24928. return matchOpt;
  24929. };
  24930. var getPreviewFor = constant$1(Optional.none);
  24931. var onAction = function (rawItem) {
  24932. return function () {
  24933. editor.undoManager.transact(function () {
  24934. editor.focus();
  24935. editor.execCommand('FontSize', false, rawItem.format);
  24936. });
  24937. };
  24938. };
  24939. var updateSelectMenuText = function (comp) {
  24940. var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  24941. var text = matchOpt.fold(constant$1(size), function (match) {
  24942. return match.title;
  24943. });
  24944. emitWith(comp, updateMenuText, { text: text });
  24945. };
  24946. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  24947. return {
  24948. tooltip: 'Font sizes',
  24949. text: Optional.some('12pt'),
  24950. icon: Optional.none(),
  24951. isSelectedFor: isSelectedFor,
  24952. getPreviewFor: getPreviewFor,
  24953. getCurrentValue: getCurrentValue,
  24954. onAction: onAction,
  24955. updateText: updateSelectMenuText,
  24956. dataset: dataset,
  24957. shouldHide: false,
  24958. isInvalid: never
  24959. };
  24960. };
  24961. var createFontsizeSelect = function (editor, backstage) {
  24962. return createSelectButton(editor, backstage, getSpec$2(editor));
  24963. };
  24964. var fontsizeSelectMenu = function (editor, backstage) {
  24965. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  24966. editor.ui.registry.addNestedMenuItem('fontsizes', {
  24967. text: 'Font sizes',
  24968. getSubmenuItems: function () {
  24969. return menuItems.items.validateItems(menuItems.getStyleItems());
  24970. }
  24971. });
  24972. };
  24973. var findNearest = function (editor, getStyles) {
  24974. var styles = getStyles();
  24975. var formats = map$2(styles, function (style) {
  24976. return style.format;
  24977. });
  24978. return Optional.from(editor.formatter.closest(formats)).bind(function (fmt) {
  24979. return find$5(styles, function (data) {
  24980. return data.format === fmt;
  24981. });
  24982. }).orThunk(function () {
  24983. return someIf(editor.formatter.match('p'), {
  24984. title: 'Paragraph',
  24985. format: 'p'
  24986. });
  24987. });
  24988. };
  24989. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  24990. var getSpec$1 = function (editor) {
  24991. var fallbackFormat = 'Paragraph';
  24992. var isSelectedFor = function (format) {
  24993. return function () {
  24994. return editor.formatter.match(format);
  24995. };
  24996. };
  24997. var getPreviewFor = function (format) {
  24998. return function () {
  24999. var fmt = editor.formatter.get(format);
  25000. return Optional.some({
  25001. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  25002. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  25003. });
  25004. };
  25005. };
  25006. var updateSelectMenuText = function (comp) {
  25007. var detectedFormat = findNearest(editor, function () {
  25008. return dataset.data;
  25009. });
  25010. var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  25011. return fmt.title;
  25012. });
  25013. emitWith(comp, updateMenuText, { text: text });
  25014. };
  25015. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  25016. return {
  25017. tooltip: 'Blocks',
  25018. text: Optional.some(fallbackFormat),
  25019. icon: Optional.none(),
  25020. isSelectedFor: isSelectedFor,
  25021. getCurrentValue: Optional.none,
  25022. getPreviewFor: getPreviewFor,
  25023. onAction: onActionToggleFormat$1(editor),
  25024. updateText: updateSelectMenuText,
  25025. dataset: dataset,
  25026. shouldHide: false,
  25027. isInvalid: function (item) {
  25028. return !editor.formatter.canApply(item.format);
  25029. }
  25030. };
  25031. };
  25032. var createFormatSelect = function (editor, backstage) {
  25033. return createSelectButton(editor, backstage, getSpec$1(editor));
  25034. };
  25035. var formatSelectMenu = function (editor, backstage) {
  25036. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  25037. editor.ui.registry.addNestedMenuItem('blockformats', {
  25038. text: 'Blocks',
  25039. getSubmenuItems: function () {
  25040. return menuItems.items.validateItems(menuItems.getStyleItems());
  25041. }
  25042. });
  25043. };
  25044. var getSpec = function (editor, dataset) {
  25045. var fallbackFormat = 'Paragraph';
  25046. var isSelectedFor = function (format) {
  25047. return function () {
  25048. return editor.formatter.match(format);
  25049. };
  25050. };
  25051. var getPreviewFor = function (format) {
  25052. return function () {
  25053. var fmt = editor.formatter.get(format);
  25054. return fmt !== undefined ? Optional.some({
  25055. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  25056. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  25057. }) : Optional.none();
  25058. };
  25059. };
  25060. var updateSelectMenuText = function (comp) {
  25061. var getFormatItems = function (fmt) {
  25062. var subs = fmt.items;
  25063. return subs !== undefined && subs.length > 0 ? bind$3(subs, getFormatItems) : [{
  25064. title: fmt.title,
  25065. format: fmt.format
  25066. }];
  25067. };
  25068. var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems);
  25069. var detectedFormat = findNearest(editor, constant$1(flattenedItems));
  25070. var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) {
  25071. return fmt.title;
  25072. });
  25073. emitWith(comp, updateMenuText, { text: text });
  25074. };
  25075. return {
  25076. tooltip: 'Formats',
  25077. text: Optional.some(fallbackFormat),
  25078. icon: Optional.none(),
  25079. isSelectedFor: isSelectedFor,
  25080. getCurrentValue: Optional.none,
  25081. getPreviewFor: getPreviewFor,
  25082. onAction: onActionToggleFormat$1(editor),
  25083. updateText: updateSelectMenuText,
  25084. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  25085. isInvalid: function (item) {
  25086. return !editor.formatter.canApply(item.format);
  25087. },
  25088. dataset: dataset
  25089. };
  25090. };
  25091. var createStyleSelect = function (editor, backstage) {
  25092. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  25093. return createSelectButton(editor, backstage, getSpec(editor, dataset));
  25094. };
  25095. var styleSelectMenu = function (editor, backstage) {
  25096. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  25097. var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset));
  25098. editor.ui.registry.addNestedMenuItem('formats', {
  25099. text: 'Formats',
  25100. getSubmenuItems: function () {
  25101. return menuItems.items.validateItems(menuItems.getStyleItems());
  25102. }
  25103. });
  25104. };
  25105. var events$3 = function (reflectingConfig, reflectingState) {
  25106. var update = function (component, data) {
  25107. reflectingConfig.updateState.each(function (updateState) {
  25108. var newState = updateState(component, data);
  25109. reflectingState.set(newState);
  25110. });
  25111. reflectingConfig.renderComponents.each(function (renderComponents) {
  25112. var newComponents = renderComponents(data, reflectingState.get());
  25113. var newChildren = map$2(newComponents, component.getSystem().build);
  25114. replaceChildren(component, newChildren);
  25115. });
  25116. };
  25117. return derive$2([
  25118. run$1(receive(), function (component, message) {
  25119. var receivingData = message;
  25120. if (!receivingData.universal) {
  25121. var channel = reflectingConfig.channel;
  25122. if (contains$2(receivingData.channels, channel)) {
  25123. update(component, receivingData.data);
  25124. }
  25125. }
  25126. }),
  25127. runOnAttached(function (comp, _se) {
  25128. reflectingConfig.initialData.each(function (rawData) {
  25129. update(comp, rawData);
  25130. });
  25131. })
  25132. ]);
  25133. };
  25134. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  25135. __proto__: null,
  25136. events: events$3
  25137. });
  25138. var getState = function (component, replaceConfig, reflectState) {
  25139. return reflectState;
  25140. };
  25141. var ReflectingApis = /*#__PURE__*/Object.freeze({
  25142. __proto__: null,
  25143. getState: getState
  25144. });
  25145. var ReflectingSchema = [
  25146. required$1('channel'),
  25147. option('renderComponents'),
  25148. option('updateState'),
  25149. option('initialData')
  25150. ];
  25151. var init$3 = function () {
  25152. var cell = Cell(Optional.none());
  25153. var clear = function () {
  25154. return cell.set(Optional.none());
  25155. };
  25156. var readState = function () {
  25157. return cell.get().getOr('none');
  25158. };
  25159. return {
  25160. readState: readState,
  25161. get: cell.get,
  25162. set: cell.set,
  25163. clear: clear
  25164. };
  25165. };
  25166. var ReflectingState = /*#__PURE__*/Object.freeze({
  25167. __proto__: null,
  25168. init: init$3
  25169. });
  25170. var Reflecting = create$7({
  25171. fields: ReflectingSchema,
  25172. name: 'reflecting',
  25173. active: ActiveReflecting,
  25174. apis: ReflectingApis,
  25175. state: ReflectingState
  25176. });
  25177. var schema$7 = constant$1([
  25178. required$1('toggleClass'),
  25179. required$1('fetch'),
  25180. onStrictHandler('onExecute'),
  25181. defaulted('getHotspot', Optional.some),
  25182. defaulted('getAnchorOverrides', constant$1({})),
  25183. schema$y(),
  25184. onStrictHandler('onItemExecute'),
  25185. option('lazySink'),
  25186. required$1('dom'),
  25187. onHandler('onOpen'),
  25188. field('splitDropdownBehaviours', [
  25189. Coupling,
  25190. Keying,
  25191. Focusing
  25192. ]),
  25193. defaulted('matchWidth', false),
  25194. defaulted('useMinWidth', false),
  25195. defaulted('eventOrder', {}),
  25196. option('role')
  25197. ].concat(sandboxFields()));
  25198. var arrowPart = required({
  25199. factory: Button,
  25200. schema: [required$1('dom')],
  25201. name: 'arrow',
  25202. defaults: function () {
  25203. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  25204. },
  25205. overrides: function (detail) {
  25206. return {
  25207. dom: {
  25208. tag: 'span',
  25209. attributes: { role: 'presentation' }
  25210. },
  25211. action: function (arrow) {
  25212. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  25213. },
  25214. buttonBehaviours: derive$1([Toggling.config({
  25215. toggleOnExecute: false,
  25216. toggleClass: detail.toggleClass
  25217. })])
  25218. };
  25219. }
  25220. });
  25221. var buttonPart = required({
  25222. factory: Button,
  25223. schema: [required$1('dom')],
  25224. name: 'button',
  25225. defaults: function () {
  25226. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  25227. },
  25228. overrides: function (detail) {
  25229. return {
  25230. dom: {
  25231. tag: 'span',
  25232. attributes: { role: 'presentation' }
  25233. },
  25234. action: function (btn) {
  25235. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  25236. detail.onExecute(splitDropdown, btn);
  25237. });
  25238. }
  25239. };
  25240. }
  25241. });
  25242. var parts$3 = constant$1([
  25243. arrowPart,
  25244. buttonPart,
  25245. optional({
  25246. factory: {
  25247. sketch: function (spec) {
  25248. return {
  25249. uid: spec.uid,
  25250. dom: {
  25251. tag: 'span',
  25252. styles: { display: 'none' },
  25253. attributes: { 'aria-hidden': 'true' },
  25254. innerHtml: spec.text
  25255. }
  25256. };
  25257. }
  25258. },
  25259. schema: [required$1('text')],
  25260. name: 'aria-descriptor'
  25261. }),
  25262. external$1({
  25263. schema: [tieredMenuMarkers()],
  25264. name: 'menu',
  25265. defaults: function (detail) {
  25266. return {
  25267. onExecute: function (tmenu, item) {
  25268. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  25269. detail.onItemExecute(splitDropdown, tmenu, item);
  25270. });
  25271. }
  25272. };
  25273. }
  25274. }),
  25275. partType$1()
  25276. ]);
  25277. var factory$5 = function (detail, components, spec, externals) {
  25278. var _a;
  25279. var switchToMenu = function (sandbox) {
  25280. Composing.getCurrent(sandbox).each(function (current) {
  25281. Highlighting.highlightFirst(current);
  25282. Keying.focusIn(current);
  25283. });
  25284. };
  25285. var action = function (component) {
  25286. var onOpenSync = switchToMenu;
  25287. togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  25288. };
  25289. var openMenu = function (comp) {
  25290. action(comp);
  25291. return Optional.some(true);
  25292. };
  25293. var executeOnButton = function (comp) {
  25294. var button = getPartOrDie(comp, detail, 'button');
  25295. emitExecute(button);
  25296. return Optional.some(true);
  25297. };
  25298. var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function (component, _simulatedEvent) {
  25299. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  25300. ariaDescriptor.each(function (descriptor) {
  25301. var descriptorId = generate$6('aria');
  25302. set$8(descriptor.element, 'id', descriptorId);
  25303. set$8(component.element, 'aria-describedby', descriptorId);
  25304. });
  25305. })])), events$a(Optional.some(action)));
  25306. var apis = {
  25307. repositionMenus: function (comp) {
  25308. if (Toggling.isOn(comp)) {
  25309. repositionMenus(comp);
  25310. }
  25311. }
  25312. };
  25313. return {
  25314. uid: detail.uid,
  25315. dom: detail.dom,
  25316. components: components,
  25317. apis: apis,
  25318. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [
  25319. 'disabling',
  25320. 'toggling',
  25321. 'alloy.base.behaviour'
  25322. ], _a)),
  25323. events: buttonEvents,
  25324. behaviours: augment(detail.splitDropdownBehaviours, [
  25325. Coupling.config({
  25326. others: {
  25327. sandbox: function (hotspot) {
  25328. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  25329. var extras = {
  25330. onOpen: function () {
  25331. Toggling.on(arrow);
  25332. Toggling.on(hotspot);
  25333. },
  25334. onClose: function () {
  25335. Toggling.off(arrow);
  25336. Toggling.off(hotspot);
  25337. }
  25338. };
  25339. return makeSandbox$1(detail, hotspot, extras);
  25340. }
  25341. }
  25342. }),
  25343. Keying.config({
  25344. mode: 'special',
  25345. onSpace: executeOnButton,
  25346. onEnter: executeOnButton,
  25347. onDown: openMenu
  25348. }),
  25349. Focusing.config({}),
  25350. Toggling.config({
  25351. toggleOnExecute: false,
  25352. aria: { mode: 'expanded' }
  25353. })
  25354. ]),
  25355. domModification: {
  25356. attributes: {
  25357. 'role': detail.role.getOr('button'),
  25358. 'aria-haspopup': true
  25359. }
  25360. }
  25361. };
  25362. };
  25363. var SplitDropdown = composite({
  25364. name: 'SplitDropdown',
  25365. configFields: schema$7(),
  25366. partFields: parts$3(),
  25367. factory: factory$5,
  25368. apis: {
  25369. repositionMenus: function (apis, comp) {
  25370. return apis.repositionMenus(comp);
  25371. }
  25372. }
  25373. });
  25374. var getButtonApi = function (component) {
  25375. return {
  25376. isDisabled: function () {
  25377. return Disabling.isDisabled(component);
  25378. },
  25379. setDisabled: function (state) {
  25380. return Disabling.set(component, state);
  25381. }
  25382. };
  25383. };
  25384. var getToggleApi = function (component) {
  25385. return {
  25386. setActive: function (state) {
  25387. Toggling.set(component, state);
  25388. },
  25389. isActive: function () {
  25390. return Toggling.isOn(component);
  25391. },
  25392. isDisabled: function () {
  25393. return Disabling.isDisabled(component);
  25394. },
  25395. setDisabled: function (state) {
  25396. return Disabling.set(component, state);
  25397. }
  25398. };
  25399. };
  25400. var getTooltipAttributes = function (tooltip, providersBackstage) {
  25401. return tooltip.map(function (tooltip) {
  25402. return {
  25403. 'aria-label': providersBackstage.translate(tooltip),
  25404. 'title': providersBackstage.translate(tooltip)
  25405. };
  25406. }).getOr({});
  25407. };
  25408. var focusButtonEvent = generate$6('focus-button');
  25409. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  25410. var _d;
  25411. return {
  25412. dom: {
  25413. tag: 'button',
  25414. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []),
  25415. attributes: getTooltipAttributes(tooltip, providersBackstage)
  25416. },
  25417. components: componentRenderPipeline([
  25418. icon.map(function (iconName) {
  25419. return renderIconFromPack(iconName, providersBackstage.icons);
  25420. }),
  25421. text.map(function (text) {
  25422. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  25423. })
  25424. ]),
  25425. eventOrder: (_d = {}, _d[mousedown()] = [
  25426. 'focusing',
  25427. 'alloy.base.behaviour',
  25428. 'common-button-display-events'
  25429. ], _d),
  25430. buttonBehaviours: derive$1([
  25431. DisablingConfigs.toolbarButton(providersBackstage.isDisabled),
  25432. receivingConfig(),
  25433. config('common-button-display-events', [run$1(mousedown(), function (button, se) {
  25434. se.event.prevent();
  25435. emit(button, focusButtonEvent);
  25436. })])
  25437. ].concat(receiver.map(function (r) {
  25438. return Reflecting.config({
  25439. channel: r,
  25440. initialData: {
  25441. icon: icon,
  25442. text: text
  25443. },
  25444. renderComponents: function (data, _state) {
  25445. return componentRenderPipeline([
  25446. data.icon.map(function (iconName) {
  25447. return renderIconFromPack(iconName, providersBackstage.icons);
  25448. }),
  25449. data.text.map(function (text) {
  25450. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  25451. })
  25452. ]);
  25453. }
  25454. });
  25455. }).toArray()).concat(behaviours.getOr([])))
  25456. };
  25457. };
  25458. var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  25459. var sharedBackstage = backstage.shared;
  25460. return FloatingToolbarButton.sketch({
  25461. lazySink: sharedBackstage.getSink,
  25462. fetch: function () {
  25463. return Future.nu(function (resolve) {
  25464. resolve(map$2(identifyButtons(spec.items), renderToolbarGroup));
  25465. });
  25466. },
  25467. markers: { toggledClass: 'tox-tbtn--enabled' },
  25468. parts: {
  25469. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers),
  25470. toolbar: {
  25471. dom: {
  25472. tag: 'div',
  25473. classes: ['tox-toolbar__overflow'],
  25474. attributes: attributes
  25475. }
  25476. }
  25477. }
  25478. });
  25479. };
  25480. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  25481. var editorOffCell = Cell(noop);
  25482. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage);
  25483. return Button.sketch({
  25484. dom: structure.dom,
  25485. components: structure.components,
  25486. eventOrder: toolbarButtonEventOrder,
  25487. buttonBehaviours: derive$1([
  25488. config('toolbar-button-events', [
  25489. onToolbarButtonExecute({
  25490. onAction: spec.onAction,
  25491. getApi: specialisation.getApi
  25492. }),
  25493. onControlAttached(specialisation, editorOffCell),
  25494. onControlDetached(specialisation, editorOffCell)
  25495. ]),
  25496. DisablingConfigs.toolbarButton(function () {
  25497. return spec.disabled || providersBackstage.isDisabled();
  25498. }),
  25499. receivingConfig()
  25500. ].concat(specialisation.toolbarButtonBehaviours))
  25501. });
  25502. };
  25503. var renderToolbarButton = function (spec, providersBackstage) {
  25504. return renderToolbarButtonWith(spec, providersBackstage, []);
  25505. };
  25506. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  25507. return renderCommonToolbarButton(spec, {
  25508. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  25509. getApi: getButtonApi,
  25510. onSetup: spec.onSetup
  25511. }, providersBackstage);
  25512. };
  25513. var renderToolbarToggleButton = function (spec, providersBackstage) {
  25514. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  25515. };
  25516. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  25517. return deepMerge(renderCommonToolbarButton(spec, {
  25518. toolbarButtonBehaviours: [
  25519. Replacing.config({}),
  25520. Toggling.config({
  25521. toggleClass: 'tox-tbtn--enabled',
  25522. aria: { mode: 'pressed' },
  25523. toggleOnExecute: false
  25524. })
  25525. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  25526. getApi: getToggleApi,
  25527. onSetup: spec.onSetup
  25528. }, providersBackstage));
  25529. };
  25530. var fetchChoices = function (getApi, spec, providersBackstage) {
  25531. return function (comp) {
  25532. return Future.nu(function (callback) {
  25533. return spec.fetch(callback);
  25534. }).map(function (items) {
  25535. return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) {
  25536. spec.onItemAction(getApi(comp), value);
  25537. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), {
  25538. movement: deriveMenuMovement(spec.columns, spec.presets),
  25539. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  25540. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
  25541. var numRows = _d.numRows, numColumns = _d.numColumns;
  25542. Keying.setGridSize(comp, numRows, numColumns);
  25543. });
  25544. })])
  25545. })));
  25546. });
  25547. };
  25548. };
  25549. var renderSplitButton = function (spec, sharedBackstage) {
  25550. var _d;
  25551. var displayChannel = generate$6('channel-update-split-dropdown-display');
  25552. var getApi = function (comp) {
  25553. return {
  25554. isDisabled: function () {
  25555. return Disabling.isDisabled(comp);
  25556. },
  25557. setDisabled: function (state) {
  25558. return Disabling.set(comp, state);
  25559. },
  25560. setIconFill: function (id, value) {
  25561. descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  25562. set$8(underlinePath, 'fill', value);
  25563. });
  25564. },
  25565. setIconStroke: function (id, value) {
  25566. descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  25567. set$8(underlinePath, 'stroke', value);
  25568. });
  25569. },
  25570. setActive: function (state) {
  25571. set$8(comp.element, 'aria-pressed', state);
  25572. descendant(comp.element, 'span').each(function (button) {
  25573. comp.getSystem().getByDom(button).each(function (buttonComp) {
  25574. return Toggling.set(buttonComp, state);
  25575. });
  25576. });
  25577. },
  25578. isActive: function () {
  25579. return descendant(comp.element, 'span').exists(function (button) {
  25580. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  25581. });
  25582. }
  25583. };
  25584. };
  25585. var editorOffCell = Cell(noop);
  25586. var specialisation = {
  25587. getApi: getApi,
  25588. onSetup: spec.onSetup
  25589. };
  25590. return SplitDropdown.sketch({
  25591. dom: {
  25592. tag: 'div',
  25593. classes: ['tox-split-button'],
  25594. attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  25595. },
  25596. onExecute: function (button) {
  25597. spec.onAction(getApi(button));
  25598. },
  25599. onItemExecute: function (_a, _b, _c) {
  25600. },
  25601. splitDropdownBehaviours: derive$1([
  25602. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  25603. receivingConfig(),
  25604. config('split-dropdown-events', [
  25605. run$1(focusButtonEvent, Focusing.focus),
  25606. onControlAttached(specialisation, editorOffCell),
  25607. onControlDetached(specialisation, editorOffCell)
  25608. ]),
  25609. Unselecting.config({})
  25610. ]),
  25611. eventOrder: (_d = {}, _d[attachedToDom()] = [
  25612. 'alloy.base.behaviour',
  25613. 'split-dropdown-events'
  25614. ], _d),
  25615. toggleClass: 'tox-tbtn--enabled',
  25616. lazySink: sharedBackstage.getSink,
  25617. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  25618. parts: { menu: part(false, spec.columns, spec.presets) },
  25619. components: [
  25620. SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({
  25621. toggleClass: 'tox-tbtn--enabled',
  25622. toggleOnExecute: false
  25623. })]), sharedBackstage.providers)),
  25624. SplitDropdown.parts.arrow({
  25625. dom: {
  25626. tag: 'button',
  25627. classes: [
  25628. 'tox-tbtn',
  25629. 'tox-split-button__chevron'
  25630. ],
  25631. innerHtml: get$1('chevron-down', sharedBackstage.providers.icons)
  25632. },
  25633. buttonBehaviours: derive$1([
  25634. DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled),
  25635. receivingConfig(),
  25636. addFocusableBehaviour()
  25637. ])
  25638. }),
  25639. SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  25640. ]
  25641. });
  25642. };
  25643. var defaultToolbar = [
  25644. {
  25645. name: 'history',
  25646. items: [
  25647. 'undo',
  25648. 'redo'
  25649. ]
  25650. },
  25651. {
  25652. name: 'styles',
  25653. items: ['styleselect']
  25654. },
  25655. {
  25656. name: 'formatting',
  25657. items: [
  25658. 'bold',
  25659. 'italic'
  25660. ]
  25661. },
  25662. {
  25663. name: 'alignment',
  25664. items: [
  25665. 'alignleft',
  25666. 'aligncenter',
  25667. 'alignright',
  25668. 'alignjustify'
  25669. ]
  25670. },
  25671. {
  25672. name: 'indentation',
  25673. items: [
  25674. 'outdent',
  25675. 'indent'
  25676. ]
  25677. },
  25678. {
  25679. name: 'permanent pen',
  25680. items: ['permanentpen']
  25681. },
  25682. {
  25683. name: 'comments',
  25684. items: ['addcomment']
  25685. }
  25686. ];
  25687. var renderFromBridge = function (bridgeBuilder, render) {
  25688. return function (spec, extras, editor) {
  25689. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  25690. return formatError(errInfo);
  25691. }).getOrDie();
  25692. return render(internal, extras, editor);
  25693. };
  25694. };
  25695. var types = {
  25696. button: renderFromBridge(createToolbarButton, function (s, extras) {
  25697. return renderToolbarButton(s, extras.backstage.shared.providers);
  25698. }),
  25699. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  25700. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  25701. }),
  25702. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  25703. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none());
  25704. }),
  25705. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  25706. return renderSplitButton(s, extras.backstage.shared);
  25707. }),
  25708. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  25709. var _a;
  25710. var buttons = editor.ui.registry.getAll().buttons;
  25711. var identify = function (toolbar) {
  25712. return identifyButtons(editor, {
  25713. buttons: buttons,
  25714. toolbar: toolbar,
  25715. allowToolbarGroups: false
  25716. }, extras, Optional.none());
  25717. };
  25718. var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  25719. switch (getToolbarMode(editor)) {
  25720. case ToolbarMode.floating:
  25721. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  25722. default:
  25723. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  25724. }
  25725. }),
  25726. styleSelectButton: function (editor, extras) {
  25727. return createStyleSelect(editor, extras.backstage);
  25728. },
  25729. fontsizeSelectButton: function (editor, extras) {
  25730. return createFontsizeSelect(editor, extras.backstage);
  25731. },
  25732. fontSelectButton: function (editor, extras) {
  25733. return createFontSelect(editor, extras.backstage);
  25734. },
  25735. formatButton: function (editor, extras) {
  25736. return createFormatSelect(editor, extras.backstage);
  25737. },
  25738. alignMenuButton: function (editor, extras) {
  25739. return createAlignSelect(editor, extras.backstage);
  25740. }
  25741. };
  25742. var extractFrom = function (spec, extras, editor) {
  25743. return get$e(types, spec.type).fold(function () {
  25744. console.error('skipping button defined by', spec);
  25745. return Optional.none();
  25746. }, function (render) {
  25747. return Optional.some(render(spec, extras, editor));
  25748. });
  25749. };
  25750. var bespokeButtons = {
  25751. styleselect: types.styleSelectButton,
  25752. fontsizeselect: types.fontsizeSelectButton,
  25753. fontselect: types.fontSelectButton,
  25754. formatselect: types.formatButton,
  25755. align: types.alignMenuButton
  25756. };
  25757. var removeUnusedDefaults = function (buttons) {
  25758. var filteredItemGroups = map$2(defaultToolbar, function (group) {
  25759. var items = filter$2(group.items, function (subItem) {
  25760. return has$2(buttons, subItem) || has$2(bespokeButtons, subItem);
  25761. });
  25762. return {
  25763. name: group.name,
  25764. items: items
  25765. };
  25766. });
  25767. return filter$2(filteredItemGroups, function (group) {
  25768. return group.items.length > 0;
  25769. });
  25770. };
  25771. var convertStringToolbar = function (strToolbar) {
  25772. var groupsStrings = strToolbar.split('|');
  25773. return map$2(groupsStrings, function (g) {
  25774. return { items: g.trim().split(' ') };
  25775. });
  25776. };
  25777. var isToolbarGroupSettingArray = function (toolbar) {
  25778. return isArrayOf(toolbar, function (t) {
  25779. return has$2(t, 'name') && has$2(t, 'items');
  25780. });
  25781. };
  25782. var createToolbar = function (toolbarConfig) {
  25783. var toolbar = toolbarConfig.toolbar;
  25784. var buttons = toolbarConfig.buttons;
  25785. if (toolbar === false) {
  25786. return [];
  25787. } else if (toolbar === undefined || toolbar === true) {
  25788. return removeUnusedDefaults(buttons);
  25789. } else if (isString(toolbar)) {
  25790. return convertStringToolbar(toolbar);
  25791. } else if (isToolbarGroupSettingArray(toolbar)) {
  25792. return toolbar;
  25793. } else {
  25794. console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  25795. return [];
  25796. }
  25797. };
  25798. var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  25799. return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  25800. return prefixes.bind(function (ps) {
  25801. return findMap(ps, function (prefix) {
  25802. return get$e(buttons, prefix + toolbarItem.toLowerCase());
  25803. });
  25804. });
  25805. }).fold(function () {
  25806. return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  25807. return r(editor, extras);
  25808. }).orThunk(function () {
  25809. return Optional.none();
  25810. });
  25811. }, function (spec) {
  25812. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  25813. console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  25814. return Optional.none();
  25815. } else {
  25816. return extractFrom(spec, extras, editor);
  25817. }
  25818. });
  25819. };
  25820. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  25821. var toolbarGroups = createToolbar(toolbarConfig);
  25822. var groups = map$2(toolbarGroups, function (group) {
  25823. var items = bind$3(group.items, function (toolbarItem) {
  25824. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  25825. });
  25826. return {
  25827. title: Optional.from(editor.translate(group.name)),
  25828. items: items
  25829. };
  25830. });
  25831. return filter$2(groups, function (group) {
  25832. return group.items.length > 0;
  25833. });
  25834. };
  25835. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  25836. var comp = uiComponents.outerContainer;
  25837. var toolbarConfig = rawUiConfig.toolbar;
  25838. var toolbarButtonsConfig = rawUiConfig.buttons;
  25839. if (isArrayOf(toolbarConfig, isString)) {
  25840. var toolbars = toolbarConfig.map(function (t) {
  25841. var config = {
  25842. toolbar: t,
  25843. buttons: toolbarButtonsConfig,
  25844. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  25845. };
  25846. return identifyButtons(editor, config, { backstage: backstage }, Optional.none());
  25847. });
  25848. OuterContainer.setToolbars(comp, toolbars);
  25849. } else {
  25850. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none()));
  25851. }
  25852. };
  25853. var detection = detect$1();
  25854. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  25855. var setupEvents$1 = function (editor, uiComponents) {
  25856. var dom = editor.dom;
  25857. var contentWindow = editor.getWin();
  25858. var initialDocEle = editor.getDoc().documentElement;
  25859. var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  25860. var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  25861. var resizeWindow = function () {
  25862. var outer = lastWindowDimensions.get();
  25863. if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) {
  25864. lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight));
  25865. fireResizeContent(editor);
  25866. }
  25867. };
  25868. var resizeDocument = function () {
  25869. var docEle = editor.getDoc().documentElement;
  25870. var inner = lastDocumentDimensions.get();
  25871. if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) {
  25872. lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight));
  25873. fireResizeContent(editor);
  25874. }
  25875. };
  25876. var scroll = function (e) {
  25877. return fireScrollContent(editor, e);
  25878. };
  25879. dom.bind(contentWindow, 'resize', resizeWindow);
  25880. dom.bind(contentWindow, 'scroll', scroll);
  25881. var elementLoad = capture(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument);
  25882. var mothership = uiComponents.uiMothership.element;
  25883. editor.on('hide', function () {
  25884. set$7(mothership, 'display', 'none');
  25885. });
  25886. editor.on('show', function () {
  25887. remove$6(mothership, 'display');
  25888. });
  25889. editor.on('NodeChange', resizeDocument);
  25890. editor.on('remove', function () {
  25891. elementLoad.unbind();
  25892. dom.unbind(contentWindow, 'resize', resizeWindow);
  25893. dom.unbind(contentWindow, 'scroll', scroll);
  25894. contentWindow = null;
  25895. });
  25896. };
  25897. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  25898. var lastToolbarWidth = Cell(0);
  25899. var outerContainer = uiComponents.outerContainer;
  25900. iframe(editor);
  25901. var eTargetNode = SugarElement.fromDom(args.targetNode);
  25902. var uiRoot = getContentContainer(getRootNode(eTargetNode));
  25903. attachSystemAfter(eTargetNode, uiComponents.mothership);
  25904. attachSystem(uiRoot, uiComponents.uiMothership);
  25905. editor.on('PostRender', function () {
  25906. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  25907. lastToolbarWidth.set(editor.getWin().innerWidth);
  25908. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  25909. OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar);
  25910. setupEvents$1(editor, uiComponents);
  25911. });
  25912. var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element');
  25913. if (isiOS12) {
  25914. setAll(socket.element, {
  25915. 'overflow': 'scroll',
  25916. '-webkit-overflow-scrolling': 'touch'
  25917. });
  25918. var limit = first(function () {
  25919. editor.fire('ScrollContent');
  25920. }, 20);
  25921. var unbinder = bind(socket.element, 'scroll', limit.throttle);
  25922. editor.on('remove', unbinder.unbind);
  25923. }
  25924. setupReadonlyModeSwitch(editor, uiComponents);
  25925. editor.addCommand('ToggleSidebar', function (_ui, value) {
  25926. OuterContainer.toggleSidebar(outerContainer, value);
  25927. editor.fire('ToggleSidebar');
  25928. });
  25929. editor.addQueryValueHandler('ToggleSidebar', function () {
  25930. return OuterContainer.whichSidebar(outerContainer);
  25931. });
  25932. var toolbarMode = getToolbarMode(editor);
  25933. var refreshDrawer = function () {
  25934. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  25935. };
  25936. if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  25937. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  25938. var width = editor.getWin().innerWidth;
  25939. if (width !== lastToolbarWidth.get()) {
  25940. refreshDrawer();
  25941. lastToolbarWidth.set(width);
  25942. }
  25943. });
  25944. }
  25945. var api = {
  25946. enable: function () {
  25947. broadcastReadonly(uiComponents, false);
  25948. },
  25949. disable: function () {
  25950. broadcastReadonly(uiComponents, true);
  25951. },
  25952. isDisabled: function () {
  25953. return Disabling.isDisabled(outerContainer);
  25954. }
  25955. };
  25956. return {
  25957. iframeContainer: socket.element.dom,
  25958. editorContainer: outerContainer.element.dom,
  25959. api: api
  25960. };
  25961. };
  25962. var Iframe = /*#__PURE__*/Object.freeze({
  25963. __proto__: null,
  25964. render: render$1
  25965. });
  25966. var parseToInt = function (val) {
  25967. var re = /^[0-9\.]+(|px)$/i;
  25968. if (re.test('' + val)) {
  25969. return Optional.some(parseInt('' + val, 10));
  25970. }
  25971. return Optional.none();
  25972. };
  25973. var numToPx = function (val) {
  25974. return isNumber(val) ? val + 'px' : val;
  25975. };
  25976. var calcCappedSize = function (size, minSize, maxSize) {
  25977. var minOverride = minSize.filter(function (min) {
  25978. return size < min;
  25979. });
  25980. var maxOverride = maxSize.filter(function (max) {
  25981. return size > max;
  25982. });
  25983. return minOverride.or(maxOverride).getOr(size);
  25984. };
  25985. var getHeight = function (editor) {
  25986. var baseHeight = getHeightSetting(editor);
  25987. var minHeight = getMinHeightSetting(editor);
  25988. var maxHeight = getMaxHeightSetting(editor);
  25989. return parseToInt(baseHeight).map(function (height) {
  25990. return calcCappedSize(height, minHeight, maxHeight);
  25991. });
  25992. };
  25993. var getHeightWithFallback = function (editor) {
  25994. var height = getHeight(editor);
  25995. return height.getOr(getHeightSetting(editor));
  25996. };
  25997. var getWidth = function (editor) {
  25998. var baseWidth = getWidthSetting(editor);
  25999. var minWidth = getMinWidthSetting(editor);
  26000. var maxWidth = getMaxWidthSetting(editor);
  26001. return parseToInt(baseWidth).map(function (width) {
  26002. return calcCappedSize(width, minWidth, maxWidth);
  26003. });
  26004. };
  26005. var getWidthWithFallback = function (editor) {
  26006. var width = getWidth(editor);
  26007. return width.getOr(getWidthSetting(editor));
  26008. };
  26009. var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
  26010. var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26011. var DOM = global$b.DOM;
  26012. var useFixedToolbarContainer = useFixedContainer(editor);
  26013. var isSticky = isStickyToolbar(editor);
  26014. var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor));
  26015. var headerBackstage = backstage.shared.header;
  26016. var isPositionedAtTop = headerBackstage.isPositionedAtTop;
  26017. var toolbarMode = getToolbarMode(editor);
  26018. var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  26019. var visible = Cell(false);
  26020. var isVisible = function () {
  26021. return visible.get() && !editor.removed;
  26022. };
  26023. var calcToolbarOffset = function (toolbar) {
  26024. return isSplitToolbar ? toolbar.fold(constant$1(0), function (tbar) {
  26025. return tbar.components().length > 1 ? get$b(tbar.components()[1].element) : 0;
  26026. }) : 0;
  26027. };
  26028. var calcMode = function (container) {
  26029. switch (getToolbarLocation(editor)) {
  26030. case ToolbarLocation.auto:
  26031. var toolbar_1 = OuterContainer.getToolbar(outerContainer);
  26032. var offset = calcToolbarOffset(toolbar_1);
  26033. var toolbarHeight = get$b(container.element) - offset;
  26034. var targetBounds = box$1(targetElm);
  26035. var roomAtTop = targetBounds.y > toolbarHeight;
  26036. if (roomAtTop) {
  26037. return 'top';
  26038. } else {
  26039. var doc = documentElement(targetElm);
  26040. var docHeight = Math.max(doc.dom.scrollHeight, get$b(doc));
  26041. var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  26042. if (roomAtBottom) {
  26043. return 'bottom';
  26044. } else {
  26045. var winBounds = win();
  26046. var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  26047. return isRoomAtBottomViewport ? 'bottom' : 'top';
  26048. }
  26049. }
  26050. case ToolbarLocation.bottom:
  26051. return 'bottom';
  26052. case ToolbarLocation.top:
  26053. default:
  26054. return 'top';
  26055. }
  26056. };
  26057. var setupMode = function (mode) {
  26058. var container = floatContainer.get();
  26059. Docking.setModes(container, [mode]);
  26060. headerBackstage.setDockingMode(mode);
  26061. var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  26062. set$8(container.element, Attribute, verticalDir);
  26063. };
  26064. var updateChromeWidth = function () {
  26065. var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  26066. var bodyMargin = parseToInt(get$c(body(), 'margin-left')).getOr(0);
  26067. return get$a(body()) - absolute$3(targetElm).left + bodyMargin;
  26068. });
  26069. set$7(floatContainer.get().element, 'max-width', maxWidth + 'px');
  26070. };
  26071. var updateChromePosition = function () {
  26072. var toolbar = OuterContainer.getToolbar(outerContainer);
  26073. var offset = calcToolbarOffset(toolbar);
  26074. var targetBounds = box$1(targetElm);
  26075. var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$b(floatContainer.get().element) + offset, 0) : targetBounds.bottom;
  26076. setAll(outerContainer.element, {
  26077. position: 'absolute',
  26078. top: Math.round(top) + 'px',
  26079. left: Math.round(targetBounds.x) + 'px'
  26080. });
  26081. };
  26082. var repositionPopups$1 = function () {
  26083. uiMothership.broadcastOn([repositionPopups()], {});
  26084. };
  26085. var updateChromeUi = function (resetDocking) {
  26086. if (resetDocking === void 0) {
  26087. resetDocking = false;
  26088. }
  26089. if (!isVisible()) {
  26090. return;
  26091. }
  26092. if (!useFixedToolbarContainer) {
  26093. updateChromeWidth();
  26094. }
  26095. if (isSplitToolbar) {
  26096. OuterContainer.refreshToolbar(outerContainer);
  26097. }
  26098. if (!useFixedToolbarContainer) {
  26099. updateChromePosition();
  26100. }
  26101. if (isSticky) {
  26102. var floatContainerComp = floatContainer.get();
  26103. resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  26104. }
  26105. repositionPopups$1();
  26106. };
  26107. var updateMode = function (updateUi) {
  26108. if (updateUi === void 0) {
  26109. updateUi = true;
  26110. }
  26111. if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  26112. return;
  26113. }
  26114. var currentMode = headerBackstage.getDockingMode();
  26115. var newMode = calcMode(floatContainer.get());
  26116. if (newMode !== currentMode) {
  26117. setupMode(newMode);
  26118. if (updateUi) {
  26119. updateChromeUi(true);
  26120. }
  26121. }
  26122. };
  26123. var show = function () {
  26124. visible.set(true);
  26125. set$7(outerContainer.element, 'display', 'flex');
  26126. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  26127. remove$6(uiMothership.element, 'display');
  26128. updateMode(false);
  26129. updateChromeUi();
  26130. };
  26131. var hide = function () {
  26132. visible.set(false);
  26133. if (uiComponents.outerContainer) {
  26134. set$7(outerContainer.element, 'display', 'none');
  26135. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  26136. }
  26137. set$7(uiMothership.element, 'display', 'none');
  26138. };
  26139. return {
  26140. isVisible: isVisible,
  26141. isPositionedAtTop: isPositionedAtTop,
  26142. show: show,
  26143. hide: hide,
  26144. update: updateChromeUi,
  26145. updateMode: updateMode,
  26146. repositionPopups: repositionPopups$1
  26147. };
  26148. };
  26149. var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
  26150. var bounds = box$1(targetElm);
  26151. return {
  26152. pos: isToolbarTop ? bounds.y : bounds.bottom,
  26153. bounds: bounds
  26154. };
  26155. };
  26156. var setupEvents = function (editor, targetElm, ui, toolbarPersist) {
  26157. var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  26158. var resizeContent = function (e) {
  26159. var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
  26160. var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
  26161. var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  26162. prevPosAndBounds.set({
  26163. pos: pos,
  26164. bounds: bounds
  26165. });
  26166. if (hasResized) {
  26167. fireResizeContent(editor, e);
  26168. }
  26169. if (ui.isVisible()) {
  26170. if (prevPos !== pos) {
  26171. ui.update(true);
  26172. } else if (hasResized) {
  26173. ui.updateMode();
  26174. ui.repositionPopups();
  26175. }
  26176. }
  26177. };
  26178. if (!toolbarPersist) {
  26179. editor.on('activate', ui.show);
  26180. editor.on('deactivate', ui.hide);
  26181. }
  26182. editor.on('SkinLoaded ResizeWindow', function () {
  26183. return ui.update(true);
  26184. });
  26185. editor.on('NodeChange keydown', function (e) {
  26186. global$f.requestAnimationFrame(function () {
  26187. return resizeContent(e);
  26188. });
  26189. });
  26190. editor.on('ScrollWindow', function () {
  26191. return ui.updateMode();
  26192. });
  26193. var elementLoad = unbindable();
  26194. elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), 'load', resizeContent));
  26195. editor.on('remove', function () {
  26196. elementLoad.clear();
  26197. });
  26198. };
  26199. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26200. var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26201. var floatContainer = Cell(null);
  26202. var targetElm = SugarElement.fromDom(args.targetNode);
  26203. var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  26204. var toolbarPersist = isToolbarPersist(editor);
  26205. inline(editor);
  26206. var render = function () {
  26207. if (floatContainer.get()) {
  26208. ui.show();
  26209. return;
  26210. }
  26211. floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  26212. var uiContainer = getUiContainer(editor);
  26213. attachSystem(uiContainer, mothership);
  26214. attachSystem(uiContainer, uiMothership);
  26215. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26216. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26217. ui.show();
  26218. setupEvents(editor, targetElm, ui, toolbarPersist);
  26219. editor.nodeChanged();
  26220. };
  26221. var delayedRender = function () {
  26222. return global$f.setEditorTimeout(editor, render, 0);
  26223. };
  26224. editor.on('show', render);
  26225. editor.on('hide', ui.hide);
  26226. if (!toolbarPersist) {
  26227. editor.on('focus', delayedRender);
  26228. editor.on('blur', ui.hide);
  26229. }
  26230. editor.on('init', function () {
  26231. if (editor.hasFocus() || toolbarPersist) {
  26232. delayedRender();
  26233. }
  26234. });
  26235. setupReadonlyModeSwitch(editor, uiComponents);
  26236. var api = {
  26237. show: function () {
  26238. ui.show();
  26239. },
  26240. hide: function () {
  26241. ui.hide();
  26242. },
  26243. enable: function () {
  26244. broadcastReadonly(uiComponents, false);
  26245. },
  26246. disable: function () {
  26247. broadcastReadonly(uiComponents, true);
  26248. },
  26249. isDisabled: function () {
  26250. return Disabling.isDisabled(outerContainer);
  26251. }
  26252. };
  26253. return {
  26254. editorContainer: outerContainer.element.dom,
  26255. api: api
  26256. };
  26257. };
  26258. var Inline = /*#__PURE__*/Object.freeze({
  26259. __proto__: null,
  26260. render: render
  26261. });
  26262. var showContextToolbarEvent = 'contexttoolbar-show';
  26263. var hideContextToolbarEvent = 'contexttoolbar-hide';
  26264. var getFormApi = function (input) {
  26265. return {
  26266. hide: function () {
  26267. return emit(input, sandboxClose());
  26268. },
  26269. getValue: function () {
  26270. return Representing.getValue(input);
  26271. }
  26272. };
  26273. };
  26274. var runOnExecute = function (memInput, original) {
  26275. return run$1(internalToolbarButtonExecute, function (comp, se) {
  26276. var input = memInput.get(comp);
  26277. var formApi = getFormApi(input);
  26278. original.onAction(formApi, se.event.buttonApi);
  26279. });
  26280. };
  26281. var renderContextButton = function (memInput, button, extras) {
  26282. var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  26283. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  26284. type: 'button',
  26285. onAction: noop
  26286. })));
  26287. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  26288. };
  26289. var renderContextToggleButton = function (memInput, button, extras) {
  26290. var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']);
  26291. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  26292. type: 'togglebutton',
  26293. onAction: noop
  26294. })));
  26295. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]);
  26296. };
  26297. var generateOne = function (memInput, button, providersBackstage) {
  26298. var extras = { backstage: { shared: { providers: providersBackstage } } };
  26299. if (button.type === 'contextformtogglebutton') {
  26300. return renderContextToggleButton(memInput, button, extras);
  26301. } else {
  26302. return renderContextButton(memInput, button, extras);
  26303. }
  26304. };
  26305. var generate = function (memInput, buttons, providersBackstage) {
  26306. var mementos = map$2(buttons, function (button) {
  26307. return record(generateOne(memInput, button, providersBackstage));
  26308. });
  26309. var asSpecs = function () {
  26310. return map$2(mementos, function (mem) {
  26311. return mem.asSpec();
  26312. });
  26313. };
  26314. var findPrimary = function (compInSystem) {
  26315. return findMap(buttons, function (button, i) {
  26316. if (button.primary) {
  26317. return Optional.from(mementos[i]).bind(function (mem) {
  26318. return mem.getOpt(compInSystem);
  26319. }).filter(not(Disabling.isDisabled));
  26320. } else {
  26321. return Optional.none();
  26322. }
  26323. });
  26324. };
  26325. return {
  26326. asSpecs: asSpecs,
  26327. findPrimary: findPrimary
  26328. };
  26329. };
  26330. var buildInitGroups = function (ctx, providers) {
  26331. var inputAttributes = ctx.label.fold(function () {
  26332. return {};
  26333. }, function (label) {
  26334. return { 'aria-label': label };
  26335. });
  26336. var memInput = record(Input.sketch({
  26337. inputClasses: [
  26338. 'tox-toolbar-textfield',
  26339. 'tox-toolbar-nav-js'
  26340. ],
  26341. data: ctx.initValue(),
  26342. inputAttributes: inputAttributes,
  26343. selectOnFocus: true,
  26344. inputBehaviours: derive$1([Keying.config({
  26345. mode: 'special',
  26346. onEnter: function (input) {
  26347. return commands.findPrimary(input).map(function (primary) {
  26348. emitExecute(primary);
  26349. return true;
  26350. });
  26351. },
  26352. onLeft: function (comp, se) {
  26353. se.cut();
  26354. return Optional.none();
  26355. },
  26356. onRight: function (comp, se) {
  26357. se.cut();
  26358. return Optional.none();
  26359. }
  26360. })])
  26361. }));
  26362. var commands = generate(memInput, ctx.commands, providers);
  26363. return [
  26364. {
  26365. title: Optional.none(),
  26366. items: [memInput.asSpec()]
  26367. },
  26368. {
  26369. title: Optional.none(),
  26370. items: commands.asSpecs()
  26371. }
  26372. ];
  26373. };
  26374. var renderContextForm = function (toolbarType, ctx, providers) {
  26375. return renderToolbar({
  26376. type: toolbarType,
  26377. uid: generate$6('context-toolbar'),
  26378. initGroups: buildInitGroups(ctx, providers),
  26379. onEscape: Optional.none,
  26380. cyclicKeying: true,
  26381. providers: providers
  26382. });
  26383. };
  26384. var ContextForm = {
  26385. renderContextForm: renderContextForm,
  26386. buildInitGroups: buildInitGroups
  26387. };
  26388. var isVerticalOverlap = function (a, b, threshold) {
  26389. if (threshold === void 0) {
  26390. threshold = 0.01;
  26391. }
  26392. return b.bottom - a.y >= threshold && a.bottom - b.y >= threshold;
  26393. };
  26394. var getRangeRect = function (rng) {
  26395. var rect = rng.getBoundingClientRect();
  26396. if (rect.height <= 0 && rect.width <= 0) {
  26397. var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element;
  26398. var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1);
  26399. return elm.filter(isElement$2).map(function (e) {
  26400. return e.dom.getBoundingClientRect();
  26401. }).getOr(rect);
  26402. } else {
  26403. return rect;
  26404. }
  26405. };
  26406. var getSelectionBounds = function (editor) {
  26407. var rng = editor.selection.getRng();
  26408. var rect = getRangeRect(rng);
  26409. if (editor.inline) {
  26410. var scroll_1 = get$9();
  26411. return bounds(scroll_1.left + rect.left, scroll_1.top + rect.top, rect.width, rect.height);
  26412. } else {
  26413. var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody()));
  26414. return bounds(bodyPos.x + rect.left, bodyPos.y + rect.top, rect.width, rect.height);
  26415. }
  26416. };
  26417. var getAnchorElementBounds = function (editor, lastElement) {
  26418. return lastElement.filter(inBody).map(absolute$2).getOrThunk(function () {
  26419. return getSelectionBounds(editor);
  26420. });
  26421. };
  26422. var getHorizontalBounds = function (contentAreaBox, viewportBounds, margin) {
  26423. var x = Math.max(contentAreaBox.x + margin, viewportBounds.x);
  26424. var right = Math.min(contentAreaBox.right - margin, viewportBounds.right);
  26425. return {
  26426. x: x,
  26427. width: right - x
  26428. };
  26429. };
  26430. var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) {
  26431. var container = SugarElement.fromDom(editor.getContainer());
  26432. var header = descendant(container, '.tox-editor-header').getOr(container);
  26433. var headerBox = box$1(header);
  26434. var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  26435. var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  26436. if (editor.inline && isToolbarAbove) {
  26437. return {
  26438. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  26439. bottom: viewportBounds.bottom
  26440. };
  26441. }
  26442. if (editor.inline && !isToolbarAbove) {
  26443. return {
  26444. y: viewportBounds.y,
  26445. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  26446. };
  26447. }
  26448. var containerBounds = toolbarType === 'line' ? box$1(container) : contentAreaBox;
  26449. if (isToolbarAbove) {
  26450. return {
  26451. y: Math.max(headerBox.bottom + margin, viewportBounds.y),
  26452. bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom)
  26453. };
  26454. }
  26455. return {
  26456. y: Math.max(containerBounds.y + margin, viewportBounds.y),
  26457. bottom: Math.min(headerBox.y - margin, viewportBounds.bottom)
  26458. };
  26459. };
  26460. var getContextToolbarBounds = function (editor, sharedBackstage, toolbarType, margin) {
  26461. if (margin === void 0) {
  26462. margin = 0;
  26463. }
  26464. var viewportBounds = getBounds$3(window);
  26465. var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer()));
  26466. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  26467. var _a = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x = _a.x, width = _a.width;
  26468. if (editor.inline && !toolbarOrMenubarEnabled) {
  26469. return bounds(x, viewportBounds.y, width, viewportBounds.height);
  26470. } else {
  26471. var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  26472. var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y = _b.y, bottom = _b.bottom;
  26473. return bounds(x, y, width, bottom - y);
  26474. }
  26475. };
  26476. var bubbleSize$1 = 12;
  26477. var bubbleAlignments$1 = {
  26478. valignCentre: [],
  26479. alignCentre: [],
  26480. alignLeft: ['tox-pop--align-left'],
  26481. alignRight: ['tox-pop--align-right'],
  26482. right: ['tox-pop--right'],
  26483. left: ['tox-pop--left'],
  26484. bottom: ['tox-pop--bottom'],
  26485. top: ['tox-pop--top'],
  26486. inset: ['tox-pop--inset']
  26487. };
  26488. var anchorOverrides = {
  26489. maxHeightFunction: expandable$1(),
  26490. maxWidthFunction: expandable()
  26491. };
  26492. var isEntireElementSelected = function (editor, elem) {
  26493. var rng = editor.selection.getRng();
  26494. var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset);
  26495. return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem);
  26496. };
  26497. var preservePosition = function (elem, position, f) {
  26498. var currentPosition = getRaw(elem, 'position');
  26499. set$7(elem, 'position', position);
  26500. var result = f(elem);
  26501. currentPosition.each(function (pos) {
  26502. return set$7(elem, 'position', pos);
  26503. });
  26504. return result;
  26505. };
  26506. var shouldUseInsetLayouts = function (position) {
  26507. return position === 'node';
  26508. };
  26509. var determineInsetLayout = function (editor, contextbar, elem, data, bounds) {
  26510. var selectionBounds = getSelectionBounds(editor);
  26511. var isSameAnchorElement = data.lastElement().exists(function (prev) {
  26512. return eq(elem, prev);
  26513. });
  26514. if (isEntireElementSelected(editor, elem)) {
  26515. return isSameAnchorElement ? preserve : north;
  26516. } else if (isSameAnchorElement) {
  26517. return preservePosition(contextbar, data.getMode(), function () {
  26518. var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar));
  26519. return isOverlapping && !data.isReposition() ? flip$2 : preserve;
  26520. });
  26521. } else {
  26522. var yBounds = data.getMode() === 'fixed' ? bounds.y + get$9().top : bounds.y;
  26523. var contextbarHeight = get$b(contextbar) + bubbleSize$1;
  26524. return yBounds + contextbarHeight <= selectionBounds.y ? north : south;
  26525. }
  26526. };
  26527. var getAnchorSpec$2 = function (editor, mobile, data, position) {
  26528. var smartInsetLayout = function (elem) {
  26529. return function (anchor, element, bubbles, placee, bounds) {
  26530. var layout = determineInsetLayout(editor, placee, elem, data, bounds);
  26531. var newAnchor = __assign(__assign({}, anchor), {
  26532. y: bounds.y,
  26533. height: bounds.height
  26534. });
  26535. return __assign(__assign({}, layout(newAnchor, element, bubbles, placee, bounds)), { alwaysFit: true });
  26536. };
  26537. };
  26538. var getInsetLayouts = function (elem) {
  26539. return shouldUseInsetLayouts(position) ? [smartInsetLayout(elem)] : [];
  26540. };
  26541. var desktopAnchorSpecLayouts = {
  26542. onLtr: function (elem) {
  26543. return [
  26544. north$2,
  26545. south$2,
  26546. northeast$2,
  26547. southeast$2,
  26548. northwest$2,
  26549. southwest$2
  26550. ].concat(getInsetLayouts(elem));
  26551. },
  26552. onRtl: function (elem) {
  26553. return [
  26554. north$2,
  26555. south$2,
  26556. northwest$2,
  26557. southwest$2,
  26558. northeast$2,
  26559. southeast$2
  26560. ].concat(getInsetLayouts(elem));
  26561. }
  26562. };
  26563. var mobileAnchorSpecLayouts = {
  26564. onLtr: function (elem) {
  26565. return [
  26566. south$2,
  26567. southeast$2,
  26568. southwest$2,
  26569. northeast$2,
  26570. northwest$2,
  26571. north$2
  26572. ].concat(getInsetLayouts(elem));
  26573. },
  26574. onRtl: function (elem) {
  26575. return [
  26576. south$2,
  26577. southwest$2,
  26578. southeast$2,
  26579. northwest$2,
  26580. northeast$2,
  26581. north$2
  26582. ].concat(getInsetLayouts(elem));
  26583. }
  26584. };
  26585. return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts;
  26586. };
  26587. var getAnchorLayout = function (editor, position, isTouch, data) {
  26588. if (position === 'line') {
  26589. return {
  26590. bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1),
  26591. layouts: {
  26592. onLtr: function () {
  26593. return [east$2];
  26594. },
  26595. onRtl: function () {
  26596. return [west$2];
  26597. }
  26598. },
  26599. overrides: anchorOverrides
  26600. };
  26601. } else {
  26602. return {
  26603. bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1),
  26604. layouts: getAnchorSpec$2(editor, isTouch, data, position),
  26605. overrides: anchorOverrides
  26606. };
  26607. }
  26608. };
  26609. var matchTargetWith = function (elem, candidates) {
  26610. var ctxs = filter$2(candidates, function (toolbarApi) {
  26611. return toolbarApi.predicate(elem.dom);
  26612. });
  26613. var _a = partition$3(ctxs, function (t) {
  26614. return t.type === 'contexttoolbar';
  26615. }), pass = _a.pass, fail = _a.fail;
  26616. return {
  26617. contextToolbars: pass,
  26618. contextForms: fail
  26619. };
  26620. };
  26621. var filterByPositionForStartNode = function (toolbars) {
  26622. if (toolbars.length <= 1) {
  26623. return toolbars;
  26624. } else {
  26625. var doesPositionExist = function (value) {
  26626. return exists(toolbars, function (t) {
  26627. return t.position === value;
  26628. });
  26629. };
  26630. var filterToolbarsByPosition = function (value) {
  26631. return filter$2(toolbars, function (t) {
  26632. return t.position === value;
  26633. });
  26634. };
  26635. var hasSelectionToolbars = doesPositionExist('selection');
  26636. var hasNodeToolbars = doesPositionExist('node');
  26637. if (hasSelectionToolbars || hasNodeToolbars) {
  26638. if (hasNodeToolbars && hasSelectionToolbars) {
  26639. var nodeToolbars = filterToolbarsByPosition('node');
  26640. var selectionToolbars = map$2(filterToolbarsByPosition('selection'), function (t) {
  26641. return __assign(__assign({}, t), { position: 'node' });
  26642. });
  26643. return nodeToolbars.concat(selectionToolbars);
  26644. } else {
  26645. return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  26646. }
  26647. } else {
  26648. return filterToolbarsByPosition('line');
  26649. }
  26650. }
  26651. };
  26652. var filterByPositionForAncestorNode = function (toolbars) {
  26653. if (toolbars.length <= 1) {
  26654. return toolbars;
  26655. } else {
  26656. var findPosition_1 = function (value) {
  26657. return find$5(toolbars, function (t) {
  26658. return t.position === value;
  26659. });
  26660. };
  26661. var basePosition = findPosition_1('selection').orThunk(function () {
  26662. return findPosition_1('node');
  26663. }).orThunk(function () {
  26664. return findPosition_1('line');
  26665. }).map(function (t) {
  26666. return t.position;
  26667. });
  26668. return basePosition.fold(function () {
  26669. return [];
  26670. }, function (pos) {
  26671. return filter$2(toolbars, function (t) {
  26672. return t.position === pos;
  26673. });
  26674. });
  26675. }
  26676. };
  26677. var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
  26678. var nodeMatches = matchTargetWith(elem, nodeCandidates);
  26679. if (nodeMatches.contextForms.length > 0) {
  26680. return Optional.some({
  26681. elem: elem,
  26682. toolbars: [nodeMatches.contextForms[0]]
  26683. });
  26684. } else {
  26685. var editorMatches = matchTargetWith(elem, editorCandidates);
  26686. if (editorMatches.contextForms.length > 0) {
  26687. return Optional.some({
  26688. elem: elem,
  26689. toolbars: [editorMatches.contextForms[0]]
  26690. });
  26691. } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  26692. var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  26693. return Optional.some({
  26694. elem: elem,
  26695. toolbars: toolbars
  26696. });
  26697. } else {
  26698. return Optional.none();
  26699. }
  26700. }
  26701. };
  26702. var matchAncestor = function (isRoot, startNode, scopes) {
  26703. if (isRoot(startNode)) {
  26704. return Optional.none();
  26705. } else {
  26706. return ancestor$2(startNode, function (ancestorElem) {
  26707. if (isElement$2(ancestorElem)) {
  26708. var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
  26709. var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  26710. return toolbars.length > 0 ? Optional.some({
  26711. elem: ancestorElem,
  26712. toolbars: toolbars
  26713. }) : Optional.none();
  26714. } else {
  26715. return Optional.none();
  26716. }
  26717. }, isRoot);
  26718. }
  26719. };
  26720. var lookup$1 = function (scopes, editor) {
  26721. var rootElem = SugarElement.fromDom(editor.getBody());
  26722. var isRoot = function (elem) {
  26723. return eq(elem, rootElem);
  26724. };
  26725. var isOutsideRoot = function (startNode) {
  26726. return !isRoot(startNode) && !contains(rootElem, startNode);
  26727. };
  26728. var startNode = SugarElement.fromDom(editor.selection.getNode());
  26729. if (isOutsideRoot(startNode)) {
  26730. return Optional.none();
  26731. }
  26732. return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
  26733. return matchAncestor(isRoot, startNode, scopes);
  26734. });
  26735. };
  26736. var categorise = function (contextToolbars, navigate) {
  26737. var forms = {};
  26738. var inNodeScope = [];
  26739. var inEditorScope = [];
  26740. var formNavigators = {};
  26741. var lookupTable = {};
  26742. var registerForm = function (key, toolbarSpec) {
  26743. var contextForm = getOrDie(createContextForm(toolbarSpec));
  26744. forms[key] = contextForm;
  26745. contextForm.launch.map(function (launch) {
  26746. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), {
  26747. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  26748. onAction: function () {
  26749. navigate(contextForm);
  26750. }
  26751. });
  26752. });
  26753. if (contextForm.scope === 'editor') {
  26754. inEditorScope.push(contextForm);
  26755. } else {
  26756. inNodeScope.push(contextForm);
  26757. }
  26758. lookupTable[key] = contextForm;
  26759. };
  26760. var registerToolbar = function (key, toolbarSpec) {
  26761. createContextToolbar(toolbarSpec).each(function (contextToolbar) {
  26762. if (toolbarSpec.scope === 'editor') {
  26763. inEditorScope.push(contextToolbar);
  26764. } else {
  26765. inNodeScope.push(contextToolbar);
  26766. }
  26767. lookupTable[key] = contextToolbar;
  26768. });
  26769. };
  26770. var keys$1 = keys(contextToolbars);
  26771. each$1(keys$1, function (key) {
  26772. var toolbarApi = contextToolbars[key];
  26773. if (toolbarApi.type === 'contextform') {
  26774. registerForm(key, toolbarApi);
  26775. } else if (toolbarApi.type === 'contexttoolbar') {
  26776. registerToolbar(key, toolbarApi);
  26777. }
  26778. });
  26779. return {
  26780. forms: forms,
  26781. inNodeScope: inNodeScope,
  26782. inEditorScope: inEditorScope,
  26783. lookupTable: lookupTable,
  26784. formNavigators: formNavigators
  26785. };
  26786. };
  26787. var forwardSlideEvent = generate$6('forward-slide');
  26788. var backSlideEvent = generate$6('backward-slide');
  26789. var changeSlideEvent = generate$6('change-slide-event');
  26790. var resizingClass = 'tox-pop--resizing';
  26791. var renderContextToolbar = function (spec) {
  26792. var stack = Cell([]);
  26793. return InlineView.sketch({
  26794. dom: {
  26795. tag: 'div',
  26796. classes: ['tox-pop']
  26797. },
  26798. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  26799. onShow: function (comp) {
  26800. stack.set([]);
  26801. InlineView.getContent(comp).each(function (c) {
  26802. remove$6(c.element, 'visibility');
  26803. });
  26804. remove$2(comp.element, resizingClass);
  26805. remove$6(comp.element, 'width');
  26806. },
  26807. inlineBehaviours: derive$1([
  26808. config('context-toolbar-events', [
  26809. runOnSource(transitionend(), function (comp, se) {
  26810. if (se.event.raw.propertyName === 'width') {
  26811. remove$2(comp.element, resizingClass);
  26812. remove$6(comp.element, 'width');
  26813. }
  26814. }),
  26815. run$1(changeSlideEvent, function (comp, se) {
  26816. var elem = comp.element;
  26817. remove$6(elem, 'width');
  26818. var currentWidth = get$a(elem);
  26819. InlineView.setContent(comp, se.event.contents);
  26820. add$2(elem, resizingClass);
  26821. var newWidth = get$a(elem);
  26822. set$7(elem, 'width', currentWidth + 'px');
  26823. InlineView.getContent(comp).each(function (newContents) {
  26824. se.event.focus.bind(function (f) {
  26825. focus$3(f);
  26826. return search(elem);
  26827. }).orThunk(function () {
  26828. Keying.focusIn(newContents);
  26829. return active(getRootNode(elem));
  26830. });
  26831. });
  26832. global$f.setTimeout(function () {
  26833. set$7(comp.element, 'width', newWidth + 'px');
  26834. }, 0);
  26835. }),
  26836. run$1(forwardSlideEvent, function (comp, se) {
  26837. InlineView.getContent(comp).each(function (oldContents) {
  26838. stack.set(stack.get().concat([{
  26839. bar: oldContents,
  26840. focus: active(getRootNode(comp.element))
  26841. }]));
  26842. });
  26843. emitWith(comp, changeSlideEvent, {
  26844. contents: se.event.forwardContents,
  26845. focus: Optional.none()
  26846. });
  26847. }),
  26848. run$1(backSlideEvent, function (comp, _se) {
  26849. last$2(stack.get()).each(function (last) {
  26850. stack.set(stack.get().slice(0, stack.get().length - 1));
  26851. emitWith(comp, changeSlideEvent, {
  26852. contents: premade(last.bar),
  26853. focus: last.focus
  26854. });
  26855. });
  26856. })
  26857. ]),
  26858. Keying.config({
  26859. mode: 'special',
  26860. onEscape: function (comp) {
  26861. return last$2(stack.get()).fold(function () {
  26862. return spec.onEscape();
  26863. }, function (_) {
  26864. emit(comp, backSlideEvent);
  26865. return Optional.some(true);
  26866. });
  26867. }
  26868. })
  26869. ]),
  26870. lazySink: function () {
  26871. return Result.value(spec.sink);
  26872. }
  26873. });
  26874. };
  26875. var transitionClass = 'tox-pop--transition';
  26876. var register$7 = function (editor, registryContextToolbars, sink, extras) {
  26877. var backstage = extras.backstage;
  26878. var sharedBackstage = backstage.shared;
  26879. var isTouch = detect$1().deviceType.isTouch;
  26880. var lastElement = value$1();
  26881. var lastTrigger = value$1();
  26882. var lastContextPosition = value$1();
  26883. var contextbar = build$1(renderContextToolbar({
  26884. sink: sink,
  26885. onEscape: function () {
  26886. editor.focus();
  26887. return Optional.some(true);
  26888. }
  26889. }));
  26890. var getBounds = function () {
  26891. var position = lastContextPosition.get().getOr('node');
  26892. var margin = shouldUseInsetLayouts(position) ? 1 : 0;
  26893. return getContextToolbarBounds(editor, sharedBackstage, position, margin);
  26894. };
  26895. var canLaunchToolbar = function () {
  26896. return !editor.removed && !(isTouch() && backstage.isContextMenuOpen());
  26897. };
  26898. var isSameLaunchElement = function (elem) {
  26899. return is$1(lift2(elem, lastElement.get(), eq), true);
  26900. };
  26901. var shouldContextToolbarHide = function () {
  26902. if (!canLaunchToolbar()) {
  26903. return true;
  26904. } else {
  26905. var contextToolbarBounds = getBounds();
  26906. var anchorBounds = is$1(lastContextPosition.get(), 'node') ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor);
  26907. return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds);
  26908. }
  26909. };
  26910. var close = function () {
  26911. lastElement.clear();
  26912. lastTrigger.clear();
  26913. lastContextPosition.clear();
  26914. InlineView.hide(contextbar);
  26915. };
  26916. var hideOrRepositionIfNecessary = function () {
  26917. if (InlineView.isOpen(contextbar)) {
  26918. var contextBarEle = contextbar.element;
  26919. remove$6(contextBarEle, 'display');
  26920. if (shouldContextToolbarHide()) {
  26921. set$7(contextBarEle, 'display', 'none');
  26922. } else {
  26923. lastTrigger.set(0);
  26924. InlineView.reposition(contextbar);
  26925. }
  26926. }
  26927. };
  26928. var wrapInPopDialog = function (toolbarSpec) {
  26929. return {
  26930. dom: {
  26931. tag: 'div',
  26932. classes: ['tox-pop__dialog']
  26933. },
  26934. components: [toolbarSpec],
  26935. behaviours: derive$1([
  26936. Keying.config({ mode: 'acyclic' }),
  26937. config('pop-dialog-wrap-events', [
  26938. runOnAttached(function (comp) {
  26939. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  26940. return Keying.focusIn(comp);
  26941. });
  26942. }),
  26943. runOnDetached(function (_comp) {
  26944. editor.shortcuts.remove('ctrl+F9');
  26945. })
  26946. ])
  26947. ])
  26948. };
  26949. };
  26950. var getScopes = cached(function () {
  26951. return categorise(registryContextToolbars, function (toolbarApi) {
  26952. var alloySpec = buildToolbar([toolbarApi]);
  26953. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  26954. });
  26955. });
  26956. var buildContextToolbarGroups = function (allButtons, ctx) {
  26957. return identifyButtons(editor, {
  26958. buttons: allButtons,
  26959. toolbar: ctx.items,
  26960. allowToolbarGroups: false
  26961. }, extras, Optional.some(['form:']));
  26962. };
  26963. var buildContextFormGroups = function (ctx, providers) {
  26964. return ContextForm.buildInitGroups(ctx, providers);
  26965. };
  26966. var buildToolbar = function (toolbars) {
  26967. var buttons = editor.ui.registry.getAll().buttons;
  26968. var scopes = getScopes();
  26969. var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  26970. var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  26971. var initGroups = flatten(map$2(toolbars, function (ctx) {
  26972. return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers);
  26973. }));
  26974. return renderToolbar({
  26975. type: toolbarType,
  26976. uid: generate$6('context-toolbar'),
  26977. initGroups: initGroups,
  26978. onEscape: Optional.none,
  26979. cyclicKeying: true,
  26980. providers: sharedBackstage.providers
  26981. });
  26982. };
  26983. var getAnchor = function (position, element) {
  26984. var anchorage = position === 'node' ? sharedBackstage.anchors.node(element) : sharedBackstage.anchors.cursor();
  26985. var anchorLayout = getAnchorLayout(editor, position, isTouch(), {
  26986. lastElement: lastElement.get,
  26987. isReposition: function () {
  26988. return is$1(lastTrigger.get(), 0);
  26989. },
  26990. getMode: function () {
  26991. return Positioning.getMode(sink);
  26992. }
  26993. });
  26994. return deepMerge(anchorage, anchorLayout);
  26995. };
  26996. var launchContext = function (toolbarApi, elem) {
  26997. launchContextToolbar.cancel();
  26998. if (!canLaunchToolbar()) {
  26999. return;
  27000. }
  27001. var toolbarSpec = buildToolbar(toolbarApi);
  27002. var position = toolbarApi[0].position;
  27003. var anchor = getAnchor(position, elem);
  27004. lastContextPosition.set(position);
  27005. lastTrigger.set(1);
  27006. var contextBarEle = contextbar.element;
  27007. remove$6(contextBarEle, 'display');
  27008. if (!isSameLaunchElement(elem)) {
  27009. remove$2(contextBarEle, transitionClass);
  27010. Positioning.reset(sink, contextbar);
  27011. }
  27012. InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), {
  27013. anchor: anchor,
  27014. transition: {
  27015. classes: [transitionClass],
  27016. mode: 'placement'
  27017. }
  27018. }, function () {
  27019. return Optional.some(getBounds());
  27020. });
  27021. elem.fold(lastElement.clear, lastElement.set);
  27022. if (shouldContextToolbarHide()) {
  27023. set$7(contextBarEle, 'display', 'none');
  27024. }
  27025. };
  27026. var launchContextToolbar = last(function () {
  27027. if (!editor.hasFocus() || editor.removed) {
  27028. return;
  27029. }
  27030. if (has(contextbar.element, transitionClass)) {
  27031. launchContextToolbar.throttle();
  27032. } else {
  27033. var scopes = getScopes();
  27034. lookup$1(scopes, editor).fold(close, function (info) {
  27035. launchContext(info.toolbars, Optional.some(info.elem));
  27036. });
  27037. }
  27038. }, 17);
  27039. editor.on('init', function () {
  27040. editor.on('remove', close);
  27041. editor.on('ScrollContent ScrollWindow ObjectResized ResizeEditor longpress', hideOrRepositionIfNecessary);
  27042. editor.on('click keyup focus SetContent', launchContextToolbar.throttle);
  27043. editor.on(hideContextToolbarEvent, close);
  27044. editor.on(showContextToolbarEvent, function (e) {
  27045. var scopes = getScopes();
  27046. get$e(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  27047. launchContext([ctx], someIf(e.target !== editor, e.target));
  27048. InlineView.getContent(contextbar).each(Keying.focusIn);
  27049. });
  27050. });
  27051. editor.on('focusout', function (_e) {
  27052. global$f.setEditorTimeout(editor, function () {
  27053. if (search(sink.element).isNone() && search(contextbar.element).isNone()) {
  27054. close();
  27055. }
  27056. }, 0);
  27057. });
  27058. editor.on('SwitchMode', function () {
  27059. if (editor.mode.isReadOnly()) {
  27060. close();
  27061. }
  27062. });
  27063. editor.on('AfterProgressState', function (event) {
  27064. if (event.state) {
  27065. close();
  27066. } else if (editor.hasFocus()) {
  27067. launchContextToolbar.throttle();
  27068. }
  27069. });
  27070. editor.on('NodeChange', function (_e) {
  27071. search(contextbar.element).fold(launchContextToolbar.throttle, noop);
  27072. });
  27073. });
  27074. };
  27075. var register$6 = function (editor) {
  27076. var alignToolbarButtons = [
  27077. {
  27078. name: 'alignleft',
  27079. text: 'Align left',
  27080. cmd: 'JustifyLeft',
  27081. icon: 'align-left'
  27082. },
  27083. {
  27084. name: 'aligncenter',
  27085. text: 'Align center',
  27086. cmd: 'JustifyCenter',
  27087. icon: 'align-center'
  27088. },
  27089. {
  27090. name: 'alignright',
  27091. text: 'Align right',
  27092. cmd: 'JustifyRight',
  27093. icon: 'align-right'
  27094. },
  27095. {
  27096. name: 'alignjustify',
  27097. text: 'Justify',
  27098. cmd: 'JustifyFull',
  27099. icon: 'align-justify'
  27100. }
  27101. ];
  27102. each$1(alignToolbarButtons, function (item) {
  27103. editor.ui.registry.addToggleButton(item.name, {
  27104. tooltip: item.text,
  27105. icon: item.icon,
  27106. onAction: onActionExecCommand(editor, item.cmd),
  27107. onSetup: onSetupFormatToggle(editor, item.name)
  27108. });
  27109. });
  27110. editor.ui.registry.addButton('alignnone', {
  27111. tooltip: 'No alignment',
  27112. icon: 'align-none',
  27113. onAction: onActionExecCommand(editor, 'JustifyNone')
  27114. });
  27115. };
  27116. var units = {
  27117. unsupportedLength: [
  27118. 'em',
  27119. 'ex',
  27120. 'cap',
  27121. 'ch',
  27122. 'ic',
  27123. 'rem',
  27124. 'lh',
  27125. 'rlh',
  27126. 'vw',
  27127. 'vh',
  27128. 'vi',
  27129. 'vb',
  27130. 'vmin',
  27131. 'vmax',
  27132. 'cm',
  27133. 'mm',
  27134. 'Q',
  27135. 'in',
  27136. 'pc',
  27137. 'pt',
  27138. 'px'
  27139. ],
  27140. fixed: [
  27141. 'px',
  27142. 'pt'
  27143. ],
  27144. relative: ['%'],
  27145. empty: ['']
  27146. };
  27147. var pattern = function () {
  27148. var decimalDigits = '[0-9]+';
  27149. var signedInteger = '[+-]?' + decimalDigits;
  27150. var exponentPart = '[eE]' + signedInteger;
  27151. var dot = '\\.';
  27152. var opt = function (input) {
  27153. return '(?:' + input + ')?';
  27154. };
  27155. var unsignedDecimalLiteral = [
  27156. 'Infinity',
  27157. decimalDigits + dot + opt(decimalDigits) + opt(exponentPart),
  27158. dot + decimalDigits + opt(exponentPart),
  27159. decimalDigits + opt(exponentPart)
  27160. ].join('|');
  27161. var float = '[+-]?(?:' + unsignedDecimalLiteral + ')';
  27162. return new RegExp('^(' + float + ')(.*)$');
  27163. }();
  27164. var isUnit = function (unit, accepted) {
  27165. return exists(accepted, function (acc) {
  27166. return exists(units[acc], function (check) {
  27167. return unit === check;
  27168. });
  27169. });
  27170. };
  27171. var parse = function (input, accepted) {
  27172. var match = Optional.from(pattern.exec(input));
  27173. return match.bind(function (array) {
  27174. var value = Number(array[1]);
  27175. var unitRaw = array[2];
  27176. if (isUnit(unitRaw, accepted)) {
  27177. return Optional.some({
  27178. value: value,
  27179. unit: unitRaw
  27180. });
  27181. } else {
  27182. return Optional.none();
  27183. }
  27184. });
  27185. };
  27186. var normalise = function (input, accepted) {
  27187. return parse(input, accepted).map(function (_a) {
  27188. var value = _a.value, unit = _a.unit;
  27189. return value + unit;
  27190. });
  27191. };
  27192. var registerController = function (editor, spec) {
  27193. var getMenuItems = function () {
  27194. var options = spec.getOptions(editor);
  27195. var initial = spec.getCurrent(editor).map(spec.hash);
  27196. var current = value$1();
  27197. return map$2(options, function (value) {
  27198. return {
  27199. type: 'togglemenuitem',
  27200. text: spec.display(value),
  27201. onSetup: function (api) {
  27202. var setActive = function (active) {
  27203. if (active) {
  27204. current.on(function (oldApi) {
  27205. return oldApi.setActive(false);
  27206. });
  27207. current.set(api);
  27208. }
  27209. api.setActive(active);
  27210. };
  27211. setActive(is$1(initial, spec.hash(value)));
  27212. var unbindWatcher = spec.watcher(editor, value, setActive);
  27213. return function () {
  27214. current.clear();
  27215. unbindWatcher();
  27216. };
  27217. },
  27218. onAction: function () {
  27219. return spec.setCurrent(editor, value);
  27220. }
  27221. };
  27222. });
  27223. };
  27224. editor.ui.registry.addMenuButton(spec.name, {
  27225. tooltip: spec.text,
  27226. icon: spec.icon,
  27227. fetch: function (callback) {
  27228. return callback(getMenuItems());
  27229. },
  27230. onSetup: spec.onToolbarSetup
  27231. });
  27232. editor.ui.registry.addNestedMenuItem(spec.name, {
  27233. type: 'nestedmenuitem',
  27234. text: spec.text,
  27235. getSubmenuItems: getMenuItems,
  27236. onSetup: spec.onMenuSetup
  27237. });
  27238. };
  27239. var lineHeightSpec = {
  27240. name: 'lineheight',
  27241. text: 'Line height',
  27242. icon: 'line-height',
  27243. getOptions: getLineHeightFormats,
  27244. hash: function (input) {
  27245. return normalise(input, [
  27246. 'fixed',
  27247. 'relative',
  27248. 'empty'
  27249. ]).getOr(input);
  27250. },
  27251. display: identity$1,
  27252. watcher: function (editor, value, callback) {
  27253. return editor.formatter.formatChanged('lineheight', callback, false, { value: value }).unbind;
  27254. },
  27255. getCurrent: function (editor) {
  27256. return Optional.from(editor.queryCommandValue('LineHeight'));
  27257. },
  27258. setCurrent: function (editor, value) {
  27259. return editor.execCommand('LineHeight', false, value);
  27260. }
  27261. };
  27262. var languageSpec = function (editor) {
  27263. var settingsOpt = Optional.from(getContentLanguages(editor));
  27264. return settingsOpt.map(function (settings) {
  27265. return {
  27266. name: 'language',
  27267. text: 'Language',
  27268. icon: 'language',
  27269. getOptions: constant$1(settings),
  27270. hash: function (input) {
  27271. return isUndefined(input.customCode) ? input.code : input.code + '/' + input.customCode;
  27272. },
  27273. display: function (input) {
  27274. return input.title;
  27275. },
  27276. watcher: function (editor, value, callback) {
  27277. return editor.formatter.formatChanged('lang', callback, false, {
  27278. value: value.code,
  27279. customValue: value.customCode
  27280. }).unbind;
  27281. },
  27282. getCurrent: function (editor) {
  27283. var node = SugarElement.fromDom(editor.selection.getNode());
  27284. return closest$4(node, function (n) {
  27285. return Optional.some(n).filter(isElement$2).bind(function (ele) {
  27286. var codeOpt = getOpt(ele, 'lang');
  27287. return codeOpt.map(function (code) {
  27288. var customCode = getOpt(ele, 'data-mce-lang').getOrUndefined();
  27289. return {
  27290. code: code,
  27291. customCode: customCode,
  27292. title: ''
  27293. };
  27294. });
  27295. });
  27296. });
  27297. },
  27298. setCurrent: function (editor, lang) {
  27299. return editor.execCommand('Lang', false, lang);
  27300. },
  27301. onToolbarSetup: function (api) {
  27302. var unbinder = unbindable();
  27303. api.setActive(editor.formatter.match('lang', {}, undefined, true));
  27304. unbinder.set(editor.formatter.formatChanged('lang', api.setActive, true));
  27305. return unbinder.clear;
  27306. }
  27307. };
  27308. });
  27309. };
  27310. var register$5 = function (editor) {
  27311. registerController(editor, lineHeightSpec);
  27312. languageSpec(editor).each(function (spec) {
  27313. return registerController(editor, spec);
  27314. });
  27315. };
  27316. var register$4 = function (editor, backstage) {
  27317. alignSelectMenu(editor, backstage);
  27318. fontSelectMenu(editor, backstage);
  27319. styleSelectMenu(editor, backstage);
  27320. formatSelectMenu(editor, backstage);
  27321. fontsizeSelectMenu(editor, backstage);
  27322. };
  27323. var onSetupOutdentState = function (editor) {
  27324. return onSetupEvent(editor, 'NodeChange', function (api) {
  27325. api.setDisabled(!editor.queryCommandState('outdent'));
  27326. });
  27327. };
  27328. var registerButtons$2 = function (editor) {
  27329. editor.ui.registry.addButton('outdent', {
  27330. tooltip: 'Decrease indent',
  27331. icon: 'outdent',
  27332. onSetup: onSetupOutdentState(editor),
  27333. onAction: onActionExecCommand(editor, 'outdent')
  27334. });
  27335. editor.ui.registry.addButton('indent', {
  27336. tooltip: 'Increase indent',
  27337. icon: 'indent',
  27338. onAction: onActionExecCommand(editor, 'indent')
  27339. });
  27340. };
  27341. var register$3 = function (editor) {
  27342. registerButtons$2(editor);
  27343. };
  27344. var onActionToggleFormat = function (editor, fmt) {
  27345. return function () {
  27346. editor.execCommand('mceToggleFormat', false, fmt);
  27347. };
  27348. };
  27349. var registerFormatButtons = function (editor) {
  27350. global$5.each([
  27351. {
  27352. name: 'bold',
  27353. text: 'Bold',
  27354. icon: 'bold'
  27355. },
  27356. {
  27357. name: 'italic',
  27358. text: 'Italic',
  27359. icon: 'italic'
  27360. },
  27361. {
  27362. name: 'underline',
  27363. text: 'Underline',
  27364. icon: 'underline'
  27365. },
  27366. {
  27367. name: 'strikethrough',
  27368. text: 'Strikethrough',
  27369. icon: 'strike-through'
  27370. },
  27371. {
  27372. name: 'subscript',
  27373. text: 'Subscript',
  27374. icon: 'subscript'
  27375. },
  27376. {
  27377. name: 'superscript',
  27378. text: 'Superscript',
  27379. icon: 'superscript'
  27380. }
  27381. ], function (btn, _idx) {
  27382. editor.ui.registry.addToggleButton(btn.name, {
  27383. tooltip: btn.text,
  27384. icon: btn.icon,
  27385. onSetup: onSetupFormatToggle(editor, btn.name),
  27386. onAction: onActionToggleFormat(editor, btn.name)
  27387. });
  27388. });
  27389. for (var i = 1; i <= 6; i++) {
  27390. var name_1 = 'h' + i;
  27391. editor.ui.registry.addToggleButton(name_1, {
  27392. text: name_1.toUpperCase(),
  27393. tooltip: 'Heading ' + i,
  27394. onSetup: onSetupFormatToggle(editor, name_1),
  27395. onAction: onActionToggleFormat(editor, name_1)
  27396. });
  27397. }
  27398. };
  27399. var registerCommandButtons = function (editor) {
  27400. global$5.each([
  27401. {
  27402. name: 'cut',
  27403. text: 'Cut',
  27404. action: 'Cut',
  27405. icon: 'cut'
  27406. },
  27407. {
  27408. name: 'copy',
  27409. text: 'Copy',
  27410. action: 'Copy',
  27411. icon: 'copy'
  27412. },
  27413. {
  27414. name: 'paste',
  27415. text: 'Paste',
  27416. action: 'Paste',
  27417. icon: 'paste'
  27418. },
  27419. {
  27420. name: 'help',
  27421. text: 'Help',
  27422. action: 'mceHelp',
  27423. icon: 'help'
  27424. },
  27425. {
  27426. name: 'selectall',
  27427. text: 'Select all',
  27428. action: 'SelectAll',
  27429. icon: 'select-all'
  27430. },
  27431. {
  27432. name: 'newdocument',
  27433. text: 'New document',
  27434. action: 'mceNewDocument',
  27435. icon: 'new-document'
  27436. },
  27437. {
  27438. name: 'removeformat',
  27439. text: 'Clear formatting',
  27440. action: 'RemoveFormat',
  27441. icon: 'remove-formatting'
  27442. },
  27443. {
  27444. name: 'remove',
  27445. text: 'Remove',
  27446. action: 'Delete',
  27447. icon: 'remove'
  27448. }
  27449. ], function (btn) {
  27450. editor.ui.registry.addButton(btn.name, {
  27451. tooltip: btn.text,
  27452. icon: btn.icon,
  27453. onAction: onActionExecCommand(editor, btn.action)
  27454. });
  27455. });
  27456. };
  27457. var registerCommandToggleButtons = function (editor) {
  27458. global$5.each([{
  27459. name: 'blockquote',
  27460. text: 'Blockquote',
  27461. action: 'mceBlockQuote',
  27462. icon: 'quote'
  27463. }], function (btn) {
  27464. editor.ui.registry.addToggleButton(btn.name, {
  27465. tooltip: btn.text,
  27466. icon: btn.icon,
  27467. onAction: onActionExecCommand(editor, btn.action),
  27468. onSetup: onSetupFormatToggle(editor, btn.name)
  27469. });
  27470. });
  27471. };
  27472. var registerButtons$1 = function (editor) {
  27473. registerFormatButtons(editor);
  27474. registerCommandButtons(editor);
  27475. registerCommandToggleButtons(editor);
  27476. };
  27477. var registerMenuItems$2 = function (editor) {
  27478. global$5.each([
  27479. {
  27480. name: 'bold',
  27481. text: 'Bold',
  27482. action: 'Bold',
  27483. icon: 'bold',
  27484. shortcut: 'Meta+B'
  27485. },
  27486. {
  27487. name: 'italic',
  27488. text: 'Italic',
  27489. action: 'Italic',
  27490. icon: 'italic',
  27491. shortcut: 'Meta+I'
  27492. },
  27493. {
  27494. name: 'underline',
  27495. text: 'Underline',
  27496. action: 'Underline',
  27497. icon: 'underline',
  27498. shortcut: 'Meta+U'
  27499. },
  27500. {
  27501. name: 'strikethrough',
  27502. text: 'Strikethrough',
  27503. action: 'Strikethrough',
  27504. icon: 'strike-through',
  27505. shortcut: ''
  27506. },
  27507. {
  27508. name: 'subscript',
  27509. text: 'Subscript',
  27510. action: 'Subscript',
  27511. icon: 'subscript',
  27512. shortcut: ''
  27513. },
  27514. {
  27515. name: 'superscript',
  27516. text: 'Superscript',
  27517. action: 'Superscript',
  27518. icon: 'superscript',
  27519. shortcut: ''
  27520. },
  27521. {
  27522. name: 'removeformat',
  27523. text: 'Clear formatting',
  27524. action: 'RemoveFormat',
  27525. icon: 'remove-formatting',
  27526. shortcut: ''
  27527. },
  27528. {
  27529. name: 'newdocument',
  27530. text: 'New document',
  27531. action: 'mceNewDocument',
  27532. icon: 'new-document',
  27533. shortcut: ''
  27534. },
  27535. {
  27536. name: 'cut',
  27537. text: 'Cut',
  27538. action: 'Cut',
  27539. icon: 'cut',
  27540. shortcut: 'Meta+X'
  27541. },
  27542. {
  27543. name: 'copy',
  27544. text: 'Copy',
  27545. action: 'Copy',
  27546. icon: 'copy',
  27547. shortcut: 'Meta+C'
  27548. },
  27549. {
  27550. name: 'paste',
  27551. text: 'Paste',
  27552. action: 'Paste',
  27553. icon: 'paste',
  27554. shortcut: 'Meta+V'
  27555. },
  27556. {
  27557. name: 'selectall',
  27558. text: 'Select all',
  27559. action: 'SelectAll',
  27560. icon: 'select-all',
  27561. shortcut: 'Meta+A'
  27562. }
  27563. ], function (btn) {
  27564. editor.ui.registry.addMenuItem(btn.name, {
  27565. text: btn.text,
  27566. icon: btn.icon,
  27567. shortcut: btn.shortcut,
  27568. onAction: onActionExecCommand(editor, btn.action)
  27569. });
  27570. });
  27571. editor.ui.registry.addMenuItem('codeformat', {
  27572. text: 'Code',
  27573. icon: 'sourcecode',
  27574. onAction: onActionToggleFormat(editor, 'code')
  27575. });
  27576. };
  27577. var register$2 = function (editor) {
  27578. registerButtons$1(editor);
  27579. registerMenuItems$2(editor);
  27580. };
  27581. var onSetupUndoRedoState = function (editor, type) {
  27582. return onSetupEvent(editor, 'Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function (api) {
  27583. api.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type]());
  27584. });
  27585. };
  27586. var registerMenuItems$1 = function (editor) {
  27587. editor.ui.registry.addMenuItem('undo', {
  27588. text: 'Undo',
  27589. icon: 'undo',
  27590. shortcut: 'Meta+Z',
  27591. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  27592. onAction: onActionExecCommand(editor, 'undo')
  27593. });
  27594. editor.ui.registry.addMenuItem('redo', {
  27595. text: 'Redo',
  27596. icon: 'redo',
  27597. shortcut: 'Meta+Y',
  27598. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  27599. onAction: onActionExecCommand(editor, 'redo')
  27600. });
  27601. };
  27602. var registerButtons = function (editor) {
  27603. editor.ui.registry.addButton('undo', {
  27604. tooltip: 'Undo',
  27605. icon: 'undo',
  27606. disabled: true,
  27607. onSetup: onSetupUndoRedoState(editor, 'hasUndo'),
  27608. onAction: onActionExecCommand(editor, 'undo')
  27609. });
  27610. editor.ui.registry.addButton('redo', {
  27611. tooltip: 'Redo',
  27612. icon: 'redo',
  27613. disabled: true,
  27614. onSetup: onSetupUndoRedoState(editor, 'hasRedo'),
  27615. onAction: onActionExecCommand(editor, 'redo')
  27616. });
  27617. };
  27618. var register$1 = function (editor) {
  27619. registerMenuItems$1(editor);
  27620. registerButtons(editor);
  27621. };
  27622. var onSetupVisualAidState = function (editor) {
  27623. return onSetupEvent(editor, 'VisualAid', function (api) {
  27624. api.setActive(editor.hasVisual);
  27625. });
  27626. };
  27627. var registerMenuItems = function (editor) {
  27628. editor.ui.registry.addToggleMenuItem('visualaid', {
  27629. text: 'Visual aids',
  27630. onSetup: onSetupVisualAidState(editor),
  27631. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  27632. });
  27633. };
  27634. var registerToolbarButton = function (editor) {
  27635. editor.ui.registry.addButton('visualaid', {
  27636. tooltip: 'Visual aids',
  27637. text: 'Visual aids',
  27638. onAction: onActionExecCommand(editor, 'mceToggleVisualAid')
  27639. });
  27640. };
  27641. var register = function (editor) {
  27642. registerToolbarButton(editor);
  27643. registerMenuItems(editor);
  27644. };
  27645. var setup$6 = function (editor, backstage) {
  27646. register$6(editor);
  27647. register$2(editor);
  27648. register$4(editor, backstage);
  27649. register$1(editor);
  27650. register$a(editor);
  27651. register(editor);
  27652. register$3(editor);
  27653. register$5(editor);
  27654. };
  27655. var nu = function (x, y) {
  27656. return {
  27657. type: 'makeshift',
  27658. x: x,
  27659. y: y
  27660. };
  27661. };
  27662. var transpose = function (pos, dx, dy) {
  27663. return nu(pos.x + dx, pos.y + dy);
  27664. };
  27665. var isTouchEvent = function (e) {
  27666. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  27667. };
  27668. var fromPageXY = function (e) {
  27669. if (isTouchEvent(e)) {
  27670. var touch = e.touches[0];
  27671. return nu(touch.pageX, touch.pageY);
  27672. } else {
  27673. return nu(e.pageX, e.pageY);
  27674. }
  27675. };
  27676. var fromClientXY = function (e) {
  27677. if (isTouchEvent(e)) {
  27678. var touch = e.touches[0];
  27679. return nu(touch.clientX, touch.clientY);
  27680. } else {
  27681. return nu(e.clientX, e.clientY);
  27682. }
  27683. };
  27684. var transposeContentAreaContainer = function (element, pos) {
  27685. var containerPos = global$b.DOM.getPos(element);
  27686. return transpose(pos, containerPos.x, containerPos.y);
  27687. };
  27688. var getPointAnchor = function (editor, e) {
  27689. if (e.type === 'contextmenu' || e.type === 'longpress') {
  27690. if (editor.inline) {
  27691. return fromPageXY(e);
  27692. } else {
  27693. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  27694. }
  27695. } else {
  27696. return getSelectionAnchor(editor);
  27697. }
  27698. };
  27699. var getSelectionAnchor = function (editor) {
  27700. return {
  27701. type: 'selection',
  27702. root: SugarElement.fromDom(editor.selection.getNode())
  27703. };
  27704. };
  27705. var getNodeAnchor = function (editor) {
  27706. return {
  27707. type: 'node',
  27708. node: Optional.some(SugarElement.fromDom(editor.selection.getNode())),
  27709. root: SugarElement.fromDom(editor.getBody())
  27710. };
  27711. };
  27712. var getAnchorSpec$1 = function (editor, e, anchorType) {
  27713. switch (anchorType) {
  27714. case 'node':
  27715. return getNodeAnchor(editor);
  27716. case 'point':
  27717. return getPointAnchor(editor, e);
  27718. case 'selection':
  27719. return getSelectionAnchor(editor);
  27720. }
  27721. };
  27722. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  27723. var items = buildMenu();
  27724. var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  27725. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  27726. e.preventDefault();
  27727. InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, {
  27728. menu: { markers: markers('normal') },
  27729. data: menuData
  27730. });
  27731. });
  27732. };
  27733. var layouts = {
  27734. onLtr: function () {
  27735. return [
  27736. south$2,
  27737. southeast$2,
  27738. southwest$2,
  27739. northeast$2,
  27740. northwest$2,
  27741. north$2,
  27742. north,
  27743. south,
  27744. northeast,
  27745. southeast,
  27746. northwest,
  27747. southwest
  27748. ];
  27749. },
  27750. onRtl: function () {
  27751. return [
  27752. south$2,
  27753. southwest$2,
  27754. southeast$2,
  27755. northwest$2,
  27756. northeast$2,
  27757. north$2,
  27758. north,
  27759. south,
  27760. northwest,
  27761. southwest,
  27762. northeast,
  27763. southeast
  27764. ];
  27765. }
  27766. };
  27767. var bubbleSize = 12;
  27768. var bubbleAlignments = {
  27769. valignCentre: [],
  27770. alignCentre: [],
  27771. alignLeft: ['tox-pop--align-left'],
  27772. alignRight: ['tox-pop--align-right'],
  27773. right: ['tox-pop--right'],
  27774. left: ['tox-pop--left'],
  27775. bottom: ['tox-pop--bottom'],
  27776. top: ['tox-pop--top']
  27777. };
  27778. var isTouchWithinSelection = function (editor, e) {
  27779. var selection = editor.selection;
  27780. if (selection.isCollapsed() || e.touches.length < 1) {
  27781. return false;
  27782. } else {
  27783. var touch_1 = e.touches[0];
  27784. var rng = selection.getRng();
  27785. var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng));
  27786. return rngRectOpt.exists(function (rngRect) {
  27787. return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY;
  27788. });
  27789. }
  27790. };
  27791. var setupiOSOverrides = function (editor) {
  27792. var originalSelection = editor.selection.getRng();
  27793. var selectionReset = function () {
  27794. global$f.setEditorTimeout(editor, function () {
  27795. editor.selection.setRng(originalSelection);
  27796. }, 10);
  27797. unbindEventListeners();
  27798. };
  27799. editor.once('touchend', selectionReset);
  27800. var preventMousedown = function (e) {
  27801. e.preventDefault();
  27802. e.stopImmediatePropagation();
  27803. };
  27804. editor.on('mousedown', preventMousedown, true);
  27805. var clearSelectionReset = function () {
  27806. return unbindEventListeners();
  27807. };
  27808. editor.once('longpresscancel', clearSelectionReset);
  27809. var unbindEventListeners = function () {
  27810. editor.off('touchend', selectionReset);
  27811. editor.off('longpresscancel', clearSelectionReset);
  27812. editor.off('mousedown', preventMousedown);
  27813. };
  27814. };
  27815. var getAnchorSpec = function (editor, e, anchorType) {
  27816. var anchorSpec = getAnchorSpec$1(editor, e, anchorType);
  27817. var bubbleYOffset = anchorType === 'point' ? bubbleSize : 0;
  27818. return __assign({
  27819. bubble: nu$5(0, bubbleYOffset, bubbleAlignments),
  27820. layouts: layouts,
  27821. overrides: {
  27822. maxWidthFunction: expandable(),
  27823. maxHeightFunction: expandable$1()
  27824. }
  27825. }, anchorSpec);
  27826. };
  27827. var show = function (editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) {
  27828. var anchorSpec = getAnchorSpec(editor, e, anchorType);
  27829. build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  27830. e.preventDefault();
  27831. InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, {
  27832. menu: {
  27833. markers: markers('normal'),
  27834. highlightImmediately: highlightImmediately
  27835. },
  27836. data: menuData,
  27837. type: 'horizontal'
  27838. }, function () {
  27839. return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === 'node' ? 'node' : 'selection'));
  27840. });
  27841. editor.fire(hideContextToolbarEvent);
  27842. });
  27843. };
  27844. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, anchorType) {
  27845. var detection = detect$1();
  27846. var isiOS = detection.os.isiOS();
  27847. var isOSX = detection.os.isOSX();
  27848. var isAndroid = detection.os.isAndroid();
  27849. var isTouch = detection.deviceType.isTouch();
  27850. var shouldHighlightImmediately = function () {
  27851. return !(isAndroid || isiOS || isOSX && isTouch);
  27852. };
  27853. var open = function () {
  27854. var items = buildMenu();
  27855. show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately());
  27856. };
  27857. if ((isOSX || isiOS) && anchorType !== 'node') {
  27858. var openiOS_1 = function () {
  27859. setupiOSOverrides(editor);
  27860. open();
  27861. };
  27862. if (isTouchWithinSelection(editor, e)) {
  27863. openiOS_1();
  27864. } else {
  27865. editor.once('selectionchange', openiOS_1);
  27866. editor.once('touchend', function () {
  27867. return editor.off('selectionchange', openiOS_1);
  27868. });
  27869. }
  27870. } else {
  27871. open();
  27872. }
  27873. };
  27874. var patchPipeConfig = function (config) {
  27875. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  27876. };
  27877. var shouldNeverUseNative = function (editor) {
  27878. return editor.getParam('contextmenu_never_use_native', false, 'boolean');
  27879. };
  27880. var getMenuItems = function (editor, name, defaultItems) {
  27881. var contextMenus = editor.ui.registry.getAll().contextMenus;
  27882. return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () {
  27883. return filter$2(patchPipeConfig(defaultItems), function (item) {
  27884. return has$2(contextMenus, item);
  27885. });
  27886. });
  27887. };
  27888. var isContextMenuDisabled = function (editor) {
  27889. return editor.getParam('contextmenu') === false;
  27890. };
  27891. var getContextMenu = function (editor) {
  27892. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  27893. };
  27894. var getAvoidOverlapSelector = function (editor) {
  27895. return editor.getParam('contextmenu_avoid_overlap', '', 'string');
  27896. };
  27897. var isSeparator = function (item) {
  27898. return isString(item) ? item === '|' : item.type === 'separator';
  27899. };
  27900. var separator = { type: 'separator' };
  27901. var makeContextItem = function (item) {
  27902. var commonMenuItem = function (item) {
  27903. return {
  27904. text: item.text,
  27905. icon: item.icon,
  27906. disabled: item.disabled,
  27907. shortcut: item.shortcut
  27908. };
  27909. };
  27910. if (isString(item)) {
  27911. return item;
  27912. } else {
  27913. switch (item.type) {
  27914. case 'separator':
  27915. return separator;
  27916. case 'submenu':
  27917. return __assign(__assign({ type: 'nestedmenuitem' }, commonMenuItem(item)), {
  27918. getSubmenuItems: function () {
  27919. var items = item.getSubmenuItems();
  27920. if (isString(items)) {
  27921. return items;
  27922. } else {
  27923. return map$2(items, makeContextItem);
  27924. }
  27925. }
  27926. });
  27927. default:
  27928. return __assign(__assign({ type: 'menuitem' }, commonMenuItem(item)), { onAction: noarg(item.onAction) });
  27929. }
  27930. }
  27931. };
  27932. var addContextMenuGroup = function (xs, groupItems) {
  27933. if (groupItems.length === 0) {
  27934. return xs;
  27935. }
  27936. var lastMenuItem = last$2(xs).filter(function (item) {
  27937. return !isSeparator(item);
  27938. });
  27939. var before = lastMenuItem.fold(function () {
  27940. return [];
  27941. }, function (_) {
  27942. return [separator];
  27943. });
  27944. return xs.concat(before).concat(groupItems).concat([separator]);
  27945. };
  27946. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  27947. var sections = foldl(menuConfig, function (acc, name) {
  27948. return get$e(contextMenus, name.toLowerCase()).map(function (menu) {
  27949. var items = menu.update(selectedElement);
  27950. if (isString(items)) {
  27951. return addContextMenuGroup(acc, items.split(' '));
  27952. } else if (items.length > 0) {
  27953. var allItems = map$2(items, makeContextItem);
  27954. return addContextMenuGroup(acc, allItems);
  27955. } else {
  27956. return acc;
  27957. }
  27958. }).getOrThunk(function () {
  27959. return acc.concat([name]);
  27960. });
  27961. }, []);
  27962. if (sections.length > 0 && isSeparator(sections[sections.length - 1])) {
  27963. sections.pop();
  27964. }
  27965. return sections;
  27966. };
  27967. var isNativeOverrideKeyEvent = function (editor, e) {
  27968. return e.ctrlKey && !shouldNeverUseNative(editor);
  27969. };
  27970. var isTriggeredByKeyboard = function (editor, e) {
  27971. return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  27972. };
  27973. var getSelectedElement = function (editor, e) {
  27974. return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target;
  27975. };
  27976. var getAnchorType = function (editor, e) {
  27977. var selector = getAvoidOverlapSelector(editor);
  27978. var anchorType = isTriggeredByKeyboard(editor, e) ? 'selection' : 'point';
  27979. if (isNotEmpty(selector)) {
  27980. var target = getSelectedElement(editor, e);
  27981. var selectorExists = closest(SugarElement.fromDom(target), selector);
  27982. return selectorExists ? 'node' : anchorType;
  27983. } else {
  27984. return anchorType;
  27985. }
  27986. };
  27987. var setup$5 = function (editor, lazySink, backstage) {
  27988. var detection = detect$1();
  27989. var isTouch = detection.deviceType.isTouch;
  27990. var contextmenu = build$1(InlineView.sketch({
  27991. dom: { tag: 'div' },
  27992. lazySink: lazySink,
  27993. onEscape: function () {
  27994. return editor.focus();
  27995. },
  27996. onShow: function () {
  27997. return backstage.setContextMenuState(true);
  27998. },
  27999. onHide: function () {
  28000. return backstage.setContextMenuState(false);
  28001. },
  28002. fireDismissalEventInstead: {},
  28003. inlineBehaviours: derive$1([config('dismissContextMenu', [run$1(dismissRequested(), function (comp, _se) {
  28004. Sandboxing.close(comp);
  28005. editor.focus();
  28006. })])])
  28007. }));
  28008. var hideContextMenu = function (_e) {
  28009. return InlineView.hide(contextmenu);
  28010. };
  28011. var showContextMenu = function (e) {
  28012. if (shouldNeverUseNative(editor)) {
  28013. e.preventDefault();
  28014. }
  28015. if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  28016. return;
  28017. }
  28018. var anchorType = getAnchorType(editor, e);
  28019. var buildMenu = function () {
  28020. var selectedElement = getSelectedElement(editor, e);
  28021. var registry = editor.ui.registry.getAll();
  28022. var menuConfig = getContextMenu(editor);
  28023. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  28024. };
  28025. var initAndShow$2 = isTouch() ? initAndShow : initAndShow$1;
  28026. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType);
  28027. };
  28028. editor.on('init', function () {
  28029. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  28030. editor.on(hideEvents, hideContextMenu);
  28031. editor.on('longpress contextmenu', showContextMenu);
  28032. });
  28033. };
  28034. var adt = Adt.generate([
  28035. {
  28036. offset: [
  28037. 'x',
  28038. 'y'
  28039. ]
  28040. },
  28041. {
  28042. absolute: [
  28043. 'x',
  28044. 'y'
  28045. ]
  28046. },
  28047. {
  28048. fixed: [
  28049. 'x',
  28050. 'y'
  28051. ]
  28052. }
  28053. ]);
  28054. var subtract = function (change) {
  28055. return function (point) {
  28056. return point.translate(-change.left, -change.top);
  28057. };
  28058. };
  28059. var add = function (change) {
  28060. return function (point) {
  28061. return point.translate(change.left, change.top);
  28062. };
  28063. };
  28064. var transform = function (changes) {
  28065. return function (x, y) {
  28066. return foldl(changes, function (rest, f) {
  28067. return f(rest);
  28068. }, SugarPosition(x, y));
  28069. };
  28070. };
  28071. var asFixed = function (coord, scroll, origin) {
  28072. return coord.fold(transform([
  28073. add(origin),
  28074. subtract(scroll)
  28075. ]), transform([subtract(scroll)]), transform([]));
  28076. };
  28077. var asAbsolute = function (coord, scroll, origin) {
  28078. return coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)]));
  28079. };
  28080. var asOffset = function (coord, scroll, origin) {
  28081. return coord.fold(transform([]), transform([subtract(origin)]), transform([
  28082. add(scroll),
  28083. subtract(origin)
  28084. ]));
  28085. };
  28086. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  28087. var a1 = asAbsolute(coord1, scroll, origin);
  28088. var a2 = asAbsolute(coord2, scroll, origin);
  28089. return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange;
  28090. };
  28091. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  28092. var a1 = asAbsolute(coord1, scroll, origin);
  28093. var a2 = asAbsolute(coord2, scroll, origin);
  28094. var left = Math.abs(a1.left - a2.left);
  28095. var top = Math.abs(a1.top - a2.top);
  28096. return SugarPosition(left, top);
  28097. };
  28098. var toStyles = function (coord, scroll, origin) {
  28099. var stylesOpt = coord.fold(function (x, y) {
  28100. return {
  28101. position: Optional.some('absolute'),
  28102. left: Optional.some(x + 'px'),
  28103. top: Optional.some(y + 'px')
  28104. };
  28105. }, function (x, y) {
  28106. return {
  28107. position: Optional.some('absolute'),
  28108. left: Optional.some(x - origin.left + 'px'),
  28109. top: Optional.some(y - origin.top + 'px')
  28110. };
  28111. }, function (x, y) {
  28112. return {
  28113. position: Optional.some('fixed'),
  28114. left: Optional.some(x + 'px'),
  28115. top: Optional.some(y + 'px')
  28116. };
  28117. });
  28118. return __assign({
  28119. right: Optional.none(),
  28120. bottom: Optional.none()
  28121. }, stylesOpt);
  28122. };
  28123. var translate = function (coord, deltaX, deltaY) {
  28124. return coord.fold(function (x, y) {
  28125. return offset(x + deltaX, y + deltaY);
  28126. }, function (x, y) {
  28127. return absolute(x + deltaX, y + deltaY);
  28128. }, function (x, y) {
  28129. return fixed(x + deltaX, y + deltaY);
  28130. });
  28131. };
  28132. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  28133. var absorbOne = function (stencil, nu) {
  28134. return function (optX, optY) {
  28135. var original = stencil(originalCoord, scroll, origin);
  28136. return nu(optX.getOr(original.left), optY.getOr(original.top));
  28137. };
  28138. };
  28139. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed));
  28140. };
  28141. var offset = adt.offset;
  28142. var absolute = adt.absolute;
  28143. var fixed = adt.fixed;
  28144. var parseAttrToInt = function (element, name) {
  28145. var value = get$d(element, name);
  28146. return isUndefined(value) ? NaN : parseInt(value, 10);
  28147. };
  28148. var get = function (component, snapsInfo) {
  28149. var element = component.element;
  28150. var x = parseAttrToInt(element, snapsInfo.leftAttr);
  28151. var y = parseAttrToInt(element, snapsInfo.topAttr);
  28152. return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y));
  28153. };
  28154. var set = function (component, snapsInfo, pt) {
  28155. var element = component.element;
  28156. set$8(element, snapsInfo.leftAttr, pt.left + 'px');
  28157. set$8(element, snapsInfo.topAttr, pt.top + 'px');
  28158. };
  28159. var clear = function (component, snapsInfo) {
  28160. var element = component.element;
  28161. remove$7(element, snapsInfo.leftAttr);
  28162. remove$7(element, snapsInfo.topAttr);
  28163. };
  28164. var getCoords = function (component, snapInfo, coord, delta) {
  28165. return get(component, snapInfo).fold(function () {
  28166. return coord;
  28167. }, function (fixed$1) {
  28168. return fixed(fixed$1.left + delta.left, fixed$1.top + delta.top);
  28169. });
  28170. };
  28171. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  28172. var newCoord = getCoords(component, snapInfo, coord, delta);
  28173. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  28174. var fixedCoord = asFixed(newCoord, scroll, origin);
  28175. set(component, snapInfo, fixedCoord);
  28176. return snap.fold(function () {
  28177. return {
  28178. coord: fixed(fixedCoord.left, fixedCoord.top),
  28179. extra: Optional.none()
  28180. };
  28181. }, function (spanned) {
  28182. return {
  28183. coord: spanned.output,
  28184. extra: spanned.extra
  28185. };
  28186. });
  28187. };
  28188. var stopDrag = function (component, snapInfo) {
  28189. clear(component, snapInfo);
  28190. };
  28191. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  28192. return findMap(snaps, function (snap) {
  28193. var sensor = snap.sensor;
  28194. var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  28195. return inRange ? Optional.some({
  28196. output: absorb(snap.output, newCoord, scroll, origin),
  28197. extra: snap.extra
  28198. }) : Optional.none();
  28199. });
  28200. };
  28201. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  28202. var snaps = snapInfo.getSnapPoints(component);
  28203. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  28204. return matchSnap.orThunk(function () {
  28205. var bestSnap = foldl(snaps, function (acc, snap) {
  28206. var sensor = snap.sensor;
  28207. var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin);
  28208. return acc.deltas.fold(function () {
  28209. return {
  28210. deltas: Optional.some(deltas),
  28211. snap: Optional.some(snap)
  28212. };
  28213. }, function (bestDeltas) {
  28214. var currAvg = (deltas.left + deltas.top) / 2;
  28215. var bestAvg = (bestDeltas.left + bestDeltas.top) / 2;
  28216. if (currAvg <= bestAvg) {
  28217. return {
  28218. deltas: Optional.some(deltas),
  28219. snap: Optional.some(snap)
  28220. };
  28221. } else {
  28222. return acc;
  28223. }
  28224. });
  28225. }, {
  28226. deltas: Optional.none(),
  28227. snap: Optional.none()
  28228. });
  28229. return bestSnap.snap.map(function (snap) {
  28230. return {
  28231. output: absorb(snap.output, newCoord, scroll, origin),
  28232. extra: snap.extra
  28233. };
  28234. });
  28235. });
  28236. };
  28237. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  28238. var snaps = snapInfo.getSnapPoints(component);
  28239. return findMatchingSnap(snaps, newCoord, scroll, origin);
  28240. };
  28241. var snapTo$1 = function (snap, scroll, origin) {
  28242. return {
  28243. coord: absorb(snap.output, snap.output, scroll, origin),
  28244. extra: snap.extra
  28245. };
  28246. };
  28247. var snapTo = function (component, dragConfig, _state, snap) {
  28248. var target = dragConfig.getTarget(component.element);
  28249. if (dragConfig.repositionTarget) {
  28250. var doc = owner$4(component.element);
  28251. var scroll_1 = get$9(doc);
  28252. var origin_1 = getOrigin(target);
  28253. var snapPin = snapTo$1(snap, scroll_1, origin_1);
  28254. var styles = toStyles(snapPin.coord, scroll_1, origin_1);
  28255. setOptions(target, styles);
  28256. }
  28257. };
  28258. var DraggingApis = /*#__PURE__*/Object.freeze({
  28259. __proto__: null,
  28260. snapTo: snapTo
  28261. });
  28262. var initialAttribute = 'data-initial-z-index';
  28263. var resetZIndex = function (blocker) {
  28264. parent(blocker.element).filter(isElement$2).each(function (root) {
  28265. getOpt(root, initialAttribute).fold(function () {
  28266. return remove$6(root, 'z-index');
  28267. }, function (zIndex) {
  28268. return set$7(root, 'z-index', zIndex);
  28269. });
  28270. remove$7(root, initialAttribute);
  28271. });
  28272. };
  28273. var changeZIndex = function (blocker) {
  28274. parent(blocker.element).filter(isElement$2).each(function (root) {
  28275. getRaw(root, 'z-index').each(function (zindex) {
  28276. set$8(root, initialAttribute, zindex);
  28277. });
  28278. set$7(root, 'z-index', get$c(blocker.element, 'z-index'));
  28279. });
  28280. };
  28281. var instigate = function (anyComponent, blocker) {
  28282. anyComponent.getSystem().addToGui(blocker);
  28283. changeZIndex(blocker);
  28284. };
  28285. var discard = function (blocker) {
  28286. resetZIndex(blocker);
  28287. blocker.getSystem().removeFromGui(blocker);
  28288. };
  28289. var createComponent = function (component, blockerClass, blockerEvents) {
  28290. return component.getSystem().build(Container.sketch({
  28291. dom: {
  28292. styles: {
  28293. 'left': '0px',
  28294. 'top': '0px',
  28295. 'width': '100%',
  28296. 'height': '100%',
  28297. 'position': 'fixed',
  28298. 'z-index': '1000000000000000'
  28299. },
  28300. classes: [blockerClass]
  28301. },
  28302. events: blockerEvents
  28303. }));
  28304. };
  28305. var SnapSchema = optionObjOf('snaps', [
  28306. required$1('getSnapPoints'),
  28307. onHandler('onSensor'),
  28308. required$1('leftAttr'),
  28309. required$1('topAttr'),
  28310. defaulted('lazyViewport', win),
  28311. defaulted('mustSnap', false)
  28312. ]);
  28313. var schema$6 = [
  28314. defaulted('useFixed', never),
  28315. required$1('blockerClass'),
  28316. defaulted('getTarget', identity$1),
  28317. defaulted('onDrag', noop),
  28318. defaulted('repositionTarget', true),
  28319. defaulted('onDrop', noop),
  28320. defaultedFunction('getBounds', win),
  28321. SnapSchema
  28322. ];
  28323. var getCurrentCoord = function (target) {
  28324. return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  28325. var nu = position === 'fixed' ? fixed : offset;
  28326. return nu(parseInt(left, 10), parseInt(top, 10));
  28327. }).getOrThunk(function () {
  28328. var location = absolute$3(target);
  28329. return absolute(location.left, location.top);
  28330. });
  28331. };
  28332. var clampCoords = function (component, coords, scroll, origin, startData) {
  28333. var bounds = startData.bounds;
  28334. var absoluteCoord = asAbsolute(coords, scroll, origin);
  28335. var newX = clamp$1(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width);
  28336. var newY = clamp$1(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height);
  28337. var newCoords = absolute(newX, newY);
  28338. return coords.fold(function () {
  28339. var offset$1 = asOffset(newCoords, scroll, origin);
  28340. return offset(offset$1.left, offset$1.top);
  28341. }, constant$1(newCoords), function () {
  28342. var fixed$1 = asFixed(newCoords, scroll, origin);
  28343. return fixed(fixed$1.left, fixed$1.top);
  28344. });
  28345. };
  28346. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  28347. var newCoord = optSnaps.fold(function () {
  28348. var translated = translate(currentCoord, delta.left, delta.top);
  28349. var fixedCoord = asFixed(translated, scroll, origin);
  28350. return fixed(fixedCoord.left, fixedCoord.top);
  28351. }, function (snapInfo) {
  28352. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  28353. snapping.extra.each(function (extra) {
  28354. snapInfo.onSensor(component, extra);
  28355. });
  28356. return snapping.coord;
  28357. });
  28358. return clampCoords(component, newCoord, scroll, origin, startData);
  28359. };
  28360. var dragBy = function (component, dragConfig, startData, delta) {
  28361. var target = dragConfig.getTarget(component.element);
  28362. if (dragConfig.repositionTarget) {
  28363. var doc = owner$4(component.element);
  28364. var scroll_1 = get$9(doc);
  28365. var origin_1 = getOrigin(target);
  28366. var currentCoord = getCurrentCoord(target);
  28367. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData);
  28368. var styles = toStyles(newCoord, scroll_1, origin_1);
  28369. setOptions(target, styles);
  28370. }
  28371. dragConfig.onDrag(component, target, delta);
  28372. };
  28373. var calcStartData = function (dragConfig, comp) {
  28374. return {
  28375. bounds: dragConfig.getBounds(),
  28376. height: getOuter$2(comp.element),
  28377. width: getOuter$1(comp.element)
  28378. };
  28379. };
  28380. var move = function (component, dragConfig, dragState, dragMode, event) {
  28381. var delta = dragState.update(dragMode, event);
  28382. var dragStartData = dragState.getStartData().getOrThunk(function () {
  28383. return calcStartData(dragConfig, component);
  28384. });
  28385. delta.each(function (dlt) {
  28386. dragBy(component, dragConfig, dragStartData, dlt);
  28387. });
  28388. };
  28389. var stop = function (component, blocker, dragConfig, dragState) {
  28390. blocker.each(discard);
  28391. dragConfig.snaps.each(function (snapInfo) {
  28392. stopDrag(component, snapInfo);
  28393. });
  28394. var target = dragConfig.getTarget(component.element);
  28395. dragState.reset();
  28396. dragConfig.onDrop(component, target);
  28397. };
  28398. var handlers = function (events) {
  28399. return function (dragConfig, dragState) {
  28400. var updateStartState = function (comp) {
  28401. dragState.setStartData(calcStartData(dragConfig, comp));
  28402. };
  28403. return derive$2(__spreadArray([run$1(windowScroll(), function (comp) {
  28404. dragState.getStartData().each(function () {
  28405. return updateStartState(comp);
  28406. });
  28407. })], events(dragConfig, dragState, updateStartState), true));
  28408. };
  28409. };
  28410. var init$2 = function (dragApi) {
  28411. return derive$2([
  28412. run$1(mousedown(), dragApi.forceDrop),
  28413. run$1(mouseup(), dragApi.drop),
  28414. run$1(mousemove(), function (comp, simulatedEvent) {
  28415. dragApi.move(simulatedEvent.event);
  28416. }),
  28417. run$1(mouseout(), dragApi.delayDrop)
  28418. ]);
  28419. };
  28420. var getData$1 = function (event) {
  28421. return Optional.from(SugarPosition(event.x, event.y));
  28422. };
  28423. var getDelta$1 = function (old, nu) {
  28424. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28425. };
  28426. var MouseData = /*#__PURE__*/Object.freeze({
  28427. __proto__: null,
  28428. getData: getData$1,
  28429. getDelta: getDelta$1
  28430. });
  28431. var events$2 = function (dragConfig, dragState, updateStartState) {
  28432. return [run$1(mousedown(), function (component, simulatedEvent) {
  28433. var raw = simulatedEvent.event.raw;
  28434. if (raw.button !== 0) {
  28435. return;
  28436. }
  28437. simulatedEvent.stop();
  28438. var stop$1 = function () {
  28439. return stop(component, Optional.some(blocker), dragConfig, dragState);
  28440. };
  28441. var delayDrop = DelayedFunction(stop$1, 200);
  28442. var dragApi = {
  28443. drop: stop$1,
  28444. delayDrop: delayDrop.schedule,
  28445. forceDrop: stop$1,
  28446. move: function (event) {
  28447. delayDrop.cancel();
  28448. move(component, dragConfig, dragState, MouseData, event);
  28449. }
  28450. };
  28451. var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi));
  28452. var start = function () {
  28453. updateStartState(component);
  28454. instigate(component, blocker);
  28455. };
  28456. start();
  28457. })];
  28458. };
  28459. var schema$5 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$2) })], false);
  28460. var init$1 = function (dragApi) {
  28461. return derive$2([
  28462. run$1(touchstart(), dragApi.forceDrop),
  28463. run$1(touchend(), dragApi.drop),
  28464. run$1(touchcancel(), dragApi.drop),
  28465. run$1(touchmove(), function (comp, simulatedEvent) {
  28466. dragApi.move(simulatedEvent.event);
  28467. })
  28468. ]);
  28469. };
  28470. var getDataFrom = function (touches) {
  28471. var touch = touches[0];
  28472. return Optional.some(SugarPosition(touch.clientX, touch.clientY));
  28473. };
  28474. var getData = function (event) {
  28475. var raw = event.raw;
  28476. var touches = raw.touches;
  28477. return touches.length === 1 ? getDataFrom(touches) : Optional.none();
  28478. };
  28479. var getDelta = function (old, nu) {
  28480. return SugarPosition(nu.left - old.left, nu.top - old.top);
  28481. };
  28482. var TouchData = /*#__PURE__*/Object.freeze({
  28483. __proto__: null,
  28484. getData: getData,
  28485. getDelta: getDelta
  28486. });
  28487. var events$1 = function (dragConfig, dragState, updateStartState) {
  28488. var blockerSingleton = value$1();
  28489. var stopBlocking = function (component) {
  28490. stop(component, blockerSingleton.get(), dragConfig, dragState);
  28491. blockerSingleton.clear();
  28492. };
  28493. return [
  28494. run$1(touchstart(), function (component, simulatedEvent) {
  28495. simulatedEvent.stop();
  28496. var stop = function () {
  28497. return stopBlocking(component);
  28498. };
  28499. var dragApi = {
  28500. drop: stop,
  28501. delayDrop: noop,
  28502. forceDrop: stop,
  28503. move: function (event) {
  28504. move(component, dragConfig, dragState, TouchData, event);
  28505. }
  28506. };
  28507. var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi));
  28508. blockerSingleton.set(blocker);
  28509. var start = function () {
  28510. updateStartState(component);
  28511. instigate(component, blocker);
  28512. };
  28513. start();
  28514. }),
  28515. run$1(touchmove(), function (component, simulatedEvent) {
  28516. simulatedEvent.stop();
  28517. move(component, dragConfig, dragState, TouchData, simulatedEvent.event);
  28518. }),
  28519. run$1(touchend(), function (component, simulatedEvent) {
  28520. simulatedEvent.stop();
  28521. stopBlocking(component);
  28522. }),
  28523. run$1(touchcancel(), stopBlocking)
  28524. ];
  28525. };
  28526. var schema$4 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$1) })], false);
  28527. var events = function (dragConfig, dragState, updateStartState) {
  28528. return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState), true), events$1(dragConfig, dragState, updateStartState), true);
  28529. };
  28530. var schema$3 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events) })], false);
  28531. var mouse = schema$5;
  28532. var touch = schema$4;
  28533. var mouseOrTouch = schema$3;
  28534. var DraggingBranches = /*#__PURE__*/Object.freeze({
  28535. __proto__: null,
  28536. mouse: mouse,
  28537. touch: touch,
  28538. mouseOrTouch: mouseOrTouch
  28539. });
  28540. var init = function () {
  28541. var previous = Optional.none();
  28542. var startData = Optional.none();
  28543. var reset = function () {
  28544. previous = Optional.none();
  28545. startData = Optional.none();
  28546. };
  28547. var calculateDelta = function (mode, nu) {
  28548. var result = previous.map(function (old) {
  28549. return mode.getDelta(old, nu);
  28550. });
  28551. previous = Optional.some(nu);
  28552. return result;
  28553. };
  28554. var update = function (mode, dragEvent) {
  28555. return mode.getData(dragEvent).bind(function (nuData) {
  28556. return calculateDelta(mode, nuData);
  28557. });
  28558. };
  28559. var setStartData = function (data) {
  28560. startData = Optional.some(data);
  28561. };
  28562. var getStartData = function () {
  28563. return startData;
  28564. };
  28565. var readState = constant$1({});
  28566. return nu$8({
  28567. readState: readState,
  28568. reset: reset,
  28569. update: update,
  28570. getStartData: getStartData,
  28571. setStartData: setStartData
  28572. });
  28573. };
  28574. var DragState = /*#__PURE__*/Object.freeze({
  28575. __proto__: null,
  28576. init: init
  28577. });
  28578. var Dragging = createModes({
  28579. branchKey: 'mode',
  28580. branches: DraggingBranches,
  28581. name: 'dragging',
  28582. active: {
  28583. events: function (dragConfig, dragState) {
  28584. var dragger = dragConfig.dragger;
  28585. return dragger.handlers(dragConfig, dragState);
  28586. }
  28587. },
  28588. extra: {
  28589. snap: function (sConfig) {
  28590. return {
  28591. sensor: sConfig.sensor,
  28592. range: sConfig.range,
  28593. output: sConfig.output,
  28594. extra: Optional.from(sConfig.extra)
  28595. };
  28596. }
  28597. },
  28598. state: DragState,
  28599. apis: DraggingApis
  28600. });
  28601. var snapWidth = 40;
  28602. var snapOffset = snapWidth / 2;
  28603. var calcSnap = function (selectorOpt, td, x, y, width, height) {
  28604. return selectorOpt.fold(function () {
  28605. return Dragging.snap({
  28606. sensor: absolute(x - snapOffset, y - snapOffset),
  28607. range: SugarPosition(width, height),
  28608. output: absolute(Optional.some(x), Optional.some(y)),
  28609. extra: { td: td }
  28610. });
  28611. }, function (selectorHandle) {
  28612. var sensorLeft = x - snapOffset;
  28613. var sensorTop = y - snapOffset;
  28614. var sensorWidth = snapWidth;
  28615. var sensorHeight = snapWidth;
  28616. var rect = selectorHandle.element.dom.getBoundingClientRect();
  28617. return Dragging.snap({
  28618. sensor: absolute(sensorLeft, sensorTop),
  28619. range: SugarPosition(sensorWidth, sensorHeight),
  28620. output: absolute(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)),
  28621. extra: { td: td }
  28622. });
  28623. });
  28624. };
  28625. var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  28626. var isSameCell = function (cellOpt, td) {
  28627. return cellOpt.exists(function (currentTd) {
  28628. return eq(currentTd, td);
  28629. });
  28630. };
  28631. return {
  28632. getSnapPoints: getSnapPoints,
  28633. leftAttr: 'data-drag-left',
  28634. topAttr: 'data-drag-top',
  28635. onSensor: function (component, extra) {
  28636. var td = extra.td;
  28637. if (!isSameCell(cell.get(), td)) {
  28638. cell.set(td);
  28639. onChange(td);
  28640. }
  28641. },
  28642. mustSnap: true
  28643. };
  28644. };
  28645. var createSelector = function (snaps) {
  28646. return record(Button.sketch({
  28647. dom: {
  28648. tag: 'div',
  28649. classes: ['tox-selector']
  28650. },
  28651. buttonBehaviours: derive$1([
  28652. Dragging.config({
  28653. mode: 'mouseOrTouch',
  28654. blockerClass: 'blocker',
  28655. snaps: snaps
  28656. }),
  28657. Unselecting.config({})
  28658. ]),
  28659. eventOrder: {
  28660. mousedown: [
  28661. 'dragging',
  28662. 'alloy.base.behaviour'
  28663. ],
  28664. touchstart: [
  28665. 'dragging',
  28666. 'alloy.base.behaviour'
  28667. ]
  28668. }
  28669. }));
  28670. };
  28671. var setup$4 = function (editor, sink) {
  28672. var tlTds = Cell([]);
  28673. var brTds = Cell([]);
  28674. var isVisible = Cell(false);
  28675. var startCell = value$1();
  28676. var finishCell = value$1();
  28677. var getTopLeftSnap = function (td) {
  28678. var box = absolute$2(td);
  28679. return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  28680. };
  28681. var getTopLeftSnaps = function () {
  28682. return map$2(tlTds.get(), function (td) {
  28683. return getTopLeftSnap(td);
  28684. });
  28685. };
  28686. var getBottomRightSnap = function (td) {
  28687. var box = absolute$2(td);
  28688. return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  28689. };
  28690. var getBottomRightSnaps = function () {
  28691. return map$2(brTds.get(), function (td) {
  28692. return getBottomRightSnap(td);
  28693. });
  28694. };
  28695. var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  28696. finishCell.get().each(function (finish) {
  28697. editor.fire('TableSelectorChange', {
  28698. start: start,
  28699. finish: finish
  28700. });
  28701. });
  28702. });
  28703. var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  28704. startCell.get().each(function (start) {
  28705. editor.fire('TableSelectorChange', {
  28706. start: start,
  28707. finish: finish
  28708. });
  28709. });
  28710. });
  28711. var memTopLeft = createSelector(topLeftSnaps);
  28712. var memBottomRight = createSelector(bottomRightSnaps);
  28713. var topLeft = build$1(memTopLeft.asSpec());
  28714. var bottomRight = build$1(memBottomRight.asSpec());
  28715. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  28716. var cellRect = cell.dom.getBoundingClientRect();
  28717. remove$6(selector.element, 'display');
  28718. var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight;
  28719. var aboveViewport = isAbove(cellRect);
  28720. var belowViewport = isBelow(cellRect, viewportHeight);
  28721. if (aboveViewport || belowViewport) {
  28722. set$7(selector.element, 'display', 'none');
  28723. }
  28724. };
  28725. var snapTo = function (selector, cell, getSnapConfig, pos) {
  28726. var snap = getSnapConfig(cell);
  28727. Dragging.snapTo(selector, snap);
  28728. var isAbove = function (rect) {
  28729. return rect[pos] < 0;
  28730. };
  28731. var isBelow = function (rect, viewportHeight) {
  28732. return rect[pos] > viewportHeight;
  28733. };
  28734. showOrHideHandle(selector, cell, isAbove, isBelow);
  28735. };
  28736. var snapTopLeft = function (cell) {
  28737. return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  28738. };
  28739. var snapLastTopLeft = function () {
  28740. return startCell.get().each(snapTopLeft);
  28741. };
  28742. var snapBottomRight = function (cell) {
  28743. return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  28744. };
  28745. var snapLastBottomRight = function () {
  28746. return finishCell.get().each(snapBottomRight);
  28747. };
  28748. if (detect$1().deviceType.isTouch()) {
  28749. editor.on('TableSelectionChange', function (e) {
  28750. if (!isVisible.get()) {
  28751. attach(sink, topLeft);
  28752. attach(sink, bottomRight);
  28753. isVisible.set(true);
  28754. }
  28755. startCell.set(e.start);
  28756. finishCell.set(e.finish);
  28757. e.otherCells.each(function (otherCells) {
  28758. tlTds.set(otherCells.upOrLeftCells);
  28759. brTds.set(otherCells.downOrRightCells);
  28760. snapTopLeft(e.start);
  28761. snapBottomRight(e.finish);
  28762. });
  28763. });
  28764. editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  28765. snapLastTopLeft();
  28766. snapLastBottomRight();
  28767. });
  28768. editor.on('TableSelectionClear', function () {
  28769. if (isVisible.get()) {
  28770. detach(topLeft);
  28771. detach(bottomRight);
  28772. isVisible.set(false);
  28773. }
  28774. startCell.clear();
  28775. finishCell.clear();
  28776. });
  28777. }
  28778. };
  28779. var isHidden = function (elm) {
  28780. if (elm.nodeType === 1) {
  28781. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  28782. return true;
  28783. }
  28784. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  28785. return true;
  28786. }
  28787. }
  28788. return false;
  28789. };
  28790. var renderElementPath = function (editor, settings, providersBackstage) {
  28791. if (!settings.delimiter) {
  28792. settings.delimiter = '\xBB';
  28793. }
  28794. var getDataPath = function (data) {
  28795. var parts = data || [];
  28796. var newPathElements = map$2(parts, function (part, index) {
  28797. return Button.sketch({
  28798. dom: {
  28799. tag: 'div',
  28800. classes: ['tox-statusbar__path-item'],
  28801. attributes: {
  28802. 'role': 'button',
  28803. 'data-index': index,
  28804. 'tab-index': -1,
  28805. 'aria-level': index + 1
  28806. },
  28807. innerHtml: part.name
  28808. },
  28809. action: function (_btn) {
  28810. editor.focus();
  28811. editor.selection.select(part.element);
  28812. editor.nodeChanged();
  28813. },
  28814. buttonBehaviours: derive$1([
  28815. DisablingConfigs.button(providersBackstage.isDisabled),
  28816. receivingConfig()
  28817. ])
  28818. });
  28819. });
  28820. var divider = {
  28821. dom: {
  28822. tag: 'div',
  28823. classes: ['tox-statusbar__path-divider'],
  28824. attributes: { 'aria-hidden': true },
  28825. innerHtml: ' ' + settings.delimiter + ' '
  28826. }
  28827. };
  28828. return foldl(newPathElements.slice(1), function (acc, element) {
  28829. var newAcc = acc;
  28830. newAcc.push(divider);
  28831. newAcc.push(element);
  28832. return newAcc;
  28833. }, [newPathElements[0]]);
  28834. };
  28835. var updatePath = function (parents) {
  28836. var newPath = [];
  28837. var i = parents.length;
  28838. while (i-- > 0) {
  28839. var parent_1 = parents[i];
  28840. if (parent_1.nodeType === 1 && !isHidden(parent_1)) {
  28841. var args = editor.fire('ResolveName', {
  28842. name: parent_1.nodeName.toLowerCase(),
  28843. target: parent_1
  28844. });
  28845. if (!args.isDefaultPrevented()) {
  28846. newPath.push({
  28847. name: args.name,
  28848. element: parent_1
  28849. });
  28850. }
  28851. if (args.isPropagationStopped()) {
  28852. break;
  28853. }
  28854. }
  28855. }
  28856. return newPath;
  28857. };
  28858. return {
  28859. dom: {
  28860. tag: 'div',
  28861. classes: ['tox-statusbar__path'],
  28862. attributes: { role: 'navigation' }
  28863. },
  28864. behaviours: derive$1([
  28865. Keying.config({
  28866. mode: 'flow',
  28867. selector: 'div[role=button]'
  28868. }),
  28869. Disabling.config({ disabled: providersBackstage.isDisabled }),
  28870. receivingConfig(),
  28871. Tabstopping.config({}),
  28872. Replacing.config({}),
  28873. config('elementPathEvents', [runOnAttached(function (comp, _e) {
  28874. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  28875. return Keying.focusIn(comp);
  28876. });
  28877. editor.on('NodeChange', function (e) {
  28878. var newPath = updatePath(e.parents);
  28879. if (newPath.length > 0) {
  28880. Replacing.set(comp, getDataPath(newPath));
  28881. } else {
  28882. Replacing.set(comp, []);
  28883. }
  28884. });
  28885. })])
  28886. ]),
  28887. components: []
  28888. };
  28889. };
  28890. var ResizeTypes;
  28891. (function (ResizeTypes) {
  28892. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  28893. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  28894. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  28895. }(ResizeTypes || (ResizeTypes = {})));
  28896. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  28897. var dimensions = {};
  28898. dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor));
  28899. if (resizeType === ResizeTypes.Both) {
  28900. dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor));
  28901. }
  28902. return dimensions;
  28903. };
  28904. var resize = function (editor, deltas, resizeType) {
  28905. var container = SugarElement.fromDom(editor.getContainer());
  28906. var dimensions = getDimensions(editor, deltas, resizeType, get$b(container), get$a(container));
  28907. each(dimensions, function (val, dim) {
  28908. return set$7(container, dim, numToPx(val));
  28909. });
  28910. fireResizeEditor(editor);
  28911. };
  28912. var getResizeType = function (editor) {
  28913. var fallback = !editor.hasPlugin('autoresize');
  28914. var resize = editor.getParam('resize', fallback);
  28915. if (resize === false) {
  28916. return ResizeTypes.None;
  28917. } else if (resize === 'both') {
  28918. return ResizeTypes.Both;
  28919. } else {
  28920. return ResizeTypes.Vertical;
  28921. }
  28922. };
  28923. var keyboardHandler = function (editor, resizeType, x, y) {
  28924. var scale = 20;
  28925. var delta = SugarPosition(x * scale, y * scale);
  28926. resize(editor, delta, resizeType);
  28927. return Optional.some(true);
  28928. };
  28929. var renderResizeHandler = function (editor, providersBackstage) {
  28930. var resizeType = getResizeType(editor);
  28931. if (resizeType === ResizeTypes.None) {
  28932. return Optional.none();
  28933. }
  28934. return Optional.some(render$3('resize-handle', {
  28935. tag: 'div',
  28936. classes: ['tox-statusbar__resize-handle'],
  28937. attributes: { title: providersBackstage.translate('Resize') },
  28938. behaviours: [
  28939. Dragging.config({
  28940. mode: 'mouse',
  28941. repositionTarget: false,
  28942. onDrag: function (_comp, _target, delta) {
  28943. return resize(editor, delta, resizeType);
  28944. },
  28945. blockerClass: 'tox-blocker'
  28946. }),
  28947. Keying.config({
  28948. mode: 'special',
  28949. onLeft: function () {
  28950. return keyboardHandler(editor, resizeType, -1, 0);
  28951. },
  28952. onRight: function () {
  28953. return keyboardHandler(editor, resizeType, 1, 0);
  28954. },
  28955. onUp: function () {
  28956. return keyboardHandler(editor, resizeType, 0, -1);
  28957. },
  28958. onDown: function () {
  28959. return keyboardHandler(editor, resizeType, 0, 1);
  28960. }
  28961. }),
  28962. Tabstopping.config({}),
  28963. Focusing.config({})
  28964. ]
  28965. }, providersBackstage.icons));
  28966. };
  28967. var renderWordCount = function (editor, providersBackstage) {
  28968. var _a;
  28969. var replaceCountText = function (comp, count, mode) {
  28970. return Replacing.set(comp, [text(providersBackstage.translate([
  28971. '{0} ' + mode,
  28972. count[mode]
  28973. ]))]);
  28974. };
  28975. return Button.sketch({
  28976. dom: {
  28977. tag: 'button',
  28978. classes: ['tox-statusbar__wordcount']
  28979. },
  28980. components: [],
  28981. buttonBehaviours: derive$1([
  28982. DisablingConfigs.button(providersBackstage.isDisabled),
  28983. receivingConfig(),
  28984. Tabstopping.config({}),
  28985. Replacing.config({}),
  28986. Representing.config({
  28987. store: {
  28988. mode: 'memory',
  28989. initialValue: {
  28990. mode: 'words',
  28991. count: {
  28992. words: 0,
  28993. characters: 0
  28994. }
  28995. }
  28996. }
  28997. }),
  28998. config('wordcount-events', [
  28999. runOnExecute$1(function (comp) {
  29000. var currentVal = Representing.getValue(comp);
  29001. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  29002. Representing.setValue(comp, {
  29003. mode: newMode,
  29004. count: currentVal.count
  29005. });
  29006. replaceCountText(comp, currentVal.count, newMode);
  29007. }),
  29008. runOnAttached(function (comp) {
  29009. editor.on('wordCountUpdate', function (e) {
  29010. var mode = Representing.getValue(comp).mode;
  29011. Representing.setValue(comp, {
  29012. mode: mode,
  29013. count: e.wordCount
  29014. });
  29015. replaceCountText(comp, e.wordCount, mode);
  29016. });
  29017. })
  29018. ])
  29019. ]),
  29020. eventOrder: (_a = {}, _a[execute$5()] = [
  29021. 'disabling',
  29022. 'alloy.base.behaviour',
  29023. 'wordcount-events'
  29024. ], _a)
  29025. });
  29026. };
  29027. var renderStatusbar = function (editor, providersBackstage) {
  29028. var renderBranding = function () {
  29029. var label = global$e.translate([
  29030. 'Powered by {0}',
  29031. 'Tiny'
  29032. ]);
  29033. 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>';
  29034. return {
  29035. dom: {
  29036. tag: 'span',
  29037. classes: ['tox-statusbar__branding'],
  29038. innerHtml: linkHtml
  29039. }
  29040. };
  29041. };
  29042. var getTextComponents = function () {
  29043. var components = [];
  29044. if (editor.getParam('elementpath', true, 'boolean')) {
  29045. components.push(renderElementPath(editor, {}, providersBackstage));
  29046. }
  29047. if (editor.hasPlugin('wordcount')) {
  29048. components.push(renderWordCount(editor, providersBackstage));
  29049. }
  29050. if (editor.getParam('branding', true, 'boolean')) {
  29051. components.push(renderBranding());
  29052. }
  29053. if (components.length > 0) {
  29054. return [{
  29055. dom: {
  29056. tag: 'div',
  29057. classes: ['tox-statusbar__text-container']
  29058. },
  29059. components: components
  29060. }];
  29061. }
  29062. return [];
  29063. };
  29064. var getComponents = function () {
  29065. var components = getTextComponents();
  29066. var resizeHandler = renderResizeHandler(editor, providersBackstage);
  29067. return components.concat(resizeHandler.toArray());
  29068. };
  29069. return {
  29070. dom: {
  29071. tag: 'div',
  29072. classes: ['tox-statusbar']
  29073. },
  29074. components: getComponents()
  29075. };
  29076. };
  29077. var setup$3 = function (editor) {
  29078. var _a;
  29079. var isInline = editor.inline;
  29080. var mode = isInline ? Inline : Iframe;
  29081. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  29082. var lazyOuterContainer = Optional.none();
  29083. var platform = detect$1();
  29084. var isIE = platform.browser.isIE();
  29085. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  29086. var isTouch = platform.deviceType.isTouch();
  29087. var touchPlatformClass = 'tox-platform-touch';
  29088. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  29089. var isToolbarBottom = isToolbarLocationBottom(editor);
  29090. var uiContainer = getUiContainer(editor);
  29091. var dirAttributes = global$e.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  29092. var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
  29093. var lazyHeader = function () {
  29094. return lazyOuterContainer.bind(OuterContainer.getHeader);
  29095. };
  29096. var isHeaderDocked = function () {
  29097. return header.isDocked(lazyHeader);
  29098. };
  29099. var resizeUiMothership = function () {
  29100. set$7(uiMothership.element, 'width', document.body.clientWidth + 'px');
  29101. };
  29102. var makeSinkDefinition = function () {
  29103. var isGridUiContainer = eq(body(), uiContainer) && get$c(uiContainer, 'display') === 'grid';
  29104. var sinkSpec = {
  29105. dom: __assign({
  29106. tag: 'div',
  29107. classes: [
  29108. 'tox',
  29109. 'tox-silver-sink',
  29110. 'tox-tinymce-aux'
  29111. ].concat(platformClasses).concat(deviceClasses)
  29112. }, dirAttributes),
  29113. behaviours: derive$1([Positioning.config({
  29114. useFixed: function () {
  29115. return isHeaderDocked();
  29116. }
  29117. })])
  29118. };
  29119. var reactiveWidthSpec = {
  29120. dom: { styles: { width: document.body.clientWidth + 'px' } },
  29121. events: derive$2([run$1(windowResize(), resizeUiMothership)])
  29122. };
  29123. return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {});
  29124. };
  29125. var sink = build$1(makeSinkDefinition());
  29126. var lazySink = function () {
  29127. return Result.value(sink);
  29128. };
  29129. var memAnchorBar = record({
  29130. dom: {
  29131. tag: 'div',
  29132. classes: ['tox-anchorbar']
  29133. }
  29134. });
  29135. var lazyAnchorBar = function () {
  29136. return lazyOuterContainer.bind(function (container) {
  29137. return memAnchorBar.getOpt(container);
  29138. }).getOrDie('Could not find a anchor bar element');
  29139. };
  29140. var lazyToolbar = function () {
  29141. return lazyOuterContainer.bind(function (container) {
  29142. return OuterContainer.getToolbar(container);
  29143. }).getOrDie('Could not find more toolbar element');
  29144. };
  29145. var lazyThrobber = function () {
  29146. return lazyOuterContainer.bind(function (container) {
  29147. return OuterContainer.getThrobber(container);
  29148. }).getOrDie('Could not find throbber element');
  29149. };
  29150. var backstage = init$7(sink, editor, lazyAnchorBar);
  29151. var partMenubar = OuterContainer.parts.menubar({
  29152. dom: {
  29153. tag: 'div',
  29154. classes: ['tox-menubar']
  29155. },
  29156. backstage: backstage,
  29157. onEscape: function () {
  29158. editor.focus();
  29159. }
  29160. });
  29161. var toolbarMode = getToolbarMode(editor);
  29162. var partToolbar = OuterContainer.parts.toolbar(__assign({
  29163. dom: {
  29164. tag: 'div',
  29165. classes: ['tox-toolbar']
  29166. },
  29167. getSink: lazySink,
  29168. providers: backstage.shared.providers,
  29169. onEscape: function () {
  29170. editor.focus();
  29171. },
  29172. type: toolbarMode,
  29173. lazyToolbar: lazyToolbar,
  29174. lazyHeader: function () {
  29175. return lazyHeader().getOrDie('Could not find header element');
  29176. }
  29177. }, verticalDirAttributes));
  29178. var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({
  29179. dom: {
  29180. tag: 'div',
  29181. classes: ['tox-toolbar-overlord']
  29182. },
  29183. providers: backstage.shared.providers,
  29184. onEscape: function () {
  29185. editor.focus();
  29186. },
  29187. type: toolbarMode
  29188. });
  29189. var partSocket = OuterContainer.parts.socket({
  29190. dom: {
  29191. tag: 'div',
  29192. classes: ['tox-edit-area']
  29193. }
  29194. });
  29195. var partSidebar = OuterContainer.parts.sidebar({
  29196. dom: {
  29197. tag: 'div',
  29198. classes: ['tox-sidebar']
  29199. }
  29200. });
  29201. var partThrobber = OuterContainer.parts.throbber({
  29202. dom: {
  29203. tag: 'div',
  29204. classes: ['tox-throbber']
  29205. },
  29206. backstage: backstage
  29207. });
  29208. var sb = editor.getParam('statusbar', true, 'boolean');
  29209. var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none();
  29210. var socketSidebarContainer = {
  29211. dom: {
  29212. tag: 'div',
  29213. classes: ['tox-sidebar-wrap']
  29214. },
  29215. components: [
  29216. partSocket,
  29217. partSidebar
  29218. ]
  29219. };
  29220. var hasMultipleToolbar = isMultipleToolbars(editor);
  29221. var hasToolbar = isToolbarEnabled(editor);
  29222. var hasMenubar = isMenubarEnabled(editor);
  29223. var getPartToolbar = function () {
  29224. if (hasMultipleToolbar) {
  29225. return [partMultipleToolbar];
  29226. } else if (hasToolbar) {
  29227. return [partToolbar];
  29228. } else {
  29229. return [];
  29230. }
  29231. };
  29232. var partHeader = OuterContainer.parts.header({
  29233. dom: __assign({
  29234. tag: 'div',
  29235. classes: ['tox-editor-header']
  29236. }, verticalDirAttributes),
  29237. components: flatten([
  29238. hasMenubar ? [partMenubar] : [],
  29239. getPartToolbar(),
  29240. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  29241. ]),
  29242. sticky: isStickyToolbar(editor),
  29243. editor: editor,
  29244. sharedBackstage: backstage.shared
  29245. });
  29246. var editorComponents = flatten([
  29247. isToolbarBottom ? [] : [partHeader],
  29248. isInline ? [] : [socketSidebarContainer],
  29249. isToolbarBottom ? [partHeader] : []
  29250. ]);
  29251. var editorContainer = {
  29252. dom: {
  29253. tag: 'div',
  29254. classes: ['tox-editor-container']
  29255. },
  29256. components: editorComponents
  29257. };
  29258. var containerComponents = flatten([
  29259. [editorContainer],
  29260. isInline ? [] : statusbar.toArray(),
  29261. [partThrobber]
  29262. ]);
  29263. var isHidden = isDistractionFree(editor);
  29264. var attributes = __assign(__assign({ role: 'application' }, global$e.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  29265. var outerContainer = build$1(OuterContainer.sketch({
  29266. dom: {
  29267. tag: 'div',
  29268. classes: [
  29269. 'tox',
  29270. 'tox-tinymce'
  29271. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
  29272. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  29273. opacity: '0',
  29274. border: '0'
  29275. } : {}),
  29276. attributes: attributes
  29277. },
  29278. components: containerComponents,
  29279. behaviours: derive$1([
  29280. receivingConfig(),
  29281. Disabling.config({ disableClass: 'tox-tinymce--disabled' }),
  29282. Keying.config({
  29283. mode: 'cyclic',
  29284. 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'
  29285. })
  29286. ])
  29287. }));
  29288. lazyOuterContainer = Optional.some(outerContainer);
  29289. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  29290. OuterContainer.focusMenubar(outerContainer);
  29291. });
  29292. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  29293. OuterContainer.focusToolbar(outerContainer);
  29294. });
  29295. editor.addCommand('ToggleToolbarDrawer', function () {
  29296. OuterContainer.toggleToolbarDrawer(outerContainer);
  29297. });
  29298. editor.addQueryStateHandler('ToggleToolbarDrawer', function () {
  29299. return OuterContainer.isToolbarDrawerToggled(outerContainer);
  29300. });
  29301. var mothership = takeover(outerContainer);
  29302. var uiMothership = takeover(sink);
  29303. setup$b(editor, mothership, uiMothership);
  29304. var getUi = function () {
  29305. var channels = {
  29306. broadcastAll: uiMothership.broadcast,
  29307. broadcastOn: uiMothership.broadcastOn,
  29308. register: noop
  29309. };
  29310. return { channels: channels };
  29311. };
  29312. var setEditorSize = function () {
  29313. var parsedHeight = numToPx(getHeightWithFallback(editor));
  29314. var parsedWidth = numToPx(getWidthWithFallback(editor));
  29315. if (!editor.inline) {
  29316. if (isValidValue('div', 'width', parsedWidth)) {
  29317. set$7(outerContainer.element, 'width', parsedWidth);
  29318. }
  29319. if (isValidValue('div', 'height', parsedHeight)) {
  29320. set$7(outerContainer.element, 'height', parsedHeight);
  29321. } else {
  29322. set$7(outerContainer.element, 'height', '200px');
  29323. }
  29324. }
  29325. return parsedHeight;
  29326. };
  29327. var renderUI = function () {
  29328. header.setup(editor, backstage.shared, lazyHeader);
  29329. setup$6(editor, backstage);
  29330. setup$5(editor, lazySink, backstage);
  29331. setup$8(editor);
  29332. setup$7(editor, lazyThrobber, backstage.shared);
  29333. map$1(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  29334. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  29335. });
  29336. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  29337. var toolbarOpt = getMultipleToolbarsSetting(editor);
  29338. var rawUiConfig = {
  29339. menuItems: menuItems,
  29340. menus: getMenus(editor),
  29341. menubar: getMenubar(editor),
  29342. toolbar: toolbarOpt.getOrThunk(function () {
  29343. return getToolbar(editor);
  29344. }),
  29345. allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  29346. buttons: buttons,
  29347. sidebar: sidebars
  29348. };
  29349. register$7(editor, contextToolbars, sink, { backstage: backstage });
  29350. setup$4(editor, sink);
  29351. var elm = editor.getElement();
  29352. var height = setEditorSize();
  29353. var uiComponents = {
  29354. mothership: mothership,
  29355. uiMothership: uiMothership,
  29356. outerContainer: outerContainer
  29357. };
  29358. var args = {
  29359. targetNode: elm,
  29360. height: height
  29361. };
  29362. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  29363. };
  29364. return {
  29365. mothership: mothership,
  29366. uiMothership: uiMothership,
  29367. backstage: backstage,
  29368. renderUI: renderUI,
  29369. getUi: getUi
  29370. };
  29371. };
  29372. var describedBy = function (describedElement, describeElement) {
  29373. var describeId = Optional.from(get$d(describedElement, 'id')).fold(function () {
  29374. var id = generate$6('dialog-describe');
  29375. set$8(describeElement, 'id', id);
  29376. return id;
  29377. }, identity$1);
  29378. set$8(describedElement, 'aria-describedby', describeId);
  29379. };
  29380. var labelledBy = function (labelledElement, labelElement) {
  29381. var labelId = getOpt(labelledElement, 'id').fold(function () {
  29382. var id = generate$6('dialog-label');
  29383. set$8(labelElement, 'id', id);
  29384. return id;
  29385. }, identity$1);
  29386. set$8(labelledElement, 'aria-labelledby', labelId);
  29387. };
  29388. var schema$2 = constant$1([
  29389. required$1('lazySink'),
  29390. option('dragBlockClass'),
  29391. defaultedFunction('getBounds', win),
  29392. defaulted('useTabstopAt', always),
  29393. defaulted('eventOrder', {}),
  29394. field('modalBehaviours', [Keying]),
  29395. onKeyboardHandler('onExecute'),
  29396. onStrictKeyboardHandler('onEscape')
  29397. ]);
  29398. var basic = { sketch: identity$1 };
  29399. var parts$2 = constant$1([
  29400. optional({
  29401. name: 'draghandle',
  29402. overrides: function (detail, spec) {
  29403. return {
  29404. behaviours: derive$1([Dragging.config({
  29405. mode: 'mouse',
  29406. getTarget: function (handle) {
  29407. return ancestor(handle, '[role="dialog"]').getOr(handle);
  29408. },
  29409. 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),
  29410. getBounds: detail.getDragBounds
  29411. })])
  29412. };
  29413. }
  29414. }),
  29415. required({
  29416. schema: [required$1('dom')],
  29417. name: 'title'
  29418. }),
  29419. required({
  29420. factory: basic,
  29421. schema: [required$1('dom')],
  29422. name: 'close'
  29423. }),
  29424. required({
  29425. factory: basic,
  29426. schema: [required$1('dom')],
  29427. name: 'body'
  29428. }),
  29429. optional({
  29430. factory: basic,
  29431. schema: [required$1('dom')],
  29432. name: 'footer'
  29433. }),
  29434. external$1({
  29435. factory: {
  29436. sketch: function (spec, detail) {
  29437. return __assign(__assign({}, spec), {
  29438. dom: detail.dom,
  29439. components: detail.components
  29440. });
  29441. }
  29442. },
  29443. schema: [
  29444. defaulted('dom', {
  29445. tag: 'div',
  29446. styles: {
  29447. position: 'fixed',
  29448. left: '0px',
  29449. top: '0px',
  29450. right: '0px',
  29451. bottom: '0px'
  29452. }
  29453. }),
  29454. defaulted('components', [])
  29455. ],
  29456. name: 'blocker'
  29457. })
  29458. ]);
  29459. var factory$4 = function (detail, components, spec, externals) {
  29460. var _a;
  29461. var dialogComp = value$1();
  29462. var showDialog = function (dialog) {
  29463. dialogComp.set(dialog);
  29464. var sink = detail.lazySink(dialog).getOrDie();
  29465. var externalBlocker = externals.blocker();
  29466. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  29467. components: externalBlocker.components.concat([premade(dialog)]),
  29468. behaviours: derive$1([
  29469. Focusing.config({}),
  29470. config('dialog-blocker-events', [runOnSource(focusin(), function () {
  29471. Keying.focusIn(dialog);
  29472. })])
  29473. ])
  29474. }));
  29475. attach(sink, blocker);
  29476. Keying.focusIn(dialog);
  29477. };
  29478. var hideDialog = function (dialog) {
  29479. dialogComp.clear();
  29480. parent(dialog.element).each(function (blockerDom) {
  29481. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  29482. detach(blocker);
  29483. });
  29484. });
  29485. };
  29486. var getDialogBody = function (dialog) {
  29487. return getPartOrDie(dialog, detail, 'body');
  29488. };
  29489. var getDialogFooter = function (dialog) {
  29490. return getPartOrDie(dialog, detail, 'footer');
  29491. };
  29492. var setBusy = function (dialog, getBusySpec) {
  29493. Blocking.block(dialog, getBusySpec);
  29494. };
  29495. var setIdle = function (dialog) {
  29496. Blocking.unblock(dialog);
  29497. };
  29498. var modalEventsId = generate$6('modal-events');
  29499. var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a));
  29500. return {
  29501. uid: detail.uid,
  29502. dom: detail.dom,
  29503. components: components,
  29504. apis: {
  29505. show: showDialog,
  29506. hide: hideDialog,
  29507. getBody: getDialogBody,
  29508. getFooter: getDialogFooter,
  29509. setIdle: setIdle,
  29510. setBusy: setBusy
  29511. },
  29512. eventOrder: eventOrder,
  29513. domModification: {
  29514. attributes: {
  29515. 'role': 'dialog',
  29516. 'aria-modal': 'true'
  29517. }
  29518. },
  29519. behaviours: augment(detail.modalBehaviours, [
  29520. Replacing.config({}),
  29521. Keying.config({
  29522. mode: 'cyclic',
  29523. onEnter: detail.onExecute,
  29524. onEscape: detail.onEscape,
  29525. useTabstopAt: detail.useTabstopAt
  29526. }),
  29527. Blocking.config({ getRoot: dialogComp.get }),
  29528. config(modalEventsId, [runOnAttached(function (c) {
  29529. labelledBy(c.element, getPartOrDie(c, detail, 'title').element);
  29530. describedBy(c.element, getPartOrDie(c, detail, 'body').element);
  29531. })])
  29532. ])
  29533. };
  29534. };
  29535. var ModalDialog = composite({
  29536. name: 'ModalDialog',
  29537. configFields: schema$2(),
  29538. partFields: parts$2(),
  29539. factory: factory$4,
  29540. apis: {
  29541. show: function (apis, dialog) {
  29542. apis.show(dialog);
  29543. },
  29544. hide: function (apis, dialog) {
  29545. apis.hide(dialog);
  29546. },
  29547. getBody: function (apis, dialog) {
  29548. return apis.getBody(dialog);
  29549. },
  29550. getFooter: function (apis, dialog) {
  29551. return apis.getFooter(dialog);
  29552. },
  29553. setBusy: function (apis, dialog, getBusySpec) {
  29554. apis.setBusy(dialog, getBusySpec);
  29555. },
  29556. setIdle: function (apis, dialog) {
  29557. apis.setIdle(dialog);
  29558. }
  29559. }
  29560. });
  29561. var dialogToggleMenuItemSchema = objOf([
  29562. requiredString('type'),
  29563. requiredString('name')
  29564. ].concat(commonMenuItemFields));
  29565. var dialogToggleMenuItemDataProcessor = boolean;
  29566. var baseFooterButtonFields = [
  29567. field$1('name', 'name', defaultedThunk(function () {
  29568. return generate$6('button-name');
  29569. }), string),
  29570. optionString('icon'),
  29571. defaultedStringEnum('align', 'end', [
  29572. 'start',
  29573. 'end'
  29574. ]),
  29575. defaultedBoolean('primary', false),
  29576. defaultedBoolean('disabled', false)
  29577. ];
  29578. var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields, true), [requiredString('text')], false);
  29579. var normalFooterButtonFields = __spreadArray([requiredStringEnum('type', [
  29580. 'submit',
  29581. 'cancel',
  29582. 'custom'
  29583. ])], dialogFooterButtonFields, true);
  29584. var menuFooterButtonFields = __spreadArray([
  29585. requiredStringEnum('type', ['menu']),
  29586. optionString('text'),
  29587. optionString('tooltip'),
  29588. optionString('icon'),
  29589. requiredArrayOf('items', dialogToggleMenuItemSchema)
  29590. ], baseFooterButtonFields, true);
  29591. var dialogFooterButtonSchema = choose$1('type', {
  29592. submit: normalFooterButtonFields,
  29593. cancel: normalFooterButtonFields,
  29594. custom: normalFooterButtonFields,
  29595. menu: menuFooterButtonFields
  29596. });
  29597. var alertBannerFields = [
  29598. requiredString('type'),
  29599. requiredString('text'),
  29600. requiredStringEnum('level', [
  29601. 'info',
  29602. 'warn',
  29603. 'error',
  29604. 'success'
  29605. ]),
  29606. requiredString('icon'),
  29607. defaulted('url', '')
  29608. ];
  29609. var alertBannerSchema = objOf(alertBannerFields);
  29610. var createBarFields = function (itemsField) {
  29611. return [
  29612. requiredString('type'),
  29613. itemsField
  29614. ];
  29615. };
  29616. var buttonFields = [
  29617. requiredString('type'),
  29618. requiredString('text'),
  29619. defaultedBoolean('disabled', false),
  29620. defaultedBoolean('primary', false),
  29621. field$1('name', 'name', defaultedThunk(function () {
  29622. return generate$6('button-name');
  29623. }), string),
  29624. optionString('icon'),
  29625. defaultedBoolean('borderless', false)
  29626. ];
  29627. var buttonSchema = objOf(buttonFields);
  29628. var checkboxFields = [
  29629. requiredString('type'),
  29630. requiredString('name'),
  29631. requiredString('label'),
  29632. defaultedBoolean('disabled', false)
  29633. ];
  29634. var checkboxSchema = objOf(checkboxFields);
  29635. var checkboxDataProcessor = boolean;
  29636. var formComponentFields = [
  29637. requiredString('type'),
  29638. requiredString('name')
  29639. ];
  29640. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  29641. var collectionFields = formComponentWithLabelFields.concat([defaulted('columns', 'auto')]);
  29642. var collectionSchema = objOf(collectionFields);
  29643. var collectionDataProcessor = arrOfObj([
  29644. requiredString('value'),
  29645. requiredString('text'),
  29646. requiredString('icon')
  29647. ]);
  29648. var colorInputFields = formComponentWithLabelFields;
  29649. var colorInputSchema = objOf(colorInputFields);
  29650. var colorInputDataProcessor = string;
  29651. var colorPickerFields = formComponentWithLabelFields;
  29652. var colorPickerSchema = objOf(colorPickerFields);
  29653. var colorPickerDataProcessor = string;
  29654. var customEditorFields = formComponentFields.concat([
  29655. defaultedString('tag', 'textarea'),
  29656. requiredString('scriptId'),
  29657. requiredString('scriptUrl'),
  29658. defaultedPostMsg('settings', undefined)
  29659. ]);
  29660. var customEditorFieldsOld = formComponentFields.concat([
  29661. defaultedString('tag', 'textarea'),
  29662. requiredFunction('init')
  29663. ]);
  29664. var customEditorSchema = valueOf(function (v) {
  29665. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  29666. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  29667. });
  29668. });
  29669. var customEditorDataProcessor = string;
  29670. var dropZoneFields = formComponentWithLabelFields;
  29671. var dropZoneSchema = objOf(dropZoneFields);
  29672. var dropZoneDataProcessor = arrOfVal();
  29673. var createGridFields = function (itemsField) {
  29674. return [
  29675. requiredString('type'),
  29676. requiredNumber('columns'),
  29677. itemsField
  29678. ];
  29679. };
  29680. var htmlPanelFields = [
  29681. requiredString('type'),
  29682. requiredString('html'),
  29683. defaultedStringEnum('presets', 'presentation', [
  29684. 'presentation',
  29685. 'document'
  29686. ])
  29687. ];
  29688. var htmlPanelSchema = objOf(htmlPanelFields);
  29689. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  29690. var iframeSchema = objOf(iframeFields);
  29691. var iframeDataProcessor = string;
  29692. var imageToolsFields = formComponentWithLabelFields.concat([requiredOf('currentState', objOf([
  29693. required$1('blob'),
  29694. requiredString('url')
  29695. ]))]);
  29696. var imageToolsSchema = objOf(imageToolsFields);
  29697. var inputFields = formComponentWithLabelFields.concat([
  29698. optionString('inputMode'),
  29699. optionString('placeholder'),
  29700. defaultedBoolean('maximized', false),
  29701. defaultedBoolean('disabled', false)
  29702. ]);
  29703. var inputSchema = objOf(inputFields);
  29704. var inputDataProcessor = string;
  29705. var createLabelFields = function (itemsField) {
  29706. return [
  29707. requiredString('type'),
  29708. requiredString('label'),
  29709. itemsField
  29710. ];
  29711. };
  29712. var listBoxSingleItemFields = [
  29713. requiredString('text'),
  29714. requiredString('value')
  29715. ];
  29716. var listBoxNestedItemFields = [
  29717. requiredString('text'),
  29718. requiredArrayOf('items', thunkOf('items', function () {
  29719. return listBoxItemSchema;
  29720. }))
  29721. ];
  29722. var listBoxItemSchema = oneOf([
  29723. objOf(listBoxSingleItemFields),
  29724. objOf(listBoxNestedItemFields)
  29725. ]);
  29726. var listBoxFields = formComponentWithLabelFields.concat([
  29727. requiredArrayOf('items', listBoxItemSchema),
  29728. defaultedBoolean('disabled', false)
  29729. ]);
  29730. var listBoxSchema = objOf(listBoxFields);
  29731. var listBoxDataProcessor = string;
  29732. var selectBoxFields = formComponentWithLabelFields.concat([
  29733. requiredArrayOfObj('items', [
  29734. requiredString('text'),
  29735. requiredString('value')
  29736. ]),
  29737. defaultedNumber('size', 1),
  29738. defaultedBoolean('disabled', false)
  29739. ]);
  29740. var selectBoxSchema = objOf(selectBoxFields);
  29741. var selectBoxDataProcessor = string;
  29742. var sizeInputFields = formComponentWithLabelFields.concat([
  29743. defaultedBoolean('constrain', true),
  29744. defaultedBoolean('disabled', false)
  29745. ]);
  29746. var sizeInputSchema = objOf(sizeInputFields);
  29747. var sizeInputDataProcessor = objOf([
  29748. requiredString('width'),
  29749. requiredString('height')
  29750. ]);
  29751. var tableFields = [
  29752. requiredString('type'),
  29753. requiredArrayOf('header', string),
  29754. requiredArrayOf('cells', arrOf(string))
  29755. ];
  29756. var tableSchema = objOf(tableFields);
  29757. var textAreaFields = formComponentWithLabelFields.concat([
  29758. optionString('placeholder'),
  29759. defaultedBoolean('maximized', false),
  29760. defaultedBoolean('disabled', false)
  29761. ]);
  29762. var textAreaSchema = objOf(textAreaFields);
  29763. var textAreaDataProcessor = string;
  29764. var urlInputFields = formComponentWithLabelFields.concat([
  29765. defaultedStringEnum('filetype', 'file', [
  29766. 'image',
  29767. 'media',
  29768. 'file'
  29769. ]),
  29770. defaulted('disabled', false)
  29771. ]);
  29772. var urlInputSchema = objOf(urlInputFields);
  29773. var urlInputDataProcessor = objOf([
  29774. requiredString('value'),
  29775. defaulted('meta', {})
  29776. ]);
  29777. var createItemsField = function (name) {
  29778. return field$1('items', 'items', required$2(), arrOf(valueOf(function (v) {
  29779. return asRaw('Checking item of ' + name, itemSchema, v).fold(function (sErr) {
  29780. return Result.error(formatError(sErr));
  29781. }, function (passValue) {
  29782. return Result.value(passValue);
  29783. });
  29784. })));
  29785. };
  29786. var itemSchema = valueThunk(function () {
  29787. return choose$2('type', {
  29788. alertbanner: alertBannerSchema,
  29789. bar: objOf(createBarFields(createItemsField('bar'))),
  29790. button: buttonSchema,
  29791. checkbox: checkboxSchema,
  29792. colorinput: colorInputSchema,
  29793. colorpicker: colorPickerSchema,
  29794. dropzone: dropZoneSchema,
  29795. grid: objOf(createGridFields(createItemsField('grid'))),
  29796. iframe: iframeSchema,
  29797. input: inputSchema,
  29798. listbox: listBoxSchema,
  29799. selectbox: selectBoxSchema,
  29800. sizeinput: sizeInputSchema,
  29801. textarea: textAreaSchema,
  29802. urlinput: urlInputSchema,
  29803. customeditor: customEditorSchema,
  29804. htmlpanel: htmlPanelSchema,
  29805. imagetools: imageToolsSchema,
  29806. collection: collectionSchema,
  29807. label: objOf(createLabelFields(createItemsField('label'))),
  29808. table: tableSchema,
  29809. panel: panelSchema
  29810. });
  29811. });
  29812. var panelFields = [
  29813. requiredString('type'),
  29814. defaulted('classes', []),
  29815. requiredArrayOf('items', itemSchema)
  29816. ];
  29817. var panelSchema = objOf(panelFields);
  29818. var tabFields = [
  29819. field$1('name', 'name', defaultedThunk(function () {
  29820. return generate$6('tab-name');
  29821. }), string),
  29822. requiredString('title'),
  29823. requiredArrayOf('items', itemSchema)
  29824. ];
  29825. var tabPanelFields = [
  29826. requiredString('type'),
  29827. requiredArrayOfObj('tabs', tabFields)
  29828. ];
  29829. var tabPanelSchema = objOf(tabPanelFields);
  29830. var dialogButtonFields = dialogFooterButtonFields;
  29831. var dialogButtonSchema = dialogFooterButtonSchema;
  29832. var dialogSchema = objOf([
  29833. requiredString('title'),
  29834. requiredOf('body', choose$2('type', {
  29835. panel: panelSchema,
  29836. tabpanel: tabPanelSchema
  29837. })),
  29838. defaultedString('size', 'normal'),
  29839. requiredArrayOf('buttons', dialogButtonSchema),
  29840. defaulted('initialData', {}),
  29841. defaultedFunction('onAction', noop),
  29842. defaultedFunction('onChange', noop),
  29843. defaultedFunction('onSubmit', noop),
  29844. defaultedFunction('onClose', noop),
  29845. defaultedFunction('onCancel', noop),
  29846. defaulted('onTabChange', noop)
  29847. ]);
  29848. var createDialog = function (spec) {
  29849. return asRaw('dialog', dialogSchema, spec);
  29850. };
  29851. var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum('type', [
  29852. 'cancel',
  29853. 'custom'
  29854. ])], dialogButtonFields, true));
  29855. var urlDialogSchema = objOf([
  29856. requiredString('title'),
  29857. requiredString('url'),
  29858. optionNumber('height'),
  29859. optionNumber('width'),
  29860. optionArrayOf('buttons', urlDialogButtonSchema),
  29861. defaultedFunction('onAction', noop),
  29862. defaultedFunction('onCancel', noop),
  29863. defaultedFunction('onClose', noop),
  29864. defaultedFunction('onMessage', noop)
  29865. ]);
  29866. var createUrlDialog = function (spec) {
  29867. return asRaw('dialog', urlDialogSchema, spec);
  29868. };
  29869. var getAllObjects = function (obj) {
  29870. if (isObject(obj)) {
  29871. return [obj].concat(bind$3(values(obj), getAllObjects));
  29872. } else if (isArray(obj)) {
  29873. return bind$3(obj, getAllObjects);
  29874. } else {
  29875. return [];
  29876. }
  29877. };
  29878. var isNamedItem = function (obj) {
  29879. return isString(obj.type) && isString(obj.name);
  29880. };
  29881. var dataProcessors = {
  29882. checkbox: checkboxDataProcessor,
  29883. colorinput: colorInputDataProcessor,
  29884. colorpicker: colorPickerDataProcessor,
  29885. dropzone: dropZoneDataProcessor,
  29886. input: inputDataProcessor,
  29887. iframe: iframeDataProcessor,
  29888. sizeinput: sizeInputDataProcessor,
  29889. selectbox: selectBoxDataProcessor,
  29890. listbox: listBoxDataProcessor,
  29891. size: sizeInputDataProcessor,
  29892. textarea: textAreaDataProcessor,
  29893. urlinput: urlInputDataProcessor,
  29894. customeditor: customEditorDataProcessor,
  29895. collection: collectionDataProcessor,
  29896. togglemenuitem: dialogToggleMenuItemDataProcessor
  29897. };
  29898. var getDataProcessor = function (item) {
  29899. return Optional.from(dataProcessors[item.type]);
  29900. };
  29901. var getNamedItems = function (structure) {
  29902. return filter$2(getAllObjects(structure), isNamedItem);
  29903. };
  29904. var createDataValidator = function (structure) {
  29905. var namedItems = getNamedItems(structure);
  29906. var fields = bind$3(namedItems, function (item) {
  29907. return getDataProcessor(item).fold(function () {
  29908. return [];
  29909. }, function (schema) {
  29910. return [requiredOf(item.name, schema)];
  29911. });
  29912. });
  29913. return objOf(fields);
  29914. };
  29915. var extract = function (structure) {
  29916. var internalDialog = getOrDie(createDialog(structure));
  29917. var dataValidator = createDataValidator(structure);
  29918. var initialData = structure.initialData;
  29919. return {
  29920. internalDialog: internalDialog,
  29921. dataValidator: dataValidator,
  29922. initialData: initialData
  29923. };
  29924. };
  29925. var DialogManager = {
  29926. open: function (factory, structure) {
  29927. var extraction = extract(structure);
  29928. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  29929. },
  29930. openUrl: function (factory, structure) {
  29931. var internalDialog = getOrDie(createUrlDialog(structure));
  29932. return factory(internalDialog);
  29933. },
  29934. redial: function (structure) {
  29935. return extract(structure);
  29936. }
  29937. };
  29938. var toValidValues = function (values) {
  29939. var errors = [];
  29940. var result = {};
  29941. each(values, function (value, name) {
  29942. value.fold(function () {
  29943. errors.push(name);
  29944. }, function (v) {
  29945. result[name] = v;
  29946. });
  29947. });
  29948. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  29949. };
  29950. var renderBodyPanel = function (spec, backstage) {
  29951. var memForm = record(Form.sketch(function (parts) {
  29952. return {
  29953. dom: {
  29954. tag: 'div',
  29955. classes: ['tox-form'].concat(spec.classes)
  29956. },
  29957. components: map$2(spec.items, function (item) {
  29958. return interpretInForm(parts, item, backstage);
  29959. })
  29960. };
  29961. }));
  29962. return {
  29963. dom: {
  29964. tag: 'div',
  29965. classes: ['tox-dialog__body']
  29966. },
  29967. components: [{
  29968. dom: {
  29969. tag: 'div',
  29970. classes: ['tox-dialog__body-content']
  29971. },
  29972. components: [memForm.asSpec()]
  29973. }],
  29974. behaviours: derive$1([
  29975. Keying.config({
  29976. mode: 'acyclic',
  29977. useTabstopAt: not(isPseudoStop)
  29978. }),
  29979. ComposingConfigs.memento(memForm),
  29980. RepresentingConfigs.memento(memForm, {
  29981. postprocess: function (formValue) {
  29982. return toValidValues(formValue).fold(function (err) {
  29983. console.error(err);
  29984. return {};
  29985. }, identity$1);
  29986. }
  29987. })
  29988. ])
  29989. };
  29990. };
  29991. var factory$3 = function (detail, _spec) {
  29992. return {
  29993. uid: detail.uid,
  29994. dom: detail.dom,
  29995. components: detail.components,
  29996. events: events$a(detail.action),
  29997. behaviours: augment(detail.tabButtonBehaviours, [
  29998. Focusing.config({}),
  29999. Keying.config({
  30000. mode: 'execution',
  30001. useSpace: true,
  30002. useEnter: true
  30003. }),
  30004. Representing.config({
  30005. store: {
  30006. mode: 'memory',
  30007. initialValue: detail.value
  30008. }
  30009. })
  30010. ]),
  30011. domModification: detail.domModification
  30012. };
  30013. };
  30014. var TabButton = single({
  30015. name: 'TabButton',
  30016. configFields: [
  30017. defaulted('uid', undefined),
  30018. required$1('value'),
  30019. field$1('dom', 'dom', mergeWithThunk(function () {
  30020. return {
  30021. attributes: {
  30022. 'role': 'tab',
  30023. 'id': generate$6('aria'),
  30024. 'aria-selected': 'false'
  30025. }
  30026. };
  30027. }), anyValue()),
  30028. option('action'),
  30029. defaulted('domModification', {}),
  30030. field('tabButtonBehaviours', [
  30031. Focusing,
  30032. Keying,
  30033. Representing
  30034. ]),
  30035. required$1('view')
  30036. ],
  30037. factory: factory$3
  30038. });
  30039. var schema$1 = constant$1([
  30040. required$1('tabs'),
  30041. required$1('dom'),
  30042. defaulted('clickToDismiss', false),
  30043. field('tabbarBehaviours', [
  30044. Highlighting,
  30045. Keying
  30046. ]),
  30047. markers$1([
  30048. 'tabClass',
  30049. 'selectedClass'
  30050. ])
  30051. ]);
  30052. var tabsPart = group({
  30053. factory: TabButton,
  30054. name: 'tabs',
  30055. unit: 'tab',
  30056. overrides: function (barDetail) {
  30057. var dismissTab$1 = function (tabbar, button) {
  30058. Highlighting.dehighlight(tabbar, button);
  30059. emitWith(tabbar, dismissTab(), {
  30060. tabbar: tabbar,
  30061. button: button
  30062. });
  30063. };
  30064. var changeTab$1 = function (tabbar, button) {
  30065. Highlighting.highlight(tabbar, button);
  30066. emitWith(tabbar, changeTab(), {
  30067. tabbar: tabbar,
  30068. button: button
  30069. });
  30070. };
  30071. return {
  30072. action: function (button) {
  30073. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  30074. var activeButton = Highlighting.isHighlighted(tabbar, button);
  30075. var response = function () {
  30076. if (activeButton && barDetail.clickToDismiss) {
  30077. return dismissTab$1;
  30078. } else if (!activeButton) {
  30079. return changeTab$1;
  30080. } else {
  30081. return noop;
  30082. }
  30083. }();
  30084. response(tabbar, button);
  30085. },
  30086. domModification: { classes: [barDetail.markers.tabClass] }
  30087. };
  30088. }
  30089. });
  30090. var parts$1 = constant$1([tabsPart]);
  30091. var factory$2 = function (detail, components, _spec, _externals) {
  30092. return {
  30093. 'uid': detail.uid,
  30094. 'dom': detail.dom,
  30095. components: components,
  30096. 'debug.sketcher': 'Tabbar',
  30097. 'domModification': { attributes: { role: 'tablist' } },
  30098. 'behaviours': augment(detail.tabbarBehaviours, [
  30099. Highlighting.config({
  30100. highlightClass: detail.markers.selectedClass,
  30101. itemClass: detail.markers.tabClass,
  30102. onHighlight: function (tabbar, tab) {
  30103. set$8(tab.element, 'aria-selected', 'true');
  30104. },
  30105. onDehighlight: function (tabbar, tab) {
  30106. set$8(tab.element, 'aria-selected', 'false');
  30107. }
  30108. }),
  30109. Keying.config({
  30110. mode: 'flow',
  30111. getInitial: function (tabbar) {
  30112. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  30113. return tab.element;
  30114. });
  30115. },
  30116. selector: '.' + detail.markers.tabClass,
  30117. executeOnMove: true
  30118. })
  30119. ])
  30120. };
  30121. };
  30122. var Tabbar = composite({
  30123. name: 'Tabbar',
  30124. configFields: schema$1(),
  30125. partFields: parts$1(),
  30126. factory: factory$2
  30127. });
  30128. var factory$1 = function (detail, _spec) {
  30129. return {
  30130. uid: detail.uid,
  30131. dom: detail.dom,
  30132. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  30133. domModification: { attributes: { role: 'tabpanel' } }
  30134. };
  30135. };
  30136. var Tabview = single({
  30137. name: 'Tabview',
  30138. configFields: [field('tabviewBehaviours', [Replacing])],
  30139. factory: factory$1
  30140. });
  30141. var schema = constant$1([
  30142. defaulted('selectFirst', true),
  30143. onHandler('onChangeTab'),
  30144. onHandler('onDismissTab'),
  30145. defaulted('tabs', []),
  30146. field('tabSectionBehaviours', [])
  30147. ]);
  30148. var barPart = required({
  30149. factory: Tabbar,
  30150. schema: [
  30151. required$1('dom'),
  30152. requiredObjOf('markers', [
  30153. required$1('tabClass'),
  30154. required$1('selectedClass')
  30155. ])
  30156. ],
  30157. name: 'tabbar',
  30158. defaults: function (detail) {
  30159. return { tabs: detail.tabs };
  30160. }
  30161. });
  30162. var viewPart = required({
  30163. factory: Tabview,
  30164. name: 'tabview'
  30165. });
  30166. var parts = constant$1([
  30167. barPart,
  30168. viewPart
  30169. ]);
  30170. var factory = function (detail, components, _spec, _externals) {
  30171. var changeTab$1 = function (button) {
  30172. var tabValue = Representing.getValue(button);
  30173. getPart(button, detail, 'tabview').each(function (tabview) {
  30174. var tabWithValue = find$5(detail.tabs, function (t) {
  30175. return t.value === tabValue;
  30176. });
  30177. tabWithValue.each(function (tabData) {
  30178. var panel = tabData.view();
  30179. getOpt(button.element, 'id').each(function (id) {
  30180. set$8(tabview.element, 'aria-labelledby', id);
  30181. });
  30182. Replacing.set(tabview, panel);
  30183. detail.onChangeTab(tabview, button, panel);
  30184. });
  30185. });
  30186. };
  30187. var changeTabBy = function (section, byPred) {
  30188. getPart(section, detail, 'tabbar').each(function (tabbar) {
  30189. byPred(tabbar).each(emitExecute);
  30190. });
  30191. };
  30192. return {
  30193. uid: detail.uid,
  30194. dom: detail.dom,
  30195. components: components,
  30196. behaviours: get$2(detail.tabSectionBehaviours),
  30197. events: derive$2(flatten([
  30198. detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
  30199. changeTabBy(section, Highlighting.getFirst);
  30200. })] : [],
  30201. [
  30202. run$1(changeTab(), function (section, simulatedEvent) {
  30203. var button = simulatedEvent.event.button;
  30204. changeTab$1(button);
  30205. }),
  30206. run$1(dismissTab(), function (section, simulatedEvent) {
  30207. var button = simulatedEvent.event.button;
  30208. detail.onDismissTab(section, button);
  30209. })
  30210. ]
  30211. ])),
  30212. apis: {
  30213. getViewItems: function (section) {
  30214. return getPart(section, detail, 'tabview').map(function (tabview) {
  30215. return Replacing.contents(tabview);
  30216. }).getOr([]);
  30217. },
  30218. showTab: function (section, tabKey) {
  30219. var getTabIfNotActive = function (tabbar) {
  30220. var candidates = Highlighting.getCandidates(tabbar);
  30221. var optTab = find$5(candidates, function (c) {
  30222. return Representing.getValue(c) === tabKey;
  30223. });
  30224. return optTab.filter(function (tab) {
  30225. return !Highlighting.isHighlighted(tabbar, tab);
  30226. });
  30227. };
  30228. changeTabBy(section, getTabIfNotActive);
  30229. }
  30230. }
  30231. };
  30232. };
  30233. var TabSection = composite({
  30234. name: 'TabSection',
  30235. configFields: schema(),
  30236. partFields: parts(),
  30237. factory: factory,
  30238. apis: {
  30239. getViewItems: function (apis, component) {
  30240. return apis.getViewItems(component);
  30241. },
  30242. showTab: function (apis, component, tabKey) {
  30243. apis.showTab(component, tabKey);
  30244. }
  30245. }
  30246. });
  30247. var measureHeights = function (allTabs, tabview, tabviewComp) {
  30248. return map$2(allTabs, function (_tab, i) {
  30249. Replacing.set(tabviewComp, allTabs[i].view());
  30250. var rect = tabview.dom.getBoundingClientRect();
  30251. Replacing.set(tabviewComp, []);
  30252. return rect.height;
  30253. });
  30254. };
  30255. var getMaxHeight = function (heights) {
  30256. return head(sort(heights, function (a, b) {
  30257. if (a > b) {
  30258. return -1;
  30259. } else if (a < b) {
  30260. return +1;
  30261. } else {
  30262. return 0;
  30263. }
  30264. }));
  30265. };
  30266. var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  30267. var documentElement$1 = documentElement(dialog).dom;
  30268. var rootElm = ancestor(dialog, '.tox-dialog-wrap').getOr(dialog);
  30269. var isFixed = get$c(rootElm, 'position') === 'fixed';
  30270. var maxHeight;
  30271. if (isFixed) {
  30272. maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight);
  30273. } else {
  30274. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  30275. }
  30276. var tabviewHeight = get$b(tabview);
  30277. var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$a(tablist);
  30278. var currentTabHeight = isTabListBeside ? Math.max(get$b(tablist), tabviewHeight) : tabviewHeight;
  30279. var dialogTopMargin = parseInt(get$c(dialog, 'margin-top'), 10) || 0;
  30280. var dialogBottomMargin = parseInt(get$c(dialog, 'margin-bottom'), 10) || 0;
  30281. var dialogHeight = get$b(dialog) + dialogTopMargin + dialogBottomMargin;
  30282. var chromeHeight = dialogHeight - currentTabHeight;
  30283. return maxHeight - chromeHeight;
  30284. };
  30285. var showTab = function (allTabs, comp) {
  30286. head(allTabs).each(function (tab) {
  30287. return TabSection.showTab(comp, tab.value);
  30288. });
  30289. };
  30290. var setTabviewHeight = function (tabview, height) {
  30291. set$7(tabview, 'height', height + 'px');
  30292. if (!detect$1().browser.isIE()) {
  30293. set$7(tabview, 'flex-basis', height + 'px');
  30294. } else {
  30295. remove$6(tabview, 'flex-basis');
  30296. }
  30297. };
  30298. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  30299. ancestor(dialogBody, '[role="dialog"]').each(function (dialog) {
  30300. descendant(dialog, '[role="tablist"]').each(function (tablist) {
  30301. maxTabHeight.get().map(function (height) {
  30302. set$7(tabview, 'height', '0');
  30303. set$7(tabview, 'flex-basis', '0');
  30304. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  30305. }).each(function (height) {
  30306. setTabviewHeight(tabview, height);
  30307. });
  30308. });
  30309. });
  30310. };
  30311. var getTabview = function (dialog) {
  30312. return descendant(dialog, '[role="tabpanel"]');
  30313. };
  30314. var setMode = function (allTabs) {
  30315. var smartTabHeight = function () {
  30316. var maxTabHeight = value$1();
  30317. var extraEvents = [
  30318. runOnAttached(function (comp) {
  30319. var dialog = comp.element;
  30320. getTabview(dialog).each(function (tabview) {
  30321. set$7(tabview, 'visibility', 'hidden');
  30322. comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) {
  30323. var heights = measureHeights(allTabs, tabview, tabviewComp);
  30324. var maxTabHeightOpt = getMaxHeight(heights);
  30325. maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set);
  30326. });
  30327. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30328. remove$6(tabview, 'visibility');
  30329. showTab(allTabs, comp);
  30330. global$f.requestAnimationFrame(function () {
  30331. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30332. });
  30333. });
  30334. }),
  30335. run$1(windowResize(), function (comp) {
  30336. var dialog = comp.element;
  30337. getTabview(dialog).each(function (tabview) {
  30338. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30339. });
  30340. }),
  30341. run$1(formResizeEvent, function (comp, _se) {
  30342. var dialog = comp.element;
  30343. getTabview(dialog).each(function (tabview) {
  30344. var oldFocus = active(getRootNode(tabview));
  30345. set$7(tabview, 'visibility', 'hidden');
  30346. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  30347. return parseInt(h, 10);
  30348. });
  30349. remove$6(tabview, 'height');
  30350. remove$6(tabview, 'flex-basis');
  30351. var newHeight = tabview.dom.getBoundingClientRect().height;
  30352. var hasGrown = oldHeight.forall(function (h) {
  30353. return newHeight > h;
  30354. });
  30355. if (hasGrown) {
  30356. maxTabHeight.set(newHeight);
  30357. updateTabviewHeight(dialog, tabview, maxTabHeight);
  30358. } else {
  30359. oldHeight.each(function (h) {
  30360. setTabviewHeight(tabview, h);
  30361. });
  30362. }
  30363. remove$6(tabview, 'visibility');
  30364. oldFocus.each(focus$3);
  30365. });
  30366. })
  30367. ];
  30368. var selectFirst = false;
  30369. return {
  30370. extraEvents: extraEvents,
  30371. selectFirst: selectFirst
  30372. };
  30373. }();
  30374. var naiveTabHeight = function () {
  30375. var extraEvents = [];
  30376. var selectFirst = true;
  30377. return {
  30378. extraEvents: extraEvents,
  30379. selectFirst: selectFirst
  30380. };
  30381. }();
  30382. return {
  30383. smartTabHeight: smartTabHeight,
  30384. naiveTabHeight: naiveTabHeight
  30385. };
  30386. };
  30387. var SendDataToSectionChannel = 'send-data-to-section';
  30388. var SendDataToViewChannel = 'send-data-to-view';
  30389. var renderTabPanel = function (spec, backstage) {
  30390. var storedValue = Cell({});
  30391. var updateDataWithForm = function (form) {
  30392. var formData = Representing.getValue(form);
  30393. var validData = toValidValues(formData).getOr({});
  30394. var currentData = storedValue.get();
  30395. var newData = deepMerge(currentData, validData);
  30396. storedValue.set(newData);
  30397. };
  30398. var setDataOnForm = function (form) {
  30399. var tabData = storedValue.get();
  30400. Representing.setValue(form, tabData);
  30401. };
  30402. var oldTab = Cell(null);
  30403. var allTabs = map$2(spec.tabs, function (tab) {
  30404. return {
  30405. value: tab.name,
  30406. dom: {
  30407. tag: 'div',
  30408. classes: ['tox-dialog__body-nav-item'],
  30409. innerHtml: backstage.shared.providers.translate(tab.title)
  30410. },
  30411. view: function () {
  30412. return [Form.sketch(function (parts) {
  30413. return {
  30414. dom: {
  30415. tag: 'div',
  30416. classes: ['tox-form']
  30417. },
  30418. components: map$2(tab.items, function (item) {
  30419. return interpretInForm(parts, item, backstage);
  30420. }),
  30421. formBehaviours: derive$1([
  30422. Keying.config({
  30423. mode: 'acyclic',
  30424. useTabstopAt: not(isPseudoStop)
  30425. }),
  30426. config('TabView.form.events', [
  30427. runOnAttached(setDataOnForm),
  30428. runOnDetached(updateDataWithForm)
  30429. ]),
  30430. Receiving.config({
  30431. channels: wrapAll([
  30432. {
  30433. key: SendDataToSectionChannel,
  30434. value: { onReceive: updateDataWithForm }
  30435. },
  30436. {
  30437. key: SendDataToViewChannel,
  30438. value: { onReceive: setDataOnForm }
  30439. }
  30440. ])
  30441. })
  30442. ])
  30443. };
  30444. })];
  30445. }
  30446. };
  30447. });
  30448. var tabMode = setMode(allTabs).smartTabHeight;
  30449. return TabSection.sketch({
  30450. dom: {
  30451. tag: 'div',
  30452. classes: ['tox-dialog__body']
  30453. },
  30454. onChangeTab: function (section, button, _viewItems) {
  30455. var name = Representing.getValue(button);
  30456. emitWith(section, formTabChangeEvent, {
  30457. name: name,
  30458. oldName: oldTab.get()
  30459. });
  30460. oldTab.set(name);
  30461. },
  30462. tabs: allTabs,
  30463. components: [
  30464. TabSection.parts.tabbar({
  30465. dom: {
  30466. tag: 'div',
  30467. classes: ['tox-dialog__body-nav']
  30468. },
  30469. components: [Tabbar.parts.tabs({})],
  30470. markers: {
  30471. tabClass: 'tox-tab',
  30472. selectedClass: 'tox-dialog__body-nav-item--active'
  30473. },
  30474. tabbarBehaviours: derive$1([Tabstopping.config({})])
  30475. }),
  30476. TabSection.parts.tabview({
  30477. dom: {
  30478. tag: 'div',
  30479. classes: ['tox-dialog__body-content']
  30480. }
  30481. })
  30482. ],
  30483. selectFirst: tabMode.selectFirst,
  30484. tabSectionBehaviours: derive$1([
  30485. config('tabpanel', tabMode.extraEvents),
  30486. Keying.config({ mode: 'acyclic' }),
  30487. Composing.config({
  30488. find: function (comp) {
  30489. return head(TabSection.getViewItems(comp));
  30490. }
  30491. }),
  30492. Representing.config({
  30493. store: {
  30494. mode: 'manual',
  30495. getValue: function (tsection) {
  30496. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  30497. return storedValue.get();
  30498. },
  30499. setValue: function (tsection, value) {
  30500. storedValue.set(value);
  30501. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  30502. }
  30503. }
  30504. })
  30505. ])
  30506. });
  30507. };
  30508. var dialogChannel = generate$6('update-dialog');
  30509. var titleChannel = generate$6('update-title');
  30510. var bodyChannel = generate$6('update-body');
  30511. var footerChannel = generate$6('update-footer');
  30512. var bodySendMessageChannel = generate$6('body-send-message');
  30513. var renderBody = function (spec, id, backstage, ariaAttrs) {
  30514. var renderComponents = function (incoming) {
  30515. switch (incoming.body.type) {
  30516. case 'tabpanel': {
  30517. return [renderTabPanel(incoming.body, backstage)];
  30518. }
  30519. default: {
  30520. return [renderBodyPanel(incoming.body, backstage)];
  30521. }
  30522. }
  30523. };
  30524. var updateState = function (_comp, incoming) {
  30525. return Optional.some({
  30526. isTabPanel: function () {
  30527. return incoming.body.type === 'tabpanel';
  30528. }
  30529. });
  30530. };
  30531. var ariaAttributes = { 'aria-live': 'polite' };
  30532. return {
  30533. dom: {
  30534. tag: 'div',
  30535. classes: ['tox-dialog__content-js'],
  30536. attributes: __assign(__assign({}, id.map(function (x) {
  30537. return { id: x };
  30538. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  30539. },
  30540. components: [],
  30541. behaviours: derive$1([
  30542. ComposingConfigs.childAt(0),
  30543. Reflecting.config({
  30544. channel: bodyChannel,
  30545. updateState: updateState,
  30546. renderComponents: renderComponents,
  30547. initialData: spec
  30548. })
  30549. ])
  30550. };
  30551. };
  30552. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  30553. return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs);
  30554. };
  30555. var renderModalBody = function (spec, backstage) {
  30556. var bodySpec = renderBody(spec, Optional.none(), backstage, false);
  30557. return ModalDialog.parts.body(bodySpec);
  30558. };
  30559. var renderIframeBody = function (spec) {
  30560. var bodySpec = {
  30561. dom: {
  30562. tag: 'div',
  30563. classes: ['tox-dialog__content-js']
  30564. },
  30565. components: [{
  30566. dom: {
  30567. tag: 'div',
  30568. classes: ['tox-dialog__body-iframe']
  30569. },
  30570. components: [craft({
  30571. dom: {
  30572. tag: 'iframe',
  30573. attributes: { src: spec.url }
  30574. },
  30575. behaviours: derive$1([
  30576. Tabstopping.config({}),
  30577. Focusing.config({})
  30578. ])
  30579. })]
  30580. }],
  30581. behaviours: derive$1([Keying.config({
  30582. mode: 'acyclic',
  30583. useTabstopAt: not(isPseudoStop)
  30584. })])
  30585. };
  30586. return ModalDialog.parts.body(bodySpec);
  30587. };
  30588. var isTouch = global$9.deviceType.isTouch();
  30589. var hiddenHeader = function (title, close) {
  30590. return {
  30591. dom: {
  30592. tag: 'div',
  30593. styles: { display: 'none' },
  30594. classes: ['tox-dialog__header']
  30595. },
  30596. components: [
  30597. title,
  30598. close
  30599. ]
  30600. };
  30601. };
  30602. var pClose = function (onClose, providersBackstage) {
  30603. return ModalDialog.parts.close(Button.sketch({
  30604. dom: {
  30605. tag: 'button',
  30606. classes: [
  30607. 'tox-button',
  30608. 'tox-button--icon',
  30609. 'tox-button--naked'
  30610. ],
  30611. attributes: {
  30612. 'type': 'button',
  30613. 'aria-label': providersBackstage.translate('Close')
  30614. }
  30615. },
  30616. action: onClose,
  30617. buttonBehaviours: derive$1([Tabstopping.config({})])
  30618. }));
  30619. };
  30620. var pUntitled = function () {
  30621. return ModalDialog.parts.title({
  30622. dom: {
  30623. tag: 'div',
  30624. classes: ['tox-dialog__title'],
  30625. innerHtml: '',
  30626. styles: { display: 'none' }
  30627. }
  30628. });
  30629. };
  30630. var pBodyMessage = function (message, providersBackstage) {
  30631. return ModalDialog.parts.body({
  30632. dom: {
  30633. tag: 'div',
  30634. classes: ['tox-dialog__body']
  30635. },
  30636. components: [{
  30637. dom: {
  30638. tag: 'div',
  30639. classes: ['tox-dialog__body-content']
  30640. },
  30641. components: [{ dom: fromHtml('<p>' + providersBackstage.translate(message) + '</p>') }]
  30642. }]
  30643. });
  30644. };
  30645. var pFooter = function (buttons) {
  30646. return ModalDialog.parts.footer({
  30647. dom: {
  30648. tag: 'div',
  30649. classes: ['tox-dialog__footer']
  30650. },
  30651. components: buttons
  30652. });
  30653. };
  30654. var pFooterGroup = function (startButtons, endButtons) {
  30655. return [
  30656. Container.sketch({
  30657. dom: {
  30658. tag: 'div',
  30659. classes: ['tox-dialog__footer-start']
  30660. },
  30661. components: startButtons
  30662. }),
  30663. Container.sketch({
  30664. dom: {
  30665. tag: 'div',
  30666. classes: ['tox-dialog__footer-end']
  30667. },
  30668. components: endButtons
  30669. })
  30670. ];
  30671. };
  30672. var renderDialog$1 = function (spec) {
  30673. var _a;
  30674. var dialogClass = 'tox-dialog';
  30675. var blockerClass = dialogClass + '-wrap';
  30676. var blockerBackdropClass = blockerClass + '__backdrop';
  30677. var scrollLockClass = dialogClass + '__disable-scroll';
  30678. return ModalDialog.sketch({
  30679. lazySink: spec.lazySink,
  30680. onEscape: function (comp) {
  30681. spec.onEscape(comp);
  30682. return Optional.some(true);
  30683. },
  30684. useTabstopAt: function (elem) {
  30685. return !isPseudoStop(elem);
  30686. },
  30687. dom: {
  30688. tag: 'div',
  30689. classes: [dialogClass].concat(spec.extraClasses),
  30690. styles: __assign({ position: 'relative' }, spec.extraStyles)
  30691. },
  30692. components: __spreadArray([
  30693. spec.header,
  30694. spec.body
  30695. ], spec.footer.toArray(), true),
  30696. parts: {
  30697. blocker: {
  30698. dom: fromHtml('<div class="' + blockerClass + '"></div>'),
  30699. components: [{
  30700. dom: {
  30701. tag: 'div',
  30702. classes: isTouch ? [
  30703. blockerBackdropClass,
  30704. blockerBackdropClass + '--opaque'
  30705. ] : [blockerBackdropClass]
  30706. }
  30707. }]
  30708. }
  30709. },
  30710. dragBlockClass: blockerClass,
  30711. modalBehaviours: derive$1(__spreadArray([
  30712. Focusing.config({}),
  30713. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  30714. Keying.focusIn(comp);
  30715. })])),
  30716. config('scroll-lock', [
  30717. runOnAttached(function () {
  30718. add$2(body(), scrollLockClass);
  30719. }),
  30720. runOnDetached(function () {
  30721. remove$2(body(), scrollLockClass);
  30722. })
  30723. ])
  30724. ], spec.extraBehaviours, true)),
  30725. eventOrder: __assign((_a = {}, _a[execute$5()] = ['dialog-events'], _a[attachedToDom()] = [
  30726. 'scroll-lock',
  30727. 'dialog-events',
  30728. 'alloy.base.behaviour'
  30729. ], _a[detachedFromDom()] = [
  30730. 'alloy.base.behaviour',
  30731. 'dialog-events',
  30732. 'scroll-lock'
  30733. ], _a), spec.eventOrder)
  30734. });
  30735. };
  30736. var renderClose = function (providersBackstage) {
  30737. return Button.sketch({
  30738. dom: {
  30739. tag: 'button',
  30740. classes: [
  30741. 'tox-button',
  30742. 'tox-button--icon',
  30743. 'tox-button--naked'
  30744. ],
  30745. attributes: {
  30746. 'type': 'button',
  30747. 'aria-label': providersBackstage.translate('Close'),
  30748. 'title': providersBackstage.translate('Close')
  30749. }
  30750. },
  30751. components: [render$3('close', {
  30752. tag: 'div',
  30753. classes: ['tox-icon']
  30754. }, providersBackstage.icons)],
  30755. action: function (comp) {
  30756. emit(comp, formCancelEvent);
  30757. }
  30758. });
  30759. };
  30760. var renderTitle = function (spec, id, providersBackstage) {
  30761. var renderComponents = function (data) {
  30762. return [text(providersBackstage.translate(data.title))];
  30763. };
  30764. return {
  30765. dom: {
  30766. tag: 'div',
  30767. classes: ['tox-dialog__title'],
  30768. attributes: __assign({}, id.map(function (x) {
  30769. return { id: x };
  30770. }).getOr({}))
  30771. },
  30772. components: renderComponents(spec),
  30773. behaviours: derive$1([Reflecting.config({
  30774. channel: titleChannel,
  30775. renderComponents: renderComponents
  30776. })])
  30777. };
  30778. };
  30779. var renderDragHandle = function () {
  30780. return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') };
  30781. };
  30782. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  30783. return Container.sketch({
  30784. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  30785. components: [
  30786. renderTitle(spec, Optional.some(titleId), providersBackstage),
  30787. renderDragHandle(),
  30788. renderClose(providersBackstage)
  30789. ],
  30790. containerBehaviours: derive$1([Dragging.config({
  30791. mode: 'mouse',
  30792. blockerClass: 'blocker',
  30793. getTarget: function (handle) {
  30794. return closest$1(handle, '[role="dialog"]').getOrDie();
  30795. },
  30796. snaps: {
  30797. getSnapPoints: function () {
  30798. return [];
  30799. },
  30800. leftAttr: 'data-drag-left',
  30801. topAttr: 'data-drag-top'
  30802. }
  30803. })])
  30804. });
  30805. };
  30806. var renderModalHeader = function (spec, providersBackstage) {
  30807. var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage));
  30808. var pHandle = ModalDialog.parts.draghandle(renderDragHandle());
  30809. var pClose = ModalDialog.parts.close(renderClose(providersBackstage));
  30810. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  30811. return Container.sketch({
  30812. dom: fromHtml('<div class="tox-dialog__header"></div>'),
  30813. components: components
  30814. });
  30815. };
  30816. var getHeader = function (title, backstage) {
  30817. return renderModalHeader({
  30818. title: backstage.shared.providers.translate(title),
  30819. draggable: backstage.dialog.isDraggableModal()
  30820. }, backstage.shared.providers);
  30821. };
  30822. var getBusySpec = function (message, bs, providers) {
  30823. return {
  30824. dom: {
  30825. tag: 'div',
  30826. classes: ['tox-dialog__busy-spinner'],
  30827. attributes: { 'aria-label': providers.translate(message) },
  30828. styles: {
  30829. left: '0px',
  30830. right: '0px',
  30831. bottom: '0px',
  30832. top: '0px',
  30833. position: 'absolute'
  30834. }
  30835. },
  30836. behaviours: bs,
  30837. components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  30838. };
  30839. };
  30840. var getEventExtras = function (lazyDialog, providers, extra) {
  30841. return {
  30842. onClose: function () {
  30843. return extra.closeWindow();
  30844. },
  30845. onBlock: function (blockEvent) {
  30846. ModalDialog.setBusy(lazyDialog(), function (_comp, bs) {
  30847. return getBusySpec(blockEvent.message, bs, providers);
  30848. });
  30849. },
  30850. onUnblock: function () {
  30851. ModalDialog.setIdle(lazyDialog());
  30852. }
  30853. };
  30854. };
  30855. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  30856. var _a;
  30857. var updateState = function (_comp, incoming) {
  30858. return Optional.some(incoming);
  30859. };
  30860. return build$1(renderDialog$1(__assign(__assign({}, spec), {
  30861. lazySink: backstage.shared.getSink,
  30862. extraBehaviours: __spreadArray([
  30863. Reflecting.config({
  30864. channel: dialogChannel,
  30865. updateState: updateState,
  30866. initialData: initialData
  30867. }),
  30868. RepresentingConfigs.memory({})
  30869. ], spec.extraBehaviours, true),
  30870. onEscape: function (comp) {
  30871. emit(comp, formCancelEvent);
  30872. },
  30873. dialogEvents: dialogEvents,
  30874. eventOrder: (_a = {}, _a[receive()] = [
  30875. Reflecting.name(),
  30876. Receiving.name()
  30877. ], _a[attachedToDom()] = [
  30878. 'scroll-lock',
  30879. Reflecting.name(),
  30880. 'messages',
  30881. 'dialog-events',
  30882. 'alloy.base.behaviour'
  30883. ], _a[detachedFromDom()] = [
  30884. 'alloy.base.behaviour',
  30885. 'dialog-events',
  30886. 'messages',
  30887. Reflecting.name(),
  30888. 'scroll-lock'
  30889. ], _a)
  30890. })));
  30891. };
  30892. var mapMenuButtons = function (buttons) {
  30893. var mapItems = function (button) {
  30894. var items = map$2(button.items, function (item) {
  30895. var cell = Cell(false);
  30896. return __assign(__assign({}, item), { storage: cell });
  30897. });
  30898. return __assign(__assign({}, button), { items: items });
  30899. };
  30900. return map$2(buttons, function (button) {
  30901. if (button.type === 'menu') {
  30902. return mapItems(button);
  30903. }
  30904. return button;
  30905. });
  30906. };
  30907. var extractCellsToObject = function (buttons) {
  30908. return foldl(buttons, function (acc, button) {
  30909. if (button.type === 'menu') {
  30910. var menuButton = button;
  30911. return foldl(menuButton.items, function (innerAcc, item) {
  30912. innerAcc[item.name] = item.storage;
  30913. return innerAcc;
  30914. }, acc);
  30915. }
  30916. return acc;
  30917. }, {});
  30918. };
  30919. var initCommonEvents = function (fireApiEvent, extras) {
  30920. return [
  30921. runWithTarget(focusin(), onFocus),
  30922. fireApiEvent(formCloseEvent, function (_api, spec) {
  30923. extras.onClose();
  30924. spec.onClose();
  30925. }),
  30926. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  30927. spec.onCancel(api);
  30928. emit(self, formCloseEvent);
  30929. }),
  30930. run$1(formUnblockEvent, function (_c, _se) {
  30931. return extras.onUnblock();
  30932. }),
  30933. run$1(formBlockEvent, function (_c, se) {
  30934. return extras.onBlock(se.event);
  30935. })
  30936. ];
  30937. };
  30938. var initUrlDialog = function (getInstanceApi, extras) {
  30939. var fireApiEvent = function (eventName, f) {
  30940. return run$1(eventName, function (c, se) {
  30941. withSpec(c, function (spec, _c) {
  30942. f(getInstanceApi(), spec, se.event, c);
  30943. });
  30944. });
  30945. };
  30946. var withSpec = function (c, f) {
  30947. Reflecting.getState(c).get().each(function (currentDialog) {
  30948. f(currentDialog, c);
  30949. });
  30950. };
  30951. return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [fireApiEvent(formActionEvent, function (api, spec, event) {
  30952. spec.onAction(api, { name: event.name });
  30953. })], false);
  30954. };
  30955. var initDialog = function (getInstanceApi, extras, getSink) {
  30956. var fireApiEvent = function (eventName, f) {
  30957. return run$1(eventName, function (c, se) {
  30958. withSpec(c, function (spec, _c) {
  30959. f(getInstanceApi(), spec, se.event, c);
  30960. });
  30961. });
  30962. };
  30963. var withSpec = function (c, f) {
  30964. Reflecting.getState(c).get().each(function (currentDialogInit) {
  30965. f(currentDialogInit.internalDialog, c);
  30966. });
  30967. };
  30968. return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [
  30969. fireApiEvent(formSubmitEvent, function (api, spec) {
  30970. return spec.onSubmit(api);
  30971. }),
  30972. fireApiEvent(formChangeEvent, function (api, spec, event) {
  30973. spec.onChange(api, { name: event.name });
  30974. }),
  30975. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  30976. var focusIn = function () {
  30977. return Keying.focusIn(component);
  30978. };
  30979. var isDisabled = function (focused) {
  30980. return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
  30981. return val === 'true';
  30982. });
  30983. };
  30984. var rootNode = getRootNode(component.element);
  30985. var current = active(rootNode);
  30986. spec.onAction(api, {
  30987. name: event.name,
  30988. value: event.value
  30989. });
  30990. active(rootNode).fold(focusIn, function (focused) {
  30991. if (isDisabled(focused)) {
  30992. focusIn();
  30993. } else if (current.exists(function (cur) {
  30994. return contains(focused, cur) && isDisabled(cur);
  30995. })) {
  30996. focusIn();
  30997. } else {
  30998. getSink().toOptional().filter(function (sink) {
  30999. return !contains(sink.element, focused);
  31000. }).each(focusIn);
  31001. }
  31002. });
  31003. }),
  31004. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  31005. spec.onTabChange(api, {
  31006. newTabName: event.name,
  31007. oldTabName: event.oldName
  31008. });
  31009. }),
  31010. runOnDetached(function (component) {
  31011. var api = getInstanceApi();
  31012. Representing.setValue(component, api.getData());
  31013. })
  31014. ], false);
  31015. };
  31016. var SilverDialogEvents = {
  31017. initUrlDialog: initUrlDialog,
  31018. initDialog: initDialog
  31019. };
  31020. var makeButton = function (button, backstage) {
  31021. return renderFooterButton(button, button.type, backstage);
  31022. };
  31023. var lookup = function (compInSystem, footerButtons, buttonName) {
  31024. return find$5(footerButtons, function (button) {
  31025. return button.name === buttonName;
  31026. }).bind(function (memButton) {
  31027. return memButton.memento.getOpt(compInSystem);
  31028. });
  31029. };
  31030. var renderComponents = function (_data, state) {
  31031. var footerButtons = state.map(function (s) {
  31032. return s.footerButtons;
  31033. }).getOr([]);
  31034. var buttonGroups = partition$3(footerButtons, function (button) {
  31035. return button.align === 'start';
  31036. });
  31037. var makeGroup = function (edge, buttons) {
  31038. return Container.sketch({
  31039. dom: {
  31040. tag: 'div',
  31041. classes: ['tox-dialog__footer-' + edge]
  31042. },
  31043. components: map$2(buttons, function (button) {
  31044. return button.memento.asSpec();
  31045. })
  31046. });
  31047. };
  31048. var startButtons = makeGroup('start', buttonGroups.pass);
  31049. var endButtons = makeGroup('end', buttonGroups.fail);
  31050. return [
  31051. startButtons,
  31052. endButtons
  31053. ];
  31054. };
  31055. var renderFooter = function (initSpec, backstage) {
  31056. var updateState = function (_comp, data) {
  31057. var footerButtons = map$2(data.buttons, function (button) {
  31058. var memButton = record(makeButton(button, backstage));
  31059. return {
  31060. name: button.name,
  31061. align: button.align,
  31062. memento: memButton
  31063. };
  31064. });
  31065. var lookupByName = function (compInSystem, buttonName) {
  31066. return lookup(compInSystem, footerButtons, buttonName);
  31067. };
  31068. return Optional.some({
  31069. lookupByName: lookupByName,
  31070. footerButtons: footerButtons
  31071. });
  31072. };
  31073. return {
  31074. dom: fromHtml('<div class="tox-dialog__footer"></div>'),
  31075. components: [],
  31076. behaviours: derive$1([Reflecting.config({
  31077. channel: footerChannel,
  31078. initialData: initSpec,
  31079. updateState: updateState,
  31080. renderComponents: renderComponents
  31081. })])
  31082. };
  31083. };
  31084. var renderInlineFooter = function (initSpec, backstage) {
  31085. return renderFooter(initSpec, backstage);
  31086. };
  31087. var renderModalFooter = function (initSpec, backstage) {
  31088. return ModalDialog.parts.footer(renderFooter(initSpec, backstage));
  31089. };
  31090. var getCompByName = function (access, name) {
  31091. var root = access.getRoot();
  31092. if (root.getSystem().isConnected()) {
  31093. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  31094. return Form.getField(form_1, name).fold(function () {
  31095. var footer = access.getFooter();
  31096. var footerState = Reflecting.getState(footer);
  31097. return footerState.get().bind(function (f) {
  31098. return f.lookupByName(form_1, name);
  31099. });
  31100. }, function (comp) {
  31101. return Optional.some(comp);
  31102. });
  31103. } else {
  31104. return Optional.none();
  31105. }
  31106. };
  31107. var validateData$1 = function (access, data) {
  31108. var root = access.getRoot();
  31109. return Reflecting.getState(root).get().map(function (dialogState) {
  31110. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  31111. }).getOr(data);
  31112. };
  31113. var getDialogApi = function (access, doRedial, menuItemStates) {
  31114. var withRoot = function (f) {
  31115. var root = access.getRoot();
  31116. if (root.getSystem().isConnected()) {
  31117. f(root);
  31118. }
  31119. };
  31120. var getData = function () {
  31121. var root = access.getRoot();
  31122. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  31123. var representedValues = Representing.getValue(valueComp);
  31124. var menuItemCurrentState = map$1(menuItemStates, function (cell) {
  31125. return cell.get();
  31126. });
  31127. return __assign(__assign({}, representedValues), menuItemCurrentState);
  31128. };
  31129. var setData = function (newData) {
  31130. withRoot(function (_) {
  31131. var prevData = instanceApi.getData();
  31132. var mergedData = __assign(__assign({}, prevData), newData);
  31133. var newInternalData = validateData$1(access, mergedData);
  31134. var form = access.getFormWrapper();
  31135. Representing.setValue(form, newInternalData);
  31136. each(menuItemStates, function (v, k) {
  31137. if (has$2(mergedData, k)) {
  31138. v.set(mergedData[k]);
  31139. }
  31140. });
  31141. });
  31142. };
  31143. var disable = function (name) {
  31144. getCompByName(access, name).each(Disabling.disable);
  31145. };
  31146. var enable = function (name) {
  31147. getCompByName(access, name).each(Disabling.enable);
  31148. };
  31149. var focus = function (name) {
  31150. getCompByName(access, name).each(Focusing.focus);
  31151. };
  31152. var block = function (message) {
  31153. if (!isString(message)) {
  31154. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  31155. }
  31156. withRoot(function (root) {
  31157. emitWith(root, formBlockEvent, { message: message });
  31158. });
  31159. };
  31160. var unblock = function () {
  31161. withRoot(function (root) {
  31162. emit(root, formUnblockEvent);
  31163. });
  31164. };
  31165. var showTab = function (name) {
  31166. withRoot(function (_) {
  31167. var body = access.getBody();
  31168. var bodyState = Reflecting.getState(body);
  31169. if (bodyState.get().exists(function (b) {
  31170. return b.isTabPanel();
  31171. })) {
  31172. Composing.getCurrent(body).each(function (tabSection) {
  31173. TabSection.showTab(tabSection, name);
  31174. });
  31175. }
  31176. });
  31177. };
  31178. var redial = function (d) {
  31179. withRoot(function (root) {
  31180. var dialogInit = doRedial(d);
  31181. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  31182. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  31183. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  31184. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  31185. instanceApi.setData(dialogInit.initialData);
  31186. });
  31187. };
  31188. var close = function () {
  31189. withRoot(function (root) {
  31190. emit(root, formCloseEvent);
  31191. });
  31192. };
  31193. var instanceApi = {
  31194. getData: getData,
  31195. setData: setData,
  31196. disable: disable,
  31197. enable: enable,
  31198. focus: focus,
  31199. block: block,
  31200. unblock: unblock,
  31201. showTab: showTab,
  31202. redial: redial,
  31203. close: close
  31204. };
  31205. return instanceApi;
  31206. };
  31207. var getDialogSizeClasses = function (size) {
  31208. switch (size) {
  31209. case 'large':
  31210. return ['tox-dialog--width-lg'];
  31211. case 'medium':
  31212. return ['tox-dialog--width-md'];
  31213. default:
  31214. return [];
  31215. }
  31216. };
  31217. var renderDialog = function (dialogInit, extra, backstage) {
  31218. var header = getHeader(dialogInit.internalDialog.title, backstage);
  31219. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  31220. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  31221. var objOfCells = extractCellsToObject(storagedMenuButtons);
  31222. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  31223. var dialogEvents = SilverDialogEvents.initDialog(function () {
  31224. return instanceApi;
  31225. }, getEventExtras(function () {
  31226. return dialog;
  31227. }, backstage.shared.providers, extra), backstage.shared.getSink);
  31228. var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size);
  31229. var spec = {
  31230. header: header,
  31231. body: body,
  31232. footer: Optional.some(footer),
  31233. extraClasses: dialogSize,
  31234. extraBehaviours: [],
  31235. extraStyles: {}
  31236. };
  31237. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  31238. var modalAccess = function () {
  31239. var getForm = function () {
  31240. var outerForm = ModalDialog.getBody(dialog);
  31241. return Composing.getCurrent(outerForm).getOr(outerForm);
  31242. };
  31243. return {
  31244. getRoot: constant$1(dialog),
  31245. getBody: function () {
  31246. return ModalDialog.getBody(dialog);
  31247. },
  31248. getFooter: function () {
  31249. return ModalDialog.getFooter(dialog);
  31250. },
  31251. getFormWrapper: getForm
  31252. };
  31253. }();
  31254. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  31255. return {
  31256. dialog: dialog,
  31257. instanceApi: instanceApi
  31258. };
  31259. };
  31260. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  31261. var _a, _b;
  31262. var dialogLabelId = generate$6('dialog-label');
  31263. var dialogContentId = generate$6('dialog-content');
  31264. var updateState = function (_comp, incoming) {
  31265. return Optional.some(incoming);
  31266. };
  31267. var memHeader = record(renderInlineHeader({
  31268. title: dialogInit.internalDialog.title,
  31269. draggable: true
  31270. }, dialogLabelId, backstage.shared.providers));
  31271. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  31272. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  31273. var objOfCells = extractCellsToObject(storagedMenuButtons);
  31274. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  31275. var dialogEvents = SilverDialogEvents.initDialog(function () {
  31276. return instanceApi;
  31277. }, {
  31278. onBlock: function (event) {
  31279. Blocking.block(dialog, function (_comp, bs) {
  31280. return getBusySpec(event.message, bs, backstage.shared.providers);
  31281. });
  31282. },
  31283. onUnblock: function () {
  31284. Blocking.unblock(dialog);
  31285. },
  31286. onClose: function () {
  31287. return extra.closeWindow();
  31288. }
  31289. }, backstage.shared.getSink);
  31290. var dialog = build$1({
  31291. dom: {
  31292. tag: 'div',
  31293. classes: [
  31294. 'tox-dialog',
  31295. 'tox-dialog-inline'
  31296. ],
  31297. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = dialogContentId, _a)
  31298. },
  31299. eventOrder: (_b = {}, _b[receive()] = [
  31300. Reflecting.name(),
  31301. Receiving.name()
  31302. ], _b[execute$5()] = ['execute-on-form'], _b[attachedToDom()] = [
  31303. 'reflecting',
  31304. 'execute-on-form'
  31305. ], _b),
  31306. behaviours: derive$1([
  31307. Keying.config({
  31308. mode: 'cyclic',
  31309. onEscape: function (c) {
  31310. emit(c, formCloseEvent);
  31311. return Optional.some(true);
  31312. },
  31313. useTabstopAt: function (elem) {
  31314. return !isPseudoStop(elem) && (name$2(elem) !== 'button' || get$d(elem, 'disabled') !== 'disabled');
  31315. }
  31316. }),
  31317. Reflecting.config({
  31318. channel: dialogChannel,
  31319. updateState: updateState,
  31320. initialData: dialogInit
  31321. }),
  31322. Focusing.config({}),
  31323. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  31324. Keying.focusIn(comp);
  31325. })])),
  31326. Blocking.config({
  31327. getRoot: function () {
  31328. return Optional.some(dialog);
  31329. }
  31330. }),
  31331. Replacing.config({}),
  31332. RepresentingConfigs.memory({})
  31333. ]),
  31334. components: [
  31335. memHeader.asSpec(),
  31336. memBody.asSpec(),
  31337. memFooter.asSpec()
  31338. ]
  31339. });
  31340. var instanceApi = getDialogApi({
  31341. getRoot: constant$1(dialog),
  31342. getFooter: function () {
  31343. return memFooter.get(dialog);
  31344. },
  31345. getBody: function () {
  31346. return memBody.get(dialog);
  31347. },
  31348. getFormWrapper: function () {
  31349. var body = memBody.get(dialog);
  31350. return Composing.getCurrent(body).getOr(body);
  31351. }
  31352. }, extra.redial, objOfCells);
  31353. return {
  31354. dialog: dialog,
  31355. instanceApi: instanceApi
  31356. };
  31357. };
  31358. var global$1 = tinymce.util.Tools.resolve('tinymce.util.URI');
  31359. var getUrlDialogApi = function (root) {
  31360. var withRoot = function (f) {
  31361. if (root.getSystem().isConnected()) {
  31362. f(root);
  31363. }
  31364. };
  31365. var block = function (message) {
  31366. if (!isString(message)) {
  31367. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  31368. }
  31369. withRoot(function (root) {
  31370. emitWith(root, formBlockEvent, { message: message });
  31371. });
  31372. };
  31373. var unblock = function () {
  31374. withRoot(function (root) {
  31375. emit(root, formUnblockEvent);
  31376. });
  31377. };
  31378. var close = function () {
  31379. withRoot(function (root) {
  31380. emit(root, formCloseEvent);
  31381. });
  31382. };
  31383. var sendMessage = function (data) {
  31384. withRoot(function (root) {
  31385. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  31386. });
  31387. };
  31388. return {
  31389. block: block,
  31390. unblock: unblock,
  31391. close: close,
  31392. sendMessage: sendMessage
  31393. };
  31394. };
  31395. var SUPPORTED_MESSAGE_ACTIONS = [
  31396. 'insertContent',
  31397. 'setContent',
  31398. 'execCommand',
  31399. 'close',
  31400. 'block',
  31401. 'unblock'
  31402. ];
  31403. var isSupportedMessage = function (data) {
  31404. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  31405. };
  31406. var isCustomMessage = function (data) {
  31407. return !isSupportedMessage(data) && isObject(data) && has$2(data, 'mceAction');
  31408. };
  31409. var handleMessage = function (editor, api, data) {
  31410. switch (data.mceAction) {
  31411. case 'insertContent':
  31412. editor.insertContent(data.content);
  31413. break;
  31414. case 'setContent':
  31415. editor.setContent(data.content);
  31416. break;
  31417. case 'execCommand':
  31418. var ui = isBoolean(data.ui) ? data.ui : false;
  31419. editor.execCommand(data.cmd, ui, data.value);
  31420. break;
  31421. case 'close':
  31422. api.close();
  31423. break;
  31424. case 'block':
  31425. api.block(data.message);
  31426. break;
  31427. case 'unblock':
  31428. api.unblock();
  31429. break;
  31430. }
  31431. };
  31432. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  31433. var _a;
  31434. var header = getHeader(internalDialog.title, backstage);
  31435. var body = renderIframeBody(internalDialog);
  31436. var footer = internalDialog.buttons.bind(function (buttons) {
  31437. if (buttons.length === 0) {
  31438. return Optional.none();
  31439. } else {
  31440. return Optional.some(renderModalFooter({ buttons: buttons }, backstage));
  31441. }
  31442. });
  31443. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  31444. return instanceApi;
  31445. }, getEventExtras(function () {
  31446. return dialog;
  31447. }, backstage.shared.providers, extra));
  31448. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  31449. return {};
  31450. }, function (height) {
  31451. return {
  31452. 'height': height + 'px',
  31453. 'max-height': height + 'px'
  31454. };
  31455. })), internalDialog.width.fold(function () {
  31456. return {};
  31457. }, function (width) {
  31458. return {
  31459. 'width': width + 'px',
  31460. 'max-width': width + 'px'
  31461. };
  31462. }));
  31463. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  31464. var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) });
  31465. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  31466. var messageHandlerUnbinder = unbindable();
  31467. var extraBehaviours = [
  31468. config('messages', [
  31469. runOnAttached(function () {
  31470. var unbind = bind(SugarElement.fromDom(window), 'message', function (e) {
  31471. if (iframeUri.isSameOrigin(new global$1(e.raw.origin))) {
  31472. var data = e.raw.data;
  31473. if (isSupportedMessage(data)) {
  31474. handleMessage(editor, instanceApi, data);
  31475. } else if (isCustomMessage(data)) {
  31476. internalDialog.onMessage(instanceApi, data);
  31477. }
  31478. }
  31479. });
  31480. messageHandlerUnbinder.set(unbind);
  31481. }),
  31482. runOnDetached(messageHandlerUnbinder.clear)
  31483. ]),
  31484. Receiving.config({
  31485. channels: (_a = {}, _a[bodySendMessageChannel] = {
  31486. onReceive: function (comp, data) {
  31487. descendant(comp.element, 'iframe').each(function (iframeEle) {
  31488. var iframeWin = iframeEle.dom.contentWindow;
  31489. iframeWin.postMessage(data, iframeDomain);
  31490. });
  31491. }
  31492. }, _a)
  31493. })
  31494. ];
  31495. var spec = {
  31496. header: header,
  31497. body: body,
  31498. footer: footer,
  31499. extraClasses: classes,
  31500. extraBehaviours: extraBehaviours,
  31501. extraStyles: styles
  31502. };
  31503. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  31504. var instanceApi = getUrlDialogApi(dialog);
  31505. return {
  31506. dialog: dialog,
  31507. instanceApi: instanceApi
  31508. };
  31509. };
  31510. var setup$2 = function (extras) {
  31511. var sharedBackstage = extras.backstage.shared;
  31512. var open = function (message, callback) {
  31513. var closeDialog = function () {
  31514. ModalDialog.hide(alertDialog);
  31515. callback();
  31516. };
  31517. var memFooterClose = record(renderFooterButton({
  31518. name: 'close-alert',
  31519. text: 'OK',
  31520. primary: true,
  31521. align: 'end',
  31522. disabled: false,
  31523. icon: Optional.none()
  31524. }, 'cancel', extras.backstage));
  31525. var titleSpec = pUntitled();
  31526. var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  31527. var alertDialog = build$1(renderDialog$1({
  31528. lazySink: function () {
  31529. return sharedBackstage.getSink();
  31530. },
  31531. header: hiddenHeader(titleSpec, closeSpec),
  31532. body: pBodyMessage(message, sharedBackstage.providers),
  31533. footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  31534. onEscape: closeDialog,
  31535. extraClasses: ['tox-alert-dialog'],
  31536. extraBehaviours: [],
  31537. extraStyles: {},
  31538. dialogEvents: [run$1(formCancelEvent, closeDialog)],
  31539. eventOrder: {}
  31540. }));
  31541. ModalDialog.show(alertDialog);
  31542. var footerCloseButton = memFooterClose.get(alertDialog);
  31543. Focusing.focus(footerCloseButton);
  31544. };
  31545. return { open: open };
  31546. };
  31547. var setup$1 = function (extras) {
  31548. var sharedBackstage = extras.backstage.shared;
  31549. var open = function (message, callback) {
  31550. var closeDialog = function (state) {
  31551. ModalDialog.hide(confirmDialog);
  31552. callback(state);
  31553. };
  31554. var memFooterYes = record(renderFooterButton({
  31555. name: 'yes',
  31556. text: 'Yes',
  31557. primary: true,
  31558. align: 'end',
  31559. disabled: false,
  31560. icon: Optional.none()
  31561. }, 'submit', extras.backstage));
  31562. var footerNo = renderFooterButton({
  31563. name: 'no',
  31564. text: 'No',
  31565. primary: false,
  31566. align: 'end',
  31567. disabled: false,
  31568. icon: Optional.none()
  31569. }, 'cancel', extras.backstage);
  31570. var titleSpec = pUntitled();
  31571. var closeSpec = pClose(function () {
  31572. return closeDialog(false);
  31573. }, sharedBackstage.providers);
  31574. var confirmDialog = build$1(renderDialog$1({
  31575. lazySink: function () {
  31576. return sharedBackstage.getSink();
  31577. },
  31578. header: hiddenHeader(titleSpec, closeSpec),
  31579. body: pBodyMessage(message, sharedBackstage.providers),
  31580. footer: Optional.some(pFooter(pFooterGroup([], [
  31581. footerNo,
  31582. memFooterYes.asSpec()
  31583. ]))),
  31584. onEscape: function () {
  31585. return closeDialog(false);
  31586. },
  31587. extraClasses: ['tox-confirm-dialog'],
  31588. extraBehaviours: [],
  31589. extraStyles: {},
  31590. dialogEvents: [
  31591. run$1(formCancelEvent, function () {
  31592. return closeDialog(false);
  31593. }),
  31594. run$1(formSubmitEvent, function () {
  31595. return closeDialog(true);
  31596. })
  31597. ],
  31598. eventOrder: {}
  31599. }));
  31600. ModalDialog.show(confirmDialog);
  31601. var footerYesButton = memFooterYes.get(confirmDialog);
  31602. Focusing.focus(footerYesButton);
  31603. };
  31604. return { open: open };
  31605. };
  31606. var validateData = function (data, validator) {
  31607. return getOrDie(asRaw('data', validator, data));
  31608. };
  31609. var isAlertOrConfirmDialog = function (target) {
  31610. return closest(target, '.tox-alert-dialog') || closest(target, '.tox-confirm-dialog');
  31611. };
  31612. var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  31613. if (isStickyToolbar && isToolbarLocationTop) {
  31614. return [];
  31615. } else {
  31616. return [Docking.config({
  31617. contextual: {
  31618. lazyContext: function () {
  31619. return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer())));
  31620. },
  31621. fadeInClass: 'tox-dialog-dock-fadein',
  31622. fadeOutClass: 'tox-dialog-dock-fadeout',
  31623. transitionClass: 'tox-dialog-dock-transition'
  31624. },
  31625. modes: ['top']
  31626. })];
  31627. }
  31628. };
  31629. var setup = function (extras) {
  31630. var backstage = extras.backstage;
  31631. var editor = extras.editor;
  31632. var isStickyToolbar$1 = isStickyToolbar(editor);
  31633. var alertDialog = setup$2(extras);
  31634. var confirmDialog = setup$1(extras);
  31635. var open = function (config, params, closeWindow) {
  31636. if (params !== undefined && params.inline === 'toolbar') {
  31637. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  31638. } else if (params !== undefined && params.inline === 'cursor') {
  31639. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  31640. } else {
  31641. return openModalDialog(config, closeWindow);
  31642. }
  31643. };
  31644. var openUrl = function (config, closeWindow) {
  31645. return openModalUrlDialog(config, closeWindow);
  31646. };
  31647. var openModalUrlDialog = function (config, closeWindow) {
  31648. var factory = function (contents) {
  31649. var dialog = renderUrlDialog(contents, {
  31650. closeWindow: function () {
  31651. ModalDialog.hide(dialog.dialog);
  31652. closeWindow(dialog.instanceApi);
  31653. }
  31654. }, editor, backstage);
  31655. ModalDialog.show(dialog.dialog);
  31656. return dialog.instanceApi;
  31657. };
  31658. return DialogManager.openUrl(factory, config);
  31659. };
  31660. var openModalDialog = function (config, closeWindow) {
  31661. var factory = function (contents, internalInitialData, dataValidator) {
  31662. var initialData = internalInitialData;
  31663. var dialogInit = {
  31664. dataValidator: dataValidator,
  31665. initialData: initialData,
  31666. internalDialog: contents
  31667. };
  31668. var dialog = renderDialog(dialogInit, {
  31669. redial: DialogManager.redial,
  31670. closeWindow: function () {
  31671. ModalDialog.hide(dialog.dialog);
  31672. closeWindow(dialog.instanceApi);
  31673. }
  31674. }, backstage);
  31675. ModalDialog.show(dialog.dialog);
  31676. dialog.instanceApi.setData(initialData);
  31677. return dialog.instanceApi;
  31678. };
  31679. return DialogManager.open(factory, config);
  31680. };
  31681. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  31682. var factory = function (contents, internalInitialData, dataValidator) {
  31683. var initialData = validateData(internalInitialData, dataValidator);
  31684. var inlineDialog = value$1();
  31685. var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  31686. var dialogInit = {
  31687. dataValidator: dataValidator,
  31688. initialData: initialData,
  31689. internalDialog: contents
  31690. };
  31691. var refreshDocking = function () {
  31692. return inlineDialog.on(function (dialog) {
  31693. InlineView.reposition(dialog);
  31694. Docking.refresh(dialog);
  31695. });
  31696. };
  31697. var dialogUi = renderInlineDialog(dialogInit, {
  31698. redial: DialogManager.redial,
  31699. closeWindow: function () {
  31700. inlineDialog.on(InlineView.hide);
  31701. editor.off('ResizeEditor', refreshDocking);
  31702. inlineDialog.clear();
  31703. closeWindow(dialogUi.instanceApi);
  31704. }
  31705. }, backstage, ariaAttrs);
  31706. var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  31707. lazySink: backstage.shared.getSink,
  31708. dom: {
  31709. tag: 'div',
  31710. classes: []
  31711. },
  31712. fireDismissalEventInstead: {}
  31713. }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
  31714. inlineBehaviours: derive$1(__spreadArray([config('window-manager-inline-events', [run$1(dismissRequested(), function (_comp, _se) {
  31715. emit(dialogUi.dialog, formCancelEvent);
  31716. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop), true)),
  31717. isExtraPart: function (_comp, target) {
  31718. return isAlertOrConfirmDialog(target);
  31719. }
  31720. })));
  31721. inlineDialog.set(inlineDialogComp);
  31722. InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor }, Optional.some(body()));
  31723. if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  31724. Docking.refresh(inlineDialogComp);
  31725. editor.on('ResizeEditor', refreshDocking);
  31726. }
  31727. dialogUi.instanceApi.setData(initialData);
  31728. Keying.focusIn(dialogUi.dialog);
  31729. return dialogUi.instanceApi;
  31730. };
  31731. return DialogManager.open(factory, config$1);
  31732. };
  31733. var confirm = function (message, callback) {
  31734. confirmDialog.open(message, function (state) {
  31735. callback(state);
  31736. });
  31737. };
  31738. var alert = function (message, callback) {
  31739. alertDialog.open(message, function () {
  31740. callback();
  31741. });
  31742. };
  31743. var close = function (instanceApi) {
  31744. instanceApi.close();
  31745. };
  31746. return {
  31747. open: open,
  31748. openUrl: openUrl,
  31749. alert: alert,
  31750. close: close,
  31751. confirm: confirm
  31752. };
  31753. };
  31754. function Theme () {
  31755. global$g.add('silver', function (editor) {
  31756. var _a = setup$3(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  31757. Autocompleter.register(editor, backstage.shared);
  31758. var windowMgr = setup({
  31759. editor: editor,
  31760. backstage: backstage
  31761. });
  31762. return {
  31763. renderUI: renderUI,
  31764. getWindowManagerImpl: constant$1(windowMgr),
  31765. getNotificationManagerImpl: function () {
  31766. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  31767. },
  31768. ui: getUi()
  31769. };
  31770. });
  31771. }
  31772. Theme();
  31773. }());