theme.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667
  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.3.0 (2020-05-21)
  8. */
  9. (function (domGlobals) {
  10. 'use strict';
  11. var noop = function () {
  12. };
  13. var noarg = function (f) {
  14. return function () {
  15. return f();
  16. };
  17. };
  18. var compose = function (fa, fb) {
  19. return function () {
  20. var args = [];
  21. for (var _i = 0; _i < arguments.length; _i++) {
  22. args[_i] = arguments[_i];
  23. }
  24. return fa(fb.apply(null, args));
  25. };
  26. };
  27. var constant = function (value) {
  28. return function () {
  29. return value;
  30. };
  31. };
  32. var identity = function (x) {
  33. return x;
  34. };
  35. function curry(fn) {
  36. var initialArgs = [];
  37. for (var _i = 1; _i < arguments.length; _i++) {
  38. initialArgs[_i - 1] = arguments[_i];
  39. }
  40. return function () {
  41. var restArgs = [];
  42. for (var _i = 0; _i < arguments.length; _i++) {
  43. restArgs[_i] = arguments[_i];
  44. }
  45. var all = initialArgs.concat(restArgs);
  46. return fn.apply(null, all);
  47. };
  48. }
  49. var not = function (f) {
  50. return function (t) {
  51. return !f(t);
  52. };
  53. };
  54. var die = function (msg) {
  55. return function () {
  56. throw new Error(msg);
  57. };
  58. };
  59. var never = constant(false);
  60. var always = constant(true);
  61. var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  62. var __assign = function () {
  63. __assign = Object.assign || function __assign(t) {
  64. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65. s = arguments[i];
  66. for (var p in s)
  67. if (Object.prototype.hasOwnProperty.call(s, p))
  68. t[p] = s[p];
  69. }
  70. return t;
  71. };
  72. return __assign.apply(this, arguments);
  73. };
  74. function __rest(s, e) {
  75. var t = {};
  76. for (var p in s)
  77. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  78. t[p] = s[p];
  79. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  80. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  81. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  82. t[p[i]] = s[p[i]];
  83. }
  84. return t;
  85. }
  86. function __spreadArrays() {
  87. for (var s = 0, i = 0, il = arguments.length; i < il; i++)
  88. s += arguments[i].length;
  89. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  90. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  91. r[k] = a[j];
  92. return r;
  93. }
  94. var none = function () {
  95. return NONE;
  96. };
  97. var NONE = function () {
  98. var eq = function (o) {
  99. return o.isNone();
  100. };
  101. var call = function (thunk) {
  102. return thunk();
  103. };
  104. var id = function (n) {
  105. return n;
  106. };
  107. var me = {
  108. fold: function (n, _s) {
  109. return n();
  110. },
  111. is: never,
  112. isSome: never,
  113. isNone: always,
  114. getOr: id,
  115. getOrThunk: call,
  116. getOrDie: function (msg) {
  117. throw new Error(msg || 'error: getOrDie called on none.');
  118. },
  119. getOrNull: constant(null),
  120. getOrUndefined: constant(undefined),
  121. or: id,
  122. orThunk: call,
  123. map: none,
  124. each: noop,
  125. bind: none,
  126. exists: never,
  127. forall: always,
  128. filter: none,
  129. equals: eq,
  130. equals_: eq,
  131. toArray: function () {
  132. return [];
  133. },
  134. toString: constant('none()')
  135. };
  136. return me;
  137. }();
  138. var some = function (a) {
  139. var constant_a = constant(a);
  140. var self = function () {
  141. return me;
  142. };
  143. var bind = function (f) {
  144. return f(a);
  145. };
  146. var me = {
  147. fold: function (n, s) {
  148. return s(a);
  149. },
  150. is: function (v) {
  151. return a === v;
  152. },
  153. isSome: always,
  154. isNone: never,
  155. getOr: constant_a,
  156. getOrThunk: constant_a,
  157. getOrDie: constant_a,
  158. getOrNull: constant_a,
  159. getOrUndefined: constant_a,
  160. or: self,
  161. orThunk: self,
  162. map: function (f) {
  163. return some(f(a));
  164. },
  165. each: function (f) {
  166. f(a);
  167. },
  168. bind: bind,
  169. exists: bind,
  170. forall: bind,
  171. filter: function (f) {
  172. return f(a) ? me : NONE;
  173. },
  174. toArray: function () {
  175. return [a];
  176. },
  177. toString: function () {
  178. return 'some(' + a + ')';
  179. },
  180. equals: function (o) {
  181. return o.is(a);
  182. },
  183. equals_: function (o, elementEq) {
  184. return o.fold(never, function (b) {
  185. return elementEq(a, b);
  186. });
  187. }
  188. };
  189. return me;
  190. };
  191. var from = function (value) {
  192. return value === null || value === undefined ? NONE : some(value);
  193. };
  194. var Option = {
  195. some: some,
  196. none: none,
  197. from: from
  198. };
  199. var value = function (o) {
  200. var is = function (v) {
  201. return o === v;
  202. };
  203. var or = function (_opt) {
  204. return value(o);
  205. };
  206. var orThunk = function (_f) {
  207. return value(o);
  208. };
  209. var map = function (f) {
  210. return value(f(o));
  211. };
  212. var mapError = function (_f) {
  213. return value(o);
  214. };
  215. var each = function (f) {
  216. f(o);
  217. };
  218. var bind = function (f) {
  219. return f(o);
  220. };
  221. var fold = function (_, onValue) {
  222. return onValue(o);
  223. };
  224. var exists = function (f) {
  225. return f(o);
  226. };
  227. var forall = function (f) {
  228. return f(o);
  229. };
  230. var toOption = function () {
  231. return Option.some(o);
  232. };
  233. return {
  234. is: is,
  235. isValue: always,
  236. isError: never,
  237. getOr: constant(o),
  238. getOrThunk: constant(o),
  239. getOrDie: constant(o),
  240. or: or,
  241. orThunk: orThunk,
  242. fold: fold,
  243. map: map,
  244. mapError: mapError,
  245. each: each,
  246. bind: bind,
  247. exists: exists,
  248. forall: forall,
  249. toOption: toOption
  250. };
  251. };
  252. var error = function (message) {
  253. var getOrThunk = function (f) {
  254. return f();
  255. };
  256. var getOrDie = function () {
  257. return die(String(message))();
  258. };
  259. var or = function (opt) {
  260. return opt;
  261. };
  262. var orThunk = function (f) {
  263. return f();
  264. };
  265. var map = function (_f) {
  266. return error(message);
  267. };
  268. var mapError = function (f) {
  269. return error(f(message));
  270. };
  271. var bind = function (_f) {
  272. return error(message);
  273. };
  274. var fold = function (onError, _) {
  275. return onError(message);
  276. };
  277. return {
  278. is: never,
  279. isValue: never,
  280. isError: always,
  281. getOr: identity,
  282. getOrThunk: getOrThunk,
  283. getOrDie: getOrDie,
  284. or: or,
  285. orThunk: orThunk,
  286. fold: fold,
  287. map: map,
  288. mapError: mapError,
  289. each: noop,
  290. bind: bind,
  291. exists: never,
  292. forall: always,
  293. toOption: Option.none
  294. };
  295. };
  296. var fromOption = function (opt, err) {
  297. return opt.fold(function () {
  298. return error(err);
  299. }, value);
  300. };
  301. var Result = {
  302. value: value,
  303. error: error,
  304. fromOption: fromOption
  305. };
  306. var typeOf = function (x) {
  307. var t = typeof x;
  308. if (x === null) {
  309. return 'null';
  310. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  311. return 'array';
  312. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  313. return 'string';
  314. } else {
  315. return t;
  316. }
  317. };
  318. var isType = function (type) {
  319. return function (value) {
  320. return typeOf(value) === type;
  321. };
  322. };
  323. var isSimpleType = function (type) {
  324. return function (value) {
  325. return typeof value === type;
  326. };
  327. };
  328. var eq = function (t) {
  329. return function (a) {
  330. return t === a;
  331. };
  332. };
  333. var isString = isType('string');
  334. var isObject = isType('object');
  335. var isArray = isType('array');
  336. var isBoolean = isSimpleType('boolean');
  337. var isUndefined = eq(undefined);
  338. var isFunction = isSimpleType('function');
  339. var isNumber = isSimpleType('number');
  340. var isArrayOf = function (value, pred) {
  341. if (isArray(value)) {
  342. for (var i = 0, len = value.length; i < len; ++i) {
  343. if (!pred(value[i])) {
  344. return false;
  345. }
  346. }
  347. return true;
  348. }
  349. return false;
  350. };
  351. var nativeSlice = Array.prototype.slice;
  352. var nativeIndexOf = Array.prototype.indexOf;
  353. var nativePush = Array.prototype.push;
  354. var rawIndexOf = function (ts, t) {
  355. return nativeIndexOf.call(ts, t);
  356. };
  357. var indexOf = function (xs, x) {
  358. var r = rawIndexOf(xs, x);
  359. return r === -1 ? Option.none() : Option.some(r);
  360. };
  361. var contains = function (xs, x) {
  362. return rawIndexOf(xs, x) > -1;
  363. };
  364. var exists = function (xs, pred) {
  365. for (var i = 0, len = xs.length; i < len; i++) {
  366. var x = xs[i];
  367. if (pred(x, i)) {
  368. return true;
  369. }
  370. }
  371. return false;
  372. };
  373. var range = function (num, f) {
  374. var r = [];
  375. for (var i = 0; i < num; i++) {
  376. r.push(f(i));
  377. }
  378. return r;
  379. };
  380. var chunk = function (array, size) {
  381. var r = [];
  382. for (var i = 0; i < array.length; i += size) {
  383. var s = nativeSlice.call(array, i, i + size);
  384. r.push(s);
  385. }
  386. return r;
  387. };
  388. var map = function (xs, f) {
  389. var len = xs.length;
  390. var r = new Array(len);
  391. for (var i = 0; i < len; i++) {
  392. var x = xs[i];
  393. r[i] = f(x, i);
  394. }
  395. return r;
  396. };
  397. var each = function (xs, f) {
  398. for (var i = 0, len = xs.length; i < len; i++) {
  399. var x = xs[i];
  400. f(x, i);
  401. }
  402. };
  403. var eachr = function (xs, f) {
  404. for (var i = xs.length - 1; i >= 0; i--) {
  405. var x = xs[i];
  406. f(x, i);
  407. }
  408. };
  409. var partition = function (xs, pred) {
  410. var pass = [];
  411. var fail = [];
  412. for (var i = 0, len = xs.length; i < len; i++) {
  413. var x = xs[i];
  414. var arr = pred(x, i) ? pass : fail;
  415. arr.push(x);
  416. }
  417. return {
  418. pass: pass,
  419. fail: fail
  420. };
  421. };
  422. var filter = function (xs, pred) {
  423. var r = [];
  424. for (var i = 0, len = xs.length; i < len; i++) {
  425. var x = xs[i];
  426. if (pred(x, i)) {
  427. r.push(x);
  428. }
  429. }
  430. return r;
  431. };
  432. var foldr = function (xs, f, acc) {
  433. eachr(xs, function (x) {
  434. acc = f(acc, x);
  435. });
  436. return acc;
  437. };
  438. var foldl = function (xs, f, acc) {
  439. each(xs, function (x) {
  440. acc = f(acc, x);
  441. });
  442. return acc;
  443. };
  444. var findUntil = function (xs, pred, until) {
  445. for (var i = 0, len = xs.length; i < len; i++) {
  446. var x = xs[i];
  447. if (pred(x, i)) {
  448. return Option.some(x);
  449. } else if (until(x, i)) {
  450. break;
  451. }
  452. }
  453. return Option.none();
  454. };
  455. var find = function (xs, pred) {
  456. return findUntil(xs, pred, never);
  457. };
  458. var findIndex = function (xs, pred) {
  459. for (var i = 0, len = xs.length; i < len; i++) {
  460. var x = xs[i];
  461. if (pred(x, i)) {
  462. return Option.some(i);
  463. }
  464. }
  465. return Option.none();
  466. };
  467. var flatten = function (xs) {
  468. var r = [];
  469. for (var i = 0, len = xs.length; i < len; ++i) {
  470. if (!isArray(xs[i])) {
  471. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  472. }
  473. nativePush.apply(r, xs[i]);
  474. }
  475. return r;
  476. };
  477. var bind = function (xs, f) {
  478. return flatten(map(xs, f));
  479. };
  480. var forall = function (xs, pred) {
  481. for (var i = 0, len = xs.length; i < len; ++i) {
  482. var x = xs[i];
  483. if (pred(x, i) !== true) {
  484. return false;
  485. }
  486. }
  487. return true;
  488. };
  489. var reverse = function (xs) {
  490. var r = nativeSlice.call(xs, 0);
  491. r.reverse();
  492. return r;
  493. };
  494. var difference = function (a1, a2) {
  495. return filter(a1, function (x) {
  496. return !contains(a2, x);
  497. });
  498. };
  499. var mapToObject = function (xs, f) {
  500. var r = {};
  501. for (var i = 0, len = xs.length; i < len; i++) {
  502. var x = xs[i];
  503. r[String(x)] = f(x, i);
  504. }
  505. return r;
  506. };
  507. var pure = function (x) {
  508. return [x];
  509. };
  510. var sort = function (xs, comparator) {
  511. var copy = nativeSlice.call(xs, 0);
  512. copy.sort(comparator);
  513. return copy;
  514. };
  515. var head = function (xs) {
  516. return xs.length === 0 ? Option.none() : Option.some(xs[0]);
  517. };
  518. var last = function (xs) {
  519. return xs.length === 0 ? Option.none() : Option.some(xs[xs.length - 1]);
  520. };
  521. var from$1 = isFunction(Array.from) ? Array.from : function (x) {
  522. return nativeSlice.call(x);
  523. };
  524. var findMap = function (arr, f) {
  525. for (var i = 0; i < arr.length; i++) {
  526. var r = f(arr[i], i);
  527. if (r.isSome()) {
  528. return r;
  529. }
  530. }
  531. return Option.none();
  532. };
  533. var keys = Object.keys;
  534. var hasOwnProperty = Object.hasOwnProperty;
  535. var each$1 = function (obj, f) {
  536. var props = keys(obj);
  537. for (var k = 0, len = props.length; k < len; k++) {
  538. var i = props[k];
  539. var x = obj[i];
  540. f(x, i);
  541. }
  542. };
  543. var map$1 = function (obj, f) {
  544. return tupleMap(obj, function (x, i) {
  545. return {
  546. k: i,
  547. v: f(x, i)
  548. };
  549. });
  550. };
  551. var tupleMap = function (obj, f) {
  552. var r = {};
  553. each$1(obj, function (x, i) {
  554. var tuple = f(x, i);
  555. r[tuple.k] = tuple.v;
  556. });
  557. return r;
  558. };
  559. var objAcc = function (r) {
  560. return function (x, i) {
  561. r[i] = x;
  562. };
  563. };
  564. var internalFilter = function (obj, pred, onTrue, onFalse) {
  565. var r = {};
  566. each$1(obj, function (x, i) {
  567. (pred(x, i) ? onTrue : onFalse)(x, i);
  568. });
  569. return r;
  570. };
  571. var filter$1 = function (obj, pred) {
  572. var t = {};
  573. internalFilter(obj, pred, objAcc(t), noop);
  574. return t;
  575. };
  576. var mapToArray = function (obj, f) {
  577. var r = [];
  578. each$1(obj, function (value, name) {
  579. r.push(f(value, name));
  580. });
  581. return r;
  582. };
  583. var find$1 = function (obj, pred) {
  584. var props = keys(obj);
  585. for (var k = 0, len = props.length; k < len; k++) {
  586. var i = props[k];
  587. var x = obj[i];
  588. if (pred(x, i, obj)) {
  589. return Option.some(x);
  590. }
  591. }
  592. return Option.none();
  593. };
  594. var values = function (obj) {
  595. return mapToArray(obj, function (v) {
  596. return v;
  597. });
  598. };
  599. var get = function (obj, key) {
  600. return has(obj, key) ? Option.from(obj[key]) : Option.none();
  601. };
  602. var has = function (obj, key) {
  603. return hasOwnProperty.call(obj, key);
  604. };
  605. var hasNonNullableKey = function (obj, key) {
  606. return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  607. };
  608. var generate = function (cases) {
  609. if (!isArray(cases)) {
  610. throw new Error('cases must be an array');
  611. }
  612. if (cases.length === 0) {
  613. throw new Error('there must be at least one case');
  614. }
  615. var constructors = [];
  616. var adt = {};
  617. each(cases, function (acase, count) {
  618. var keys$1 = keys(acase);
  619. if (keys$1.length !== 1) {
  620. throw new Error('one and only one name per case');
  621. }
  622. var key = keys$1[0];
  623. var value = acase[key];
  624. if (adt[key] !== undefined) {
  625. throw new Error('duplicate key detected:' + key);
  626. } else if (key === 'cata') {
  627. throw new Error('cannot have a case named cata (sorry)');
  628. } else if (!isArray(value)) {
  629. throw new Error('case arguments must be an array');
  630. }
  631. constructors.push(key);
  632. adt[key] = function () {
  633. var argLength = arguments.length;
  634. if (argLength !== value.length) {
  635. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  636. }
  637. var args = new Array(argLength);
  638. for (var i = 0; i < args.length; i++) {
  639. args[i] = arguments[i];
  640. }
  641. var match = function (branches) {
  642. var branchKeys = keys(branches);
  643. if (constructors.length !== branchKeys.length) {
  644. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  645. }
  646. var allReqd = forall(constructors, function (reqKey) {
  647. return contains(branchKeys, reqKey);
  648. });
  649. if (!allReqd) {
  650. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  651. }
  652. return branches[key].apply(null, args);
  653. };
  654. return {
  655. fold: function () {
  656. if (arguments.length !== cases.length) {
  657. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
  658. }
  659. var target = arguments[count];
  660. return target.apply(null, args);
  661. },
  662. match: match,
  663. log: function (label) {
  664. domGlobals.console.log(label, {
  665. constructors: constructors,
  666. constructor: key,
  667. params: args
  668. });
  669. }
  670. };
  671. };
  672. });
  673. return adt;
  674. };
  675. var Adt = { generate: generate };
  676. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  677. var shallow = function (old, nu) {
  678. return nu;
  679. };
  680. var deep = function (old, nu) {
  681. var bothObjects = isObject(old) && isObject(nu);
  682. return bothObjects ? deepMerge(old, nu) : nu;
  683. };
  684. var baseMerge = function (merger) {
  685. return function () {
  686. var objects = new Array(arguments.length);
  687. for (var i = 0; i < objects.length; i++) {
  688. objects[i] = arguments[i];
  689. }
  690. if (objects.length === 0) {
  691. throw new Error('Can\'t merge zero objects');
  692. }
  693. var ret = {};
  694. for (var j = 0; j < objects.length; j++) {
  695. var curObject = objects[j];
  696. for (var key in curObject) {
  697. if (hasOwnProperty$1.call(curObject, key)) {
  698. ret[key] = merger(ret[key], curObject[key]);
  699. }
  700. }
  701. }
  702. return ret;
  703. };
  704. };
  705. var deepMerge = baseMerge(deep);
  706. var merge = baseMerge(shallow);
  707. var cached = function (f) {
  708. var called = false;
  709. var r;
  710. return function () {
  711. var args = [];
  712. for (var _i = 0; _i < arguments.length; _i++) {
  713. args[_i] = arguments[_i];
  714. }
  715. if (!called) {
  716. called = true;
  717. r = f.apply(null, args);
  718. }
  719. return r;
  720. };
  721. };
  722. var SimpleResultType;
  723. (function (SimpleResultType) {
  724. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  725. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  726. }(SimpleResultType || (SimpleResultType = {})));
  727. var fold = function (res, onError, onValue) {
  728. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  729. };
  730. var partition$1 = function (results) {
  731. var values = [];
  732. var errors = [];
  733. each(results, function (obj) {
  734. fold(obj, function (err) {
  735. return errors.push(err);
  736. }, function (val) {
  737. return values.push(val);
  738. });
  739. });
  740. return {
  741. values: values,
  742. errors: errors
  743. };
  744. };
  745. var mapError = function (res, f) {
  746. if (res.stype === SimpleResultType.Error) {
  747. return {
  748. stype: SimpleResultType.Error,
  749. serror: f(res.serror)
  750. };
  751. } else {
  752. return res;
  753. }
  754. };
  755. var map$2 = function (res, f) {
  756. if (res.stype === SimpleResultType.Value) {
  757. return {
  758. stype: SimpleResultType.Value,
  759. svalue: f(res.svalue)
  760. };
  761. } else {
  762. return res;
  763. }
  764. };
  765. var bind$1 = function (res, f) {
  766. if (res.stype === SimpleResultType.Value) {
  767. return f(res.svalue);
  768. } else {
  769. return res;
  770. }
  771. };
  772. var bindError = function (res, f) {
  773. if (res.stype === SimpleResultType.Error) {
  774. return f(res.serror);
  775. } else {
  776. return res;
  777. }
  778. };
  779. var svalue = function (v) {
  780. return {
  781. stype: SimpleResultType.Value,
  782. svalue: v
  783. };
  784. };
  785. var serror = function (e) {
  786. return {
  787. stype: SimpleResultType.Error,
  788. serror: e
  789. };
  790. };
  791. var toResult = function (res) {
  792. return fold(res, Result.error, Result.value);
  793. };
  794. var fromResult = function (res) {
  795. return res.fold(serror, svalue);
  796. };
  797. var SimpleResult = {
  798. fromResult: fromResult,
  799. toResult: toResult,
  800. svalue: svalue,
  801. partition: partition$1,
  802. serror: serror,
  803. bind: bind$1,
  804. bindError: bindError,
  805. map: map$2,
  806. mapError: mapError,
  807. fold: fold
  808. };
  809. var adt = Adt.generate([
  810. { strict: [] },
  811. { defaultedThunk: ['fallbackThunk'] },
  812. { asOption: [] },
  813. { asDefaultedOptionThunk: ['fallbackThunk'] },
  814. { mergeWithThunk: ['baseThunk'] }
  815. ]);
  816. var defaulted = function (fallback) {
  817. return adt.defaultedThunk(constant(fallback));
  818. };
  819. var mergeWith = function (base) {
  820. return adt.mergeWithThunk(constant(base));
  821. };
  822. var strict = adt.strict;
  823. var asOption = adt.asOption;
  824. var defaultedThunk = adt.defaultedThunk;
  825. var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
  826. var mergeWithThunk = adt.mergeWithThunk;
  827. var exclude = function (obj, fields) {
  828. var r = {};
  829. each$1(obj, function (v, k) {
  830. if (!contains(fields, k)) {
  831. r[k] = v;
  832. }
  833. });
  834. return r;
  835. };
  836. var wrap = function (key, value) {
  837. var _a;
  838. return _a = {}, _a[key] = value, _a;
  839. };
  840. var wrapAll = function (keyvalues) {
  841. var r = {};
  842. each(keyvalues, function (kv) {
  843. r[kv.key] = kv.value;
  844. });
  845. return r;
  846. };
  847. var comparison = Adt.generate([
  848. {
  849. bothErrors: [
  850. 'error1',
  851. 'error2'
  852. ]
  853. },
  854. {
  855. firstError: [
  856. 'error1',
  857. 'value2'
  858. ]
  859. },
  860. {
  861. secondError: [
  862. 'value1',
  863. 'error2'
  864. ]
  865. },
  866. {
  867. bothValues: [
  868. 'value1',
  869. 'value2'
  870. ]
  871. }
  872. ]);
  873. var partition$2 = function (results) {
  874. var errors = [];
  875. var values = [];
  876. each(results, function (result) {
  877. result.fold(function (err) {
  878. errors.push(err);
  879. }, function (value) {
  880. values.push(value);
  881. });
  882. });
  883. return {
  884. errors: errors,
  885. values: values
  886. };
  887. };
  888. var exclude$1 = function (obj, fields) {
  889. return exclude(obj, fields);
  890. };
  891. var wrap$1 = function (key, value) {
  892. return wrap(key, value);
  893. };
  894. var wrapAll$1 = function (keyvalues) {
  895. return wrapAll(keyvalues);
  896. };
  897. var mergeValues = function (values, base) {
  898. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge.apply(undefined, values)));
  899. };
  900. var mergeErrors = function (errors) {
  901. return Result.error(flatten(errors));
  902. };
  903. var consolidate = function (objs, base) {
  904. var partitions = partition$2(objs);
  905. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  906. };
  907. var mergeValues$1 = function (values, base) {
  908. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge.apply(undefined, values))) : SimpleResult.svalue(base);
  909. };
  910. var mergeErrors$1 = function (errors) {
  911. return compose(SimpleResult.serror, flatten)(errors);
  912. };
  913. var consolidateObj = function (objects, base) {
  914. var partition = SimpleResult.partition(objects);
  915. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  916. };
  917. var consolidateArr = function (objects) {
  918. var partitions = SimpleResult.partition(objects);
  919. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  920. };
  921. var ResultCombine = {
  922. consolidateObj: consolidateObj,
  923. consolidateArr: consolidateArr
  924. };
  925. var formatObj = function (input) {
  926. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  927. };
  928. var formatErrors = function (errors) {
  929. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  930. path: [],
  931. getErrorInfo: function () {
  932. return '... (only showing first ten failures)';
  933. }
  934. }]) : errors;
  935. return map(es, function (e) {
  936. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  937. });
  938. };
  939. var nu = function (path, getErrorInfo) {
  940. return SimpleResult.serror([{
  941. path: path,
  942. getErrorInfo: getErrorInfo
  943. }]);
  944. };
  945. var missingStrict = function (path, key, obj) {
  946. return nu(path, function () {
  947. return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
  948. });
  949. };
  950. var missingKey = function (path, key) {
  951. return nu(path, function () {
  952. return 'Choice schema did not contain choice key: "' + key + '"';
  953. });
  954. };
  955. var missingBranch = function (path, branches, branch) {
  956. return nu(path, function () {
  957. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  958. });
  959. };
  960. var unsupportedFields = function (path, unsupported) {
  961. return nu(path, function () {
  962. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  963. });
  964. };
  965. var custom = function (path, err) {
  966. return nu(path, function () {
  967. return err;
  968. });
  969. };
  970. var adt$1 = Adt.generate([
  971. {
  972. field: [
  973. 'key',
  974. 'okey',
  975. 'presence',
  976. 'prop'
  977. ]
  978. },
  979. {
  980. state: [
  981. 'okey',
  982. 'instantiator'
  983. ]
  984. }
  985. ]);
  986. var strictAccess = function (path, obj, key) {
  987. return get(obj, key).fold(function () {
  988. return missingStrict(path, key, obj);
  989. }, SimpleResult.svalue);
  990. };
  991. var fallbackAccess = function (obj, key, fallbackThunk) {
  992. var v = get(obj, key).fold(function () {
  993. return fallbackThunk(obj);
  994. }, identity);
  995. return SimpleResult.svalue(v);
  996. };
  997. var optionAccess = function (obj, key) {
  998. return SimpleResult.svalue(get(obj, key));
  999. };
  1000. var optionDefaultedAccess = function (obj, key, fallback) {
  1001. var opt = get(obj, key).map(function (val) {
  1002. return val === true ? fallback(obj) : val;
  1003. });
  1004. return SimpleResult.svalue(opt);
  1005. };
  1006. var cExtractOne = function (path, obj, field, strength) {
  1007. return field.fold(function (key, okey, presence, prop) {
  1008. var bundle = function (av) {
  1009. var result = prop.extract(path.concat([key]), strength, av);
  1010. return SimpleResult.map(result, function (res) {
  1011. return wrap(okey, strength(res));
  1012. });
  1013. };
  1014. var bundleAsOption = function (optValue) {
  1015. return optValue.fold(function () {
  1016. var outcome = wrap(okey, strength(Option.none()));
  1017. return SimpleResult.svalue(outcome);
  1018. }, function (ov) {
  1019. var result = prop.extract(path.concat([key]), strength, ov);
  1020. return SimpleResult.map(result, function (res) {
  1021. return wrap(okey, strength(Option.some(res)));
  1022. });
  1023. });
  1024. };
  1025. return function () {
  1026. return presence.fold(function () {
  1027. return SimpleResult.bind(strictAccess(path, obj, key), bundle);
  1028. }, function (fallbackThunk) {
  1029. return SimpleResult.bind(fallbackAccess(obj, key, fallbackThunk), bundle);
  1030. }, function () {
  1031. return SimpleResult.bind(optionAccess(obj, key), bundleAsOption);
  1032. }, function (fallbackThunk) {
  1033. return SimpleResult.bind(optionDefaultedAccess(obj, key, fallbackThunk), bundleAsOption);
  1034. }, function (baseThunk) {
  1035. var base = baseThunk(obj);
  1036. var result = SimpleResult.map(fallbackAccess(obj, key, constant({})), function (v) {
  1037. return deepMerge(base, v);
  1038. });
  1039. return SimpleResult.bind(result, bundle);
  1040. });
  1041. }();
  1042. }, function (okey, instantiator) {
  1043. var state = instantiator(obj);
  1044. return SimpleResult.svalue(wrap(okey, strength(state)));
  1045. });
  1046. };
  1047. var cExtract = function (path, obj, fields, strength) {
  1048. var results = map(fields, function (field) {
  1049. return cExtractOne(path, obj, field, strength);
  1050. });
  1051. return ResultCombine.consolidateObj(results, {});
  1052. };
  1053. var valueThunk = function (getDelegate) {
  1054. var extract = function (path, strength, val) {
  1055. return getDelegate().extract(path, strength, val);
  1056. };
  1057. var toString = function () {
  1058. return getDelegate().toString();
  1059. };
  1060. return {
  1061. extract: extract,
  1062. toString: toString
  1063. };
  1064. };
  1065. var value$1 = function (validator) {
  1066. var extract = function (path, strength, val) {
  1067. return SimpleResult.bindError(validator(val, strength), function (err) {
  1068. return custom(path, err);
  1069. });
  1070. };
  1071. var toString = function () {
  1072. return 'val';
  1073. };
  1074. return {
  1075. extract: extract,
  1076. toString: toString
  1077. };
  1078. };
  1079. var getSetKeys = function (obj) {
  1080. return keys(filter$1(obj, function (value) {
  1081. return value !== undefined && value !== null;
  1082. }));
  1083. };
  1084. var objOfOnly = function (fields) {
  1085. var delegate = objOf(fields);
  1086. var fieldNames = foldr(fields, function (acc, f) {
  1087. return f.fold(function (key) {
  1088. return deepMerge(acc, wrap$1(key, true));
  1089. }, constant(acc));
  1090. }, {});
  1091. var extract = function (path, strength, o) {
  1092. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1093. var extra = filter(keys, function (k) {
  1094. return !hasNonNullableKey(fieldNames, k);
  1095. });
  1096. return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
  1097. };
  1098. return {
  1099. extract: extract,
  1100. toString: delegate.toString
  1101. };
  1102. };
  1103. var objOf = function (fields) {
  1104. var extract = function (path, strength, o) {
  1105. return cExtract(path, o, fields, strength);
  1106. };
  1107. var toString = function () {
  1108. var fieldStrings = map(fields, function (field) {
  1109. return field.fold(function (key, okey, presence, prop) {
  1110. return key + ' -> ' + prop.toString();
  1111. }, function (okey, _instantiator) {
  1112. return 'state(' + okey + ')';
  1113. });
  1114. });
  1115. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1116. };
  1117. return {
  1118. extract: extract,
  1119. toString: toString
  1120. };
  1121. };
  1122. var arrOf = function (prop) {
  1123. var extract = function (path, strength, array) {
  1124. var results = map(array, function (a, i) {
  1125. return prop.extract(path.concat(['[' + i + ']']), strength, a);
  1126. });
  1127. return ResultCombine.consolidateArr(results);
  1128. };
  1129. var toString = function () {
  1130. return 'array(' + prop.toString() + ')';
  1131. };
  1132. return {
  1133. extract: extract,
  1134. toString: toString
  1135. };
  1136. };
  1137. var oneOf = function (props) {
  1138. var extract = function (path, strength, val) {
  1139. var errors = [];
  1140. for (var _i = 0, props_1 = props; _i < props_1.length; _i++) {
  1141. var prop = props_1[_i];
  1142. var res = prop.extract(path, strength, val);
  1143. if (res.stype === SimpleResultType.Value) {
  1144. return res;
  1145. }
  1146. errors.push(res);
  1147. }
  1148. return ResultCombine.consolidateArr(errors);
  1149. };
  1150. var toString = function () {
  1151. return 'oneOf(' + map(props, function (prop) {
  1152. return prop.toString();
  1153. }).join(', ') + ')';
  1154. };
  1155. return {
  1156. extract: extract,
  1157. toString: toString
  1158. };
  1159. };
  1160. var setOf = function (validator, prop) {
  1161. var validateKeys = function (path, keys) {
  1162. return arrOf(value$1(validator)).extract(path, identity, keys);
  1163. };
  1164. var extract = function (path, strength, o) {
  1165. var keys$1 = keys(o);
  1166. var validatedKeys = validateKeys(path, keys$1);
  1167. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1168. var schema = map(validKeys, function (vk) {
  1169. return adt$1.field(vk, vk, strict(), prop);
  1170. });
  1171. return objOf(schema).extract(path, strength, o);
  1172. });
  1173. };
  1174. var toString = function () {
  1175. return 'setOf(' + prop.toString() + ')';
  1176. };
  1177. return {
  1178. extract: extract,
  1179. toString: toString
  1180. };
  1181. };
  1182. var anyValue = constant(value$1(SimpleResult.svalue));
  1183. var arrOfObj = compose(arrOf, objOf);
  1184. var state = adt$1.state;
  1185. var field = adt$1.field;
  1186. var chooseFrom = function (path, strength, input, branches, ch) {
  1187. var fields = get(branches, ch);
  1188. return fields.fold(function () {
  1189. return missingBranch(path, branches, ch);
  1190. }, function (vp) {
  1191. return vp.extract(path.concat(['branch: ' + ch]), strength, input);
  1192. });
  1193. };
  1194. var choose = function (key, branches) {
  1195. var extract = function (path, strength, input) {
  1196. var choice = get(input, key);
  1197. return choice.fold(function () {
  1198. return missingKey(path, key);
  1199. }, function (chosen) {
  1200. return chooseFrom(path, strength, input, branches, chosen);
  1201. });
  1202. };
  1203. var toString = function () {
  1204. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1205. };
  1206. return {
  1207. extract: extract,
  1208. toString: toString
  1209. };
  1210. };
  1211. var _anyValue = value$1(SimpleResult.svalue);
  1212. var arrOfObj$1 = function (objFields) {
  1213. return arrOfObj(objFields);
  1214. };
  1215. var arrOfVal = function () {
  1216. return arrOf(_anyValue);
  1217. };
  1218. var valueThunkOf = valueThunk;
  1219. var valueOf = function (validator) {
  1220. return value$1(function (v) {
  1221. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1222. });
  1223. };
  1224. var setOf$1 = function (validator, prop) {
  1225. return setOf(function (v) {
  1226. return SimpleResult.fromResult(validator(v));
  1227. }, prop);
  1228. };
  1229. var extract = function (label, prop, strength, obj) {
  1230. var res = prop.extract([label], strength, obj);
  1231. return SimpleResult.mapError(res, function (errs) {
  1232. return {
  1233. input: obj,
  1234. errors: errs
  1235. };
  1236. });
  1237. };
  1238. var asRaw = function (label, prop, obj) {
  1239. return SimpleResult.toResult(extract(label, prop, identity, obj));
  1240. };
  1241. var getOrDie = function (extraction) {
  1242. return extraction.fold(function (errInfo) {
  1243. throw new Error(formatError(errInfo));
  1244. }, identity);
  1245. };
  1246. var asRawOrDie = function (label, prop, obj) {
  1247. return getOrDie(asRaw(label, prop, obj));
  1248. };
  1249. var formatError = function (errInfo) {
  1250. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1251. };
  1252. var chooseProcessor = function (key, branches) {
  1253. return choose(key, branches);
  1254. };
  1255. var choose$1 = function (key, branches) {
  1256. return choose(key, map$1(branches, objOf));
  1257. };
  1258. var anyValue$1 = constant(_anyValue);
  1259. var typedValue = function (validator, expectedType) {
  1260. return value$1(function (a) {
  1261. var actualType = typeof a;
  1262. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1263. });
  1264. };
  1265. var number = typedValue(isNumber, 'number');
  1266. var string = typedValue(isString, 'string');
  1267. var boolean = typedValue(isBoolean, 'boolean');
  1268. var functionProcessor = typedValue(isFunction, 'function');
  1269. var isPostMessageable = function (val) {
  1270. var every = function (iter, callbackFn) {
  1271. var result = iter.next();
  1272. while (!result.done) {
  1273. if (!callbackFn(result.value)) {
  1274. return false;
  1275. }
  1276. result = iter.next();
  1277. }
  1278. return true;
  1279. };
  1280. if (Object(val) !== val) {
  1281. return true;
  1282. }
  1283. switch ({}.toString.call(val).slice(8, -1)) {
  1284. case 'Boolean':
  1285. case 'Number':
  1286. case 'String':
  1287. case 'Date':
  1288. case 'RegExp':
  1289. case 'Blob':
  1290. case 'FileList':
  1291. case 'ImageData':
  1292. case 'ImageBitmap':
  1293. case 'ArrayBuffer':
  1294. return true;
  1295. case 'Array':
  1296. case 'Object':
  1297. return Object.keys(val).every(function (prop) {
  1298. return isPostMessageable(val[prop]);
  1299. });
  1300. case 'Map':
  1301. return every(val.keys(), isPostMessageable) && every(val.values(), isPostMessageable);
  1302. case 'Set':
  1303. return every(val.keys(), isPostMessageable);
  1304. default:
  1305. return false;
  1306. }
  1307. };
  1308. var postMessageable = value$1(function (a) {
  1309. return isPostMessageable(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected value to be acceptable for sending via postMessage');
  1310. });
  1311. var validateEnum = function (values) {
  1312. return valueOf(function (value) {
  1313. return contains(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".');
  1314. });
  1315. };
  1316. var strict$1 = function (key) {
  1317. return field(key, key, strict(), anyValue());
  1318. };
  1319. var strictOf = function (key, schema) {
  1320. return field(key, key, strict(), schema);
  1321. };
  1322. var strictNumber = function (key) {
  1323. return strictOf(key, number);
  1324. };
  1325. var strictString = function (key) {
  1326. return strictOf(key, string);
  1327. };
  1328. var strictStringEnum = function (key, values) {
  1329. return field(key, key, strict(), validateEnum(values));
  1330. };
  1331. var strictBoolean = function (key) {
  1332. return strictOf(key, boolean);
  1333. };
  1334. var strictFunction = function (key) {
  1335. return strictOf(key, functionProcessor);
  1336. };
  1337. var forbid = function (key, message) {
  1338. return field(key, key, asOption(), value$1(function (_v) {
  1339. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1340. }));
  1341. };
  1342. var strictObjOf = function (key, objSchema) {
  1343. return field(key, key, strict(), objOf(objSchema));
  1344. };
  1345. var strictArrayOfObj = function (key, objFields) {
  1346. return field(key, key, strict(), arrOfObj(objFields));
  1347. };
  1348. var strictArrayOf = function (key, schema) {
  1349. return field(key, key, strict(), arrOf(schema));
  1350. };
  1351. var option = function (key) {
  1352. return field(key, key, asOption(), anyValue());
  1353. };
  1354. var optionOf = function (key, schema) {
  1355. return field(key, key, asOption(), schema);
  1356. };
  1357. var optionNumber = function (key) {
  1358. return optionOf(key, number);
  1359. };
  1360. var optionString = function (key) {
  1361. return optionOf(key, string);
  1362. };
  1363. var optionFunction = function (key) {
  1364. return optionOf(key, functionProcessor);
  1365. };
  1366. var optionArrayOf = function (key, schema) {
  1367. return optionOf(key, arrOf(schema));
  1368. };
  1369. var optionObjOf = function (key, objSchema) {
  1370. return optionOf(key, objOf(objSchema));
  1371. };
  1372. var optionObjOfOnly = function (key, objSchema) {
  1373. return optionOf(key, objOfOnly(objSchema));
  1374. };
  1375. var defaulted$1 = function (key, fallback) {
  1376. return field(key, key, defaulted(fallback), anyValue());
  1377. };
  1378. var defaultedOf = function (key, fallback, schema) {
  1379. return field(key, key, defaulted(fallback), schema);
  1380. };
  1381. var defaultedNumber = function (key, fallback) {
  1382. return defaultedOf(key, fallback, number);
  1383. };
  1384. var defaultedString = function (key, fallback) {
  1385. return defaultedOf(key, fallback, string);
  1386. };
  1387. var defaultedStringEnum = function (key, fallback, values) {
  1388. return defaultedOf(key, fallback, validateEnum(values));
  1389. };
  1390. var defaultedBoolean = function (key, fallback) {
  1391. return defaultedOf(key, fallback, boolean);
  1392. };
  1393. var defaultedFunction = function (key, fallback) {
  1394. return defaultedOf(key, fallback, functionProcessor);
  1395. };
  1396. var defaultedPostMsg = function (key, fallback) {
  1397. return defaultedOf(key, fallback, postMessageable);
  1398. };
  1399. var defaultedArrayOf = function (key, fallback, schema) {
  1400. return defaultedOf(key, fallback, arrOf(schema));
  1401. };
  1402. var defaultedObjOf = function (key, fallback, objSchema) {
  1403. return defaultedOf(key, fallback, objOf(objSchema));
  1404. };
  1405. var state$1 = function (okey, instantiator) {
  1406. return state(okey, instantiator);
  1407. };
  1408. var Cell = function (initial) {
  1409. var value = initial;
  1410. var get = function () {
  1411. return value;
  1412. };
  1413. var set = function (v) {
  1414. value = v;
  1415. };
  1416. return {
  1417. get: get,
  1418. set: set
  1419. };
  1420. };
  1421. var fromHtml = function (html, scope) {
  1422. var doc = scope || domGlobals.document;
  1423. var div = doc.createElement('div');
  1424. div.innerHTML = html;
  1425. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  1426. domGlobals.console.error('HTML does not have a single root node', html);
  1427. throw new Error('HTML must have a single root node');
  1428. }
  1429. return fromDom(div.childNodes[0]);
  1430. };
  1431. var fromTag = function (tag, scope) {
  1432. var doc = scope || domGlobals.document;
  1433. var node = doc.createElement(tag);
  1434. return fromDom(node);
  1435. };
  1436. var fromText = function (text, scope) {
  1437. var doc = scope || domGlobals.document;
  1438. var node = doc.createTextNode(text);
  1439. return fromDom(node);
  1440. };
  1441. var fromDom = function (node) {
  1442. if (node === null || node === undefined) {
  1443. throw new Error('Node cannot be null or undefined');
  1444. }
  1445. return { dom: constant(node) };
  1446. };
  1447. var fromPoint = function (docElm, x, y) {
  1448. var doc = docElm.dom();
  1449. return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
  1450. };
  1451. var Element = {
  1452. fromHtml: fromHtml,
  1453. fromTag: fromTag,
  1454. fromText: fromText,
  1455. fromDom: fromDom,
  1456. fromPoint: fromPoint
  1457. };
  1458. var compareDocumentPosition = function (a, b, match) {
  1459. return (a.compareDocumentPosition(b) & match) !== 0;
  1460. };
  1461. var documentPositionContainedBy = function (a, b) {
  1462. return compareDocumentPosition(a, b, domGlobals.Node.DOCUMENT_POSITION_CONTAINED_BY);
  1463. };
  1464. var firstMatch = function (regexes, s) {
  1465. for (var i = 0; i < regexes.length; i++) {
  1466. var x = regexes[i];
  1467. if (x.test(s)) {
  1468. return x;
  1469. }
  1470. }
  1471. return undefined;
  1472. };
  1473. var find$2 = function (regexes, agent) {
  1474. var r = firstMatch(regexes, agent);
  1475. if (!r) {
  1476. return {
  1477. major: 0,
  1478. minor: 0
  1479. };
  1480. }
  1481. var group = function (i) {
  1482. return Number(agent.replace(r, '$' + i));
  1483. };
  1484. return nu$1(group(1), group(2));
  1485. };
  1486. var detect = function (versionRegexes, agent) {
  1487. var cleanedAgent = String(agent).toLowerCase();
  1488. if (versionRegexes.length === 0) {
  1489. return unknown();
  1490. }
  1491. return find$2(versionRegexes, cleanedAgent);
  1492. };
  1493. var unknown = function () {
  1494. return nu$1(0, 0);
  1495. };
  1496. var nu$1 = function (major, minor) {
  1497. return {
  1498. major: major,
  1499. minor: minor
  1500. };
  1501. };
  1502. var Version = {
  1503. nu: nu$1,
  1504. detect: detect,
  1505. unknown: unknown
  1506. };
  1507. var edge = 'Edge';
  1508. var chrome = 'Chrome';
  1509. var ie = 'IE';
  1510. var opera = 'Opera';
  1511. var firefox = 'Firefox';
  1512. var safari = 'Safari';
  1513. var unknown$1 = function () {
  1514. return nu$2({
  1515. current: undefined,
  1516. version: Version.unknown()
  1517. });
  1518. };
  1519. var nu$2 = function (info) {
  1520. var current = info.current;
  1521. var version = info.version;
  1522. var isBrowser = function (name) {
  1523. return function () {
  1524. return current === name;
  1525. };
  1526. };
  1527. return {
  1528. current: current,
  1529. version: version,
  1530. isEdge: isBrowser(edge),
  1531. isChrome: isBrowser(chrome),
  1532. isIE: isBrowser(ie),
  1533. isOpera: isBrowser(opera),
  1534. isFirefox: isBrowser(firefox),
  1535. isSafari: isBrowser(safari)
  1536. };
  1537. };
  1538. var Browser = {
  1539. unknown: unknown$1,
  1540. nu: nu$2,
  1541. edge: constant(edge),
  1542. chrome: constant(chrome),
  1543. ie: constant(ie),
  1544. opera: constant(opera),
  1545. firefox: constant(firefox),
  1546. safari: constant(safari)
  1547. };
  1548. var windows = 'Windows';
  1549. var ios = 'iOS';
  1550. var android = 'Android';
  1551. var linux = 'Linux';
  1552. var osx = 'OSX';
  1553. var solaris = 'Solaris';
  1554. var freebsd = 'FreeBSD';
  1555. var chromeos = 'ChromeOS';
  1556. var unknown$2 = function () {
  1557. return nu$3({
  1558. current: undefined,
  1559. version: Version.unknown()
  1560. });
  1561. };
  1562. var nu$3 = function (info) {
  1563. var current = info.current;
  1564. var version = info.version;
  1565. var isOS = function (name) {
  1566. return function () {
  1567. return current === name;
  1568. };
  1569. };
  1570. return {
  1571. current: current,
  1572. version: version,
  1573. isWindows: isOS(windows),
  1574. isiOS: isOS(ios),
  1575. isAndroid: isOS(android),
  1576. isOSX: isOS(osx),
  1577. isLinux: isOS(linux),
  1578. isSolaris: isOS(solaris),
  1579. isFreeBSD: isOS(freebsd),
  1580. isChromeOS: isOS(chromeos)
  1581. };
  1582. };
  1583. var OperatingSystem = {
  1584. unknown: unknown$2,
  1585. nu: nu$3,
  1586. windows: constant(windows),
  1587. ios: constant(ios),
  1588. android: constant(android),
  1589. linux: constant(linux),
  1590. osx: constant(osx),
  1591. solaris: constant(solaris),
  1592. freebsd: constant(freebsd),
  1593. chromeos: constant(chromeos)
  1594. };
  1595. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  1596. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  1597. var isiPhone = os.isiOS() && !isiPad;
  1598. var isMobile = os.isiOS() || os.isAndroid();
  1599. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  1600. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  1601. var isPhone = isiPhone || isMobile && !isTablet;
  1602. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  1603. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  1604. return {
  1605. isiPad: constant(isiPad),
  1606. isiPhone: constant(isiPhone),
  1607. isTablet: constant(isTablet),
  1608. isPhone: constant(isPhone),
  1609. isTouch: constant(isTouch),
  1610. isAndroid: os.isAndroid,
  1611. isiOS: os.isiOS,
  1612. isWebView: constant(iOSwebview),
  1613. isDesktop: constant(isDesktop)
  1614. };
  1615. };
  1616. var detect$1 = function (candidates, userAgent) {
  1617. var agent = String(userAgent).toLowerCase();
  1618. return find(candidates, function (candidate) {
  1619. return candidate.search(agent);
  1620. });
  1621. };
  1622. var detectBrowser = function (browsers, userAgent) {
  1623. return detect$1(browsers, userAgent).map(function (browser) {
  1624. var version = Version.detect(browser.versionRegexes, userAgent);
  1625. return {
  1626. current: browser.name,
  1627. version: version
  1628. };
  1629. });
  1630. };
  1631. var detectOs = function (oses, userAgent) {
  1632. return detect$1(oses, userAgent).map(function (os) {
  1633. var version = Version.detect(os.versionRegexes, userAgent);
  1634. return {
  1635. current: os.name,
  1636. version: version
  1637. };
  1638. });
  1639. };
  1640. var UaString = {
  1641. detectBrowser: detectBrowser,
  1642. detectOs: detectOs
  1643. };
  1644. var checkRange = function (str, substr, start) {
  1645. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  1646. };
  1647. var contains$1 = function (str, substr) {
  1648. return str.indexOf(substr) !== -1;
  1649. };
  1650. var endsWith = function (str, suffix) {
  1651. return checkRange(str, suffix, str.length - suffix.length);
  1652. };
  1653. var blank = function (r) {
  1654. return function (s) {
  1655. return s.replace(r, '');
  1656. };
  1657. };
  1658. var trim = blank(/^\s+|\s+$/g);
  1659. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  1660. var checkContains = function (target) {
  1661. return function (uastring) {
  1662. return contains$1(uastring, target);
  1663. };
  1664. };
  1665. var browsers = [
  1666. {
  1667. name: 'Edge',
  1668. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  1669. search: function (uastring) {
  1670. return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
  1671. }
  1672. },
  1673. {
  1674. name: 'Chrome',
  1675. versionRegexes: [
  1676. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  1677. normalVersionRegex
  1678. ],
  1679. search: function (uastring) {
  1680. return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
  1681. }
  1682. },
  1683. {
  1684. name: 'IE',
  1685. versionRegexes: [
  1686. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  1687. /.*?rv:([0-9]+)\.([0-9]+).*/
  1688. ],
  1689. search: function (uastring) {
  1690. return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
  1691. }
  1692. },
  1693. {
  1694. name: 'Opera',
  1695. versionRegexes: [
  1696. normalVersionRegex,
  1697. /.*?opera\/([0-9]+)\.([0-9]+).*/
  1698. ],
  1699. search: checkContains('opera')
  1700. },
  1701. {
  1702. name: 'Firefox',
  1703. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  1704. search: checkContains('firefox')
  1705. },
  1706. {
  1707. name: 'Safari',
  1708. versionRegexes: [
  1709. normalVersionRegex,
  1710. /.*?cpu os ([0-9]+)_([0-9]+).*/
  1711. ],
  1712. search: function (uastring) {
  1713. return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
  1714. }
  1715. }
  1716. ];
  1717. var oses = [
  1718. {
  1719. name: 'Windows',
  1720. search: checkContains('win'),
  1721. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  1722. },
  1723. {
  1724. name: 'iOS',
  1725. search: function (uastring) {
  1726. return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
  1727. },
  1728. versionRegexes: [
  1729. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  1730. /.*cpu os ([0-9]+)_([0-9]+).*/,
  1731. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  1732. ]
  1733. },
  1734. {
  1735. name: 'Android',
  1736. search: checkContains('android'),
  1737. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  1738. },
  1739. {
  1740. name: 'OSX',
  1741. search: checkContains('mac os x'),
  1742. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  1743. },
  1744. {
  1745. name: 'Linux',
  1746. search: checkContains('linux'),
  1747. versionRegexes: []
  1748. },
  1749. {
  1750. name: 'Solaris',
  1751. search: checkContains('sunos'),
  1752. versionRegexes: []
  1753. },
  1754. {
  1755. name: 'FreeBSD',
  1756. search: checkContains('freebsd'),
  1757. versionRegexes: []
  1758. },
  1759. {
  1760. name: 'ChromeOS',
  1761. search: checkContains('cros'),
  1762. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  1763. }
  1764. ];
  1765. var PlatformInfo = {
  1766. browsers: constant(browsers),
  1767. oses: constant(oses)
  1768. };
  1769. var detect$2 = function (userAgent, mediaMatch) {
  1770. var browsers = PlatformInfo.browsers();
  1771. var oses = PlatformInfo.oses();
  1772. var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
  1773. var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  1774. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  1775. return {
  1776. browser: browser,
  1777. os: os,
  1778. deviceType: deviceType
  1779. };
  1780. };
  1781. var PlatformDetection = { detect: detect$2 };
  1782. var mediaMatch = function (query) {
  1783. return domGlobals.window.matchMedia(query).matches;
  1784. };
  1785. var platform = cached(function () {
  1786. return PlatformDetection.detect(domGlobals.navigator.userAgent, mediaMatch);
  1787. });
  1788. var detect$3 = function () {
  1789. return platform();
  1790. };
  1791. var DOCUMENT = 9;
  1792. var ELEMENT = 1;
  1793. var TEXT = 3;
  1794. var ELEMENT$1 = ELEMENT;
  1795. var DOCUMENT$1 = DOCUMENT;
  1796. var is = function (element, selector) {
  1797. var dom = element.dom();
  1798. if (dom.nodeType !== ELEMENT$1) {
  1799. return false;
  1800. } else {
  1801. var elem = dom;
  1802. if (elem.matches !== undefined) {
  1803. return elem.matches(selector);
  1804. } else if (elem.msMatchesSelector !== undefined) {
  1805. return elem.msMatchesSelector(selector);
  1806. } else if (elem.webkitMatchesSelector !== undefined) {
  1807. return elem.webkitMatchesSelector(selector);
  1808. } else if (elem.mozMatchesSelector !== undefined) {
  1809. return elem.mozMatchesSelector(selector);
  1810. } else {
  1811. throw new Error('Browser lacks native selectors');
  1812. }
  1813. }
  1814. };
  1815. var bypassSelector = function (dom) {
  1816. return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
  1817. };
  1818. var all = function (selector, scope) {
  1819. var base = scope === undefined ? domGlobals.document : scope.dom();
  1820. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), Element.fromDom);
  1821. };
  1822. var one = function (selector, scope) {
  1823. var base = scope === undefined ? domGlobals.document : scope.dom();
  1824. return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element.fromDom);
  1825. };
  1826. var eq$1 = function (e1, e2) {
  1827. return e1.dom() === e2.dom();
  1828. };
  1829. var regularContains = function (e1, e2) {
  1830. var d1 = e1.dom();
  1831. var d2 = e2.dom();
  1832. return d1 === d2 ? false : d1.contains(d2);
  1833. };
  1834. var ieContains = function (e1, e2) {
  1835. return documentPositionContainedBy(e1.dom(), e2.dom());
  1836. };
  1837. var contains$2 = function (e1, e2) {
  1838. return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2);
  1839. };
  1840. var ensureIsRoot = function (isRoot) {
  1841. return isFunction(isRoot) ? isRoot : constant(false);
  1842. };
  1843. var ancestor = function (scope, transform, isRoot) {
  1844. var element = scope.dom();
  1845. var stop = ensureIsRoot(isRoot);
  1846. while (element.parentNode) {
  1847. element = element.parentNode;
  1848. var el = Element.fromDom(element);
  1849. var transformed = transform(el);
  1850. if (transformed.isSome()) {
  1851. return transformed;
  1852. } else if (stop(el)) {
  1853. break;
  1854. }
  1855. }
  1856. return Option.none();
  1857. };
  1858. var closest = function (scope, transform, isRoot) {
  1859. var current = transform(scope);
  1860. var stop = ensureIsRoot(isRoot);
  1861. return current.orThunk(function () {
  1862. return stop(scope) ? Option.none() : ancestor(scope, transform, stop);
  1863. });
  1864. };
  1865. var isSource = function (component, simulatedEvent) {
  1866. return eq$1(component.element(), simulatedEvent.event().target());
  1867. };
  1868. var nu$4 = function (parts) {
  1869. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  1870. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  1871. }
  1872. return asRawOrDie('Extracting event.handler', objOfOnly([
  1873. defaulted$1('can', constant(true)),
  1874. defaulted$1('abort', constant(false)),
  1875. defaulted$1('run', noop)
  1876. ]), parts);
  1877. };
  1878. var all$1 = function (handlers, f) {
  1879. return function () {
  1880. var args = [];
  1881. for (var _i = 0; _i < arguments.length; _i++) {
  1882. args[_i] = arguments[_i];
  1883. }
  1884. return foldl(handlers, function (acc, handler) {
  1885. return acc && f(handler).apply(undefined, args);
  1886. }, true);
  1887. };
  1888. };
  1889. var any = function (handlers, f) {
  1890. return function () {
  1891. var args = [];
  1892. for (var _i = 0; _i < arguments.length; _i++) {
  1893. args[_i] = arguments[_i];
  1894. }
  1895. return foldl(handlers, function (acc, handler) {
  1896. return acc || f(handler).apply(undefined, args);
  1897. }, false);
  1898. };
  1899. };
  1900. var read = function (handler) {
  1901. return isFunction(handler) ? {
  1902. can: constant(true),
  1903. abort: constant(false),
  1904. run: handler
  1905. } : handler;
  1906. };
  1907. var fuse = function (handlers) {
  1908. var can = all$1(handlers, function (handler) {
  1909. return handler.can;
  1910. });
  1911. var abort = any(handlers, function (handler) {
  1912. return handler.abort;
  1913. });
  1914. var run = function () {
  1915. var args = [];
  1916. for (var _i = 0; _i < arguments.length; _i++) {
  1917. args[_i] = arguments[_i];
  1918. }
  1919. each(handlers, function (handler) {
  1920. handler.run.apply(undefined, args);
  1921. });
  1922. };
  1923. return nu$4({
  1924. can: can,
  1925. abort: abort,
  1926. run: run
  1927. });
  1928. };
  1929. var touchstart = constant('touchstart');
  1930. var touchmove = constant('touchmove');
  1931. var touchend = constant('touchend');
  1932. var touchcancel = constant('touchcancel');
  1933. var mousedown = constant('mousedown');
  1934. var mousemove = constant('mousemove');
  1935. var mouseout = constant('mouseout');
  1936. var mouseup = constant('mouseup');
  1937. var mouseover = constant('mouseover');
  1938. var focusin = constant('focusin');
  1939. var focusout = constant('focusout');
  1940. var keydown = constant('keydown');
  1941. var keyup = constant('keyup');
  1942. var input = constant('input');
  1943. var change = constant('change');
  1944. var click = constant('click');
  1945. var transitionend = constant('transitionend');
  1946. var selectstart = constant('selectstart');
  1947. var alloy = { tap: constant('alloy.tap') };
  1948. var focus = constant('alloy.focus');
  1949. var postBlur = constant('alloy.blur.post');
  1950. var postPaste = constant('alloy.paste.post');
  1951. var receive = constant('alloy.receive');
  1952. var execute = constant('alloy.execute');
  1953. var focusItem = constant('alloy.focus.item');
  1954. var tap = alloy.tap;
  1955. var longpress = constant('alloy.longpress');
  1956. var sandboxClose = constant('alloy.sandbox.close');
  1957. var typeaheadCancel = constant('alloy.typeahead.cancel');
  1958. var systemInit = constant('alloy.system.init');
  1959. var documentTouchmove = constant('alloy.system.touchmove');
  1960. var documentTouchend = constant('alloy.system.touchend');
  1961. var windowScroll = constant('alloy.system.scroll');
  1962. var windowResize = constant('alloy.system.resize');
  1963. var attachedToDom = constant('alloy.system.attached');
  1964. var detachedFromDom = constant('alloy.system.detached');
  1965. var dismissRequested = constant('alloy.system.dismissRequested');
  1966. var repositionRequested = constant('alloy.system.repositionRequested');
  1967. var focusShifted = constant('alloy.focusmanager.shifted');
  1968. var slotVisibility = constant('alloy.slotcontainer.visibility');
  1969. var changeTab = constant('alloy.change.tab');
  1970. var dismissTab = constant('alloy.dismiss.tab');
  1971. var highlight = constant('alloy.highlight');
  1972. var dehighlight = constant('alloy.dehighlight');
  1973. var emit = function (component, event) {
  1974. dispatchWith(component, component.element(), event, {});
  1975. };
  1976. var emitWith = function (component, event, properties) {
  1977. dispatchWith(component, component.element(), event, properties);
  1978. };
  1979. var emitExecute = function (component) {
  1980. emit(component, execute());
  1981. };
  1982. var dispatch = function (component, target, event) {
  1983. dispatchWith(component, target, event, {});
  1984. };
  1985. var dispatchWith = function (component, target, event, properties) {
  1986. var data = __assign({ target: target }, properties);
  1987. component.getSystem().triggerEvent(event, target, map$1(data, constant));
  1988. };
  1989. var dispatchEvent = function (component, target, event, simulatedEvent) {
  1990. component.getSystem().triggerEvent(event, target, simulatedEvent.event());
  1991. };
  1992. var derive = function (configs) {
  1993. return wrapAll$1(configs);
  1994. };
  1995. var abort = function (name, predicate) {
  1996. return {
  1997. key: name,
  1998. value: nu$4({ abort: predicate })
  1999. };
  2000. };
  2001. var can = function (name, predicate) {
  2002. return {
  2003. key: name,
  2004. value: nu$4({ can: predicate })
  2005. };
  2006. };
  2007. var preventDefault = function (name) {
  2008. return {
  2009. key: name,
  2010. value: nu$4({
  2011. run: function (component, simulatedEvent) {
  2012. simulatedEvent.event().prevent();
  2013. }
  2014. })
  2015. };
  2016. };
  2017. var run = function (name, handler) {
  2018. return {
  2019. key: name,
  2020. value: nu$4({ run: handler })
  2021. };
  2022. };
  2023. var runActionExtra = function (name, action, extra) {
  2024. return {
  2025. key: name,
  2026. value: nu$4({
  2027. run: function (component, simulatedEvent) {
  2028. action.apply(undefined, [
  2029. component,
  2030. simulatedEvent
  2031. ].concat(extra));
  2032. }
  2033. })
  2034. };
  2035. };
  2036. var runOnName = function (name) {
  2037. return function (handler) {
  2038. return run(name, handler);
  2039. };
  2040. };
  2041. var runOnSourceName = function (name) {
  2042. return function (handler) {
  2043. return {
  2044. key: name,
  2045. value: nu$4({
  2046. run: function (component, simulatedEvent) {
  2047. if (isSource(component, simulatedEvent)) {
  2048. handler(component, simulatedEvent);
  2049. }
  2050. }
  2051. })
  2052. };
  2053. };
  2054. };
  2055. var redirectToUid = function (name, uid) {
  2056. return run(name, function (component, simulatedEvent) {
  2057. component.getSystem().getByUid(uid).each(function (redirectee) {
  2058. dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
  2059. });
  2060. });
  2061. };
  2062. var redirectToPart = function (name, detail, partName) {
  2063. var uid = detail.partUids[partName];
  2064. return redirectToUid(name, uid);
  2065. };
  2066. var runWithTarget = function (name, f) {
  2067. return run(name, function (component, simulatedEvent) {
  2068. var ev = simulatedEvent.event();
  2069. var target = component.getSystem().getByDom(ev.target()).fold(function () {
  2070. var closest$1 = closest(ev.target(), function (el) {
  2071. return component.getSystem().getByDom(el).toOption();
  2072. }, constant(false));
  2073. return closest$1.getOr(component);
  2074. }, function (c) {
  2075. return c;
  2076. });
  2077. f(component, target, simulatedEvent);
  2078. });
  2079. };
  2080. var cutter = function (name) {
  2081. return run(name, function (component, simulatedEvent) {
  2082. simulatedEvent.cut();
  2083. });
  2084. };
  2085. var stopper = function (name) {
  2086. return run(name, function (component, simulatedEvent) {
  2087. simulatedEvent.stop();
  2088. });
  2089. };
  2090. var runOnSource = function (name, f) {
  2091. return runOnSourceName(name)(f);
  2092. };
  2093. var runOnAttached = runOnSourceName(attachedToDom());
  2094. var runOnDetached = runOnSourceName(detachedFromDom());
  2095. var runOnInit = runOnSourceName(systemInit());
  2096. var runOnExecute = runOnName(execute());
  2097. var owner = function (element) {
  2098. return Element.fromDom(element.dom().ownerDocument);
  2099. };
  2100. var documentElement = function (element) {
  2101. return Element.fromDom(element.dom().ownerDocument.documentElement);
  2102. };
  2103. var defaultView = function (element) {
  2104. return Element.fromDom(element.dom().ownerDocument.defaultView);
  2105. };
  2106. var parent = function (element) {
  2107. return Option.from(element.dom().parentNode).map(Element.fromDom);
  2108. };
  2109. var offsetParent = function (element) {
  2110. return Option.from(element.dom().offsetParent).map(Element.fromDom);
  2111. };
  2112. var nextSibling = function (element) {
  2113. return Option.from(element.dom().nextSibling).map(Element.fromDom);
  2114. };
  2115. var children = function (element) {
  2116. return map(element.dom().childNodes, Element.fromDom);
  2117. };
  2118. var child = function (element, index) {
  2119. var cs = element.dom().childNodes;
  2120. return Option.from(cs[index]).map(Element.fromDom);
  2121. };
  2122. var firstChild = function (element) {
  2123. return child(element, 0);
  2124. };
  2125. var before = function (marker, element) {
  2126. var parent$1 = parent(marker);
  2127. parent$1.each(function (v) {
  2128. v.dom().insertBefore(element.dom(), marker.dom());
  2129. });
  2130. };
  2131. var after = function (marker, element) {
  2132. var sibling = nextSibling(marker);
  2133. sibling.fold(function () {
  2134. var parent$1 = parent(marker);
  2135. parent$1.each(function (v) {
  2136. append(v, element);
  2137. });
  2138. }, function (v) {
  2139. before(v, element);
  2140. });
  2141. };
  2142. var prepend = function (parent, element) {
  2143. var firstChild$1 = firstChild(parent);
  2144. firstChild$1.fold(function () {
  2145. append(parent, element);
  2146. }, function (v) {
  2147. parent.dom().insertBefore(element.dom(), v.dom());
  2148. });
  2149. };
  2150. var append = function (parent, element) {
  2151. parent.dom().appendChild(element.dom());
  2152. };
  2153. var appendAt = function (parent, element, index) {
  2154. child(parent, index).fold(function () {
  2155. append(parent, element);
  2156. }, function (v) {
  2157. before(v, element);
  2158. });
  2159. };
  2160. var before$1 = function (marker, elements) {
  2161. each(elements, function (x) {
  2162. before(marker, x);
  2163. });
  2164. };
  2165. var append$1 = function (parent, elements) {
  2166. each(elements, function (x) {
  2167. append(parent, x);
  2168. });
  2169. };
  2170. var empty = function (element) {
  2171. element.dom().textContent = '';
  2172. each(children(element), function (rogue) {
  2173. remove(rogue);
  2174. });
  2175. };
  2176. var remove = function (element) {
  2177. var dom = element.dom();
  2178. if (dom.parentNode !== null) {
  2179. dom.parentNode.removeChild(dom);
  2180. }
  2181. };
  2182. var unwrap = function (wrapper) {
  2183. var children$1 = children(wrapper);
  2184. if (children$1.length > 0) {
  2185. before$1(wrapper, children$1);
  2186. }
  2187. remove(wrapper);
  2188. };
  2189. var fromHtml$1 = function (html, scope) {
  2190. var doc = scope || domGlobals.document;
  2191. var div = doc.createElement('div');
  2192. div.innerHTML = html;
  2193. return children(Element.fromDom(div));
  2194. };
  2195. var get$1 = function (element) {
  2196. return element.dom().innerHTML;
  2197. };
  2198. var set = function (element, content) {
  2199. var owner$1 = owner(element);
  2200. var docDom = owner$1.dom();
  2201. var fragment = Element.fromDom(docDom.createDocumentFragment());
  2202. var contentElements = fromHtml$1(content, docDom);
  2203. append$1(fragment, contentElements);
  2204. empty(element);
  2205. append(element, fragment);
  2206. };
  2207. var getOuter = function (element) {
  2208. var container = Element.fromTag('div');
  2209. var clone = Element.fromDom(element.dom().cloneNode(true));
  2210. append(container, clone);
  2211. return get$1(container);
  2212. };
  2213. var Global = typeof domGlobals.window !== 'undefined' ? domGlobals.window : Function('return this;')();
  2214. var name = function (element) {
  2215. var r = element.dom().nodeName;
  2216. return r.toLowerCase();
  2217. };
  2218. var type = function (element) {
  2219. return element.dom().nodeType;
  2220. };
  2221. var isType$1 = function (t) {
  2222. return function (element) {
  2223. return type(element) === t;
  2224. };
  2225. };
  2226. var isElement = isType$1(ELEMENT);
  2227. var isText = isType$1(TEXT);
  2228. var rawSet = function (dom, key, value) {
  2229. if (isString(value) || isBoolean(value) || isNumber(value)) {
  2230. dom.setAttribute(key, value + '');
  2231. } else {
  2232. domGlobals.console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  2233. throw new Error('Attribute value was not simple');
  2234. }
  2235. };
  2236. var set$1 = function (element, key, value) {
  2237. rawSet(element.dom(), key, value);
  2238. };
  2239. var setAll = function (element, attrs) {
  2240. var dom = element.dom();
  2241. each$1(attrs, function (v, k) {
  2242. rawSet(dom, k, v);
  2243. });
  2244. };
  2245. var get$2 = function (element, key) {
  2246. var v = element.dom().getAttribute(key);
  2247. return v === null ? undefined : v;
  2248. };
  2249. var getOpt = function (element, key) {
  2250. return Option.from(get$2(element, key));
  2251. };
  2252. var has$1 = function (element, key) {
  2253. var dom = element.dom();
  2254. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  2255. };
  2256. var remove$1 = function (element, key) {
  2257. element.dom().removeAttribute(key);
  2258. };
  2259. var clone = function (original, isDeep) {
  2260. return Element.fromDom(original.dom().cloneNode(isDeep));
  2261. };
  2262. var shallow$1 = function (original) {
  2263. return clone(original, false);
  2264. };
  2265. var getHtml = function (element) {
  2266. var clone = shallow$1(element);
  2267. return getOuter(clone);
  2268. };
  2269. var element = function (elem) {
  2270. return getHtml(elem);
  2271. };
  2272. var isRecursive = function (component, originator, target) {
  2273. return eq$1(originator, component.element()) && !eq$1(originator, target);
  2274. };
  2275. var events = derive([can(focus(), function (component, simulatedEvent) {
  2276. var originator = simulatedEvent.event().originator();
  2277. var target = simulatedEvent.event().target();
  2278. if (isRecursive(component, originator, target)) {
  2279. domGlobals.console.warn(focus() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus() + ' event handlers');
  2280. return false;
  2281. } else {
  2282. return true;
  2283. }
  2284. })]);
  2285. var DefaultEvents = /*#__PURE__*/Object.freeze({
  2286. __proto__: null,
  2287. events: events
  2288. });
  2289. var unique = 0;
  2290. var generate$1 = function (prefix) {
  2291. var date = new Date();
  2292. var time = date.getTime();
  2293. var random = Math.floor(Math.random() * 1000000000);
  2294. unique++;
  2295. return prefix + '_' + random + unique + String(time);
  2296. };
  2297. var prefix = constant('alloy-id-');
  2298. var idAttr = constant('data-alloy-id');
  2299. var prefix$1 = prefix();
  2300. var idAttr$1 = idAttr();
  2301. var write = function (label, elem) {
  2302. var id = generate$1(prefix$1 + label);
  2303. writeOnly(elem, id);
  2304. return id;
  2305. };
  2306. var writeOnly = function (elem, uid) {
  2307. Object.defineProperty(elem.dom(), idAttr$1, {
  2308. value: uid,
  2309. writable: true
  2310. });
  2311. };
  2312. var read$1 = function (elem) {
  2313. var id = isElement(elem) ? elem.dom()[idAttr$1] : null;
  2314. return Option.from(id);
  2315. };
  2316. var generate$2 = function (prefix) {
  2317. return generate$1(prefix);
  2318. };
  2319. var make = identity;
  2320. var NoContextApi = function (getComp) {
  2321. var fail = function (event) {
  2322. return function () {
  2323. throw new Error('The component must be in a context to send: ' + event + (getComp ? '\n' + element(getComp().element()) + ' is not in context.' : ''));
  2324. };
  2325. };
  2326. return {
  2327. debugInfo: constant('fake'),
  2328. triggerEvent: fail('triggerEvent'),
  2329. triggerFocus: fail('triggerFocus'),
  2330. triggerEscape: fail('triggerEscape'),
  2331. build: fail('build'),
  2332. addToWorld: fail('addToWorld'),
  2333. removeFromWorld: fail('removeFromWorld'),
  2334. addToGui: fail('addToGui'),
  2335. removeFromGui: fail('removeFromGui'),
  2336. getByUid: fail('getByUid'),
  2337. getByDom: fail('getByDom'),
  2338. broadcast: fail('broadcast'),
  2339. broadcastOn: fail('broadcastOn'),
  2340. broadcastEvent: fail('broadcastEvent'),
  2341. isConnected: constant(false)
  2342. };
  2343. };
  2344. var singleton = NoContextApi();
  2345. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2346. var delegate = apiFunction.toString();
  2347. var endIndex = delegate.indexOf(')') + 1;
  2348. var openBracketIndex = delegate.indexOf('(');
  2349. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2350. f.toFunctionAnnotation = function () {
  2351. return {
  2352. name: apiName,
  2353. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2354. };
  2355. };
  2356. return f;
  2357. };
  2358. var cleanParameters = function (parameters) {
  2359. return map(parameters, function (p) {
  2360. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2361. });
  2362. };
  2363. var markAsExtraApi = function (f, extraName) {
  2364. var delegate = f.toString();
  2365. var endIndex = delegate.indexOf(')') + 1;
  2366. var openBracketIndex = delegate.indexOf('(');
  2367. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2368. f.toFunctionAnnotation = function () {
  2369. return {
  2370. name: extraName,
  2371. parameters: cleanParameters(parameters)
  2372. };
  2373. };
  2374. return f;
  2375. };
  2376. var markAsSketchApi = function (f, apiFunction) {
  2377. var delegate = apiFunction.toString();
  2378. var endIndex = delegate.indexOf(')') + 1;
  2379. var openBracketIndex = delegate.indexOf('(');
  2380. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2381. f.toFunctionAnnotation = function () {
  2382. return {
  2383. name: 'OVERRIDE',
  2384. parameters: cleanParameters(parameters.slice(1))
  2385. };
  2386. };
  2387. return f;
  2388. };
  2389. var premadeTag = generate$1('alloy-premade');
  2390. var premade = function (comp) {
  2391. return wrap$1(premadeTag, comp);
  2392. };
  2393. var getPremade = function (spec) {
  2394. return get(spec, premadeTag);
  2395. };
  2396. var makeApi = function (f) {
  2397. return markAsSketchApi(function (component) {
  2398. var rest = [];
  2399. for (var _i = 1; _i < arguments.length; _i++) {
  2400. rest[_i - 1] = arguments[_i];
  2401. }
  2402. return f.apply(void 0, __spreadArrays([
  2403. component.getApis(),
  2404. component
  2405. ], rest));
  2406. }, f);
  2407. };
  2408. var NoState = {
  2409. init: function () {
  2410. return nu$5({
  2411. readState: function () {
  2412. return 'No State required';
  2413. }
  2414. });
  2415. }
  2416. };
  2417. var nu$5 = function (spec) {
  2418. return spec;
  2419. };
  2420. var generateFrom = function (spec, all) {
  2421. var schema = map(all, function (a) {
  2422. return optionObjOf(a.name(), [
  2423. strict$1('config'),
  2424. defaulted$1('state', NoState)
  2425. ]);
  2426. });
  2427. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  2428. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  2429. }, function (v) {
  2430. return v;
  2431. });
  2432. return {
  2433. list: all,
  2434. data: map$1(validated, function (optBlobThunk) {
  2435. var output = optBlobThunk.map(function (blob) {
  2436. return {
  2437. config: blob.config,
  2438. state: blob.state.init(blob.config)
  2439. };
  2440. });
  2441. return function () {
  2442. return output;
  2443. };
  2444. })
  2445. };
  2446. };
  2447. var getBehaviours = function (bData) {
  2448. return bData.list;
  2449. };
  2450. var getData = function (bData) {
  2451. return bData.data;
  2452. };
  2453. var byInnerKey = function (data, tuple) {
  2454. var r = {};
  2455. each$1(data, function (detail, key) {
  2456. each$1(detail, function (value, indexKey) {
  2457. var chain = get(r, indexKey).getOr([]);
  2458. r[indexKey] = chain.concat([tuple(key, value)]);
  2459. });
  2460. });
  2461. return r;
  2462. };
  2463. var nu$6 = function (s) {
  2464. return {
  2465. classes: s.classes !== undefined ? s.classes : [],
  2466. attributes: s.attributes !== undefined ? s.attributes : {},
  2467. styles: s.styles !== undefined ? s.styles : {}
  2468. };
  2469. };
  2470. var merge$1 = function (defnA, mod) {
  2471. return __assign(__assign({}, defnA), {
  2472. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2473. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2474. classes: defnA.classes.concat(mod.classes)
  2475. });
  2476. };
  2477. var combine = function (info, baseMod, behaviours, base) {
  2478. var modsByBehaviour = __assign({}, baseMod);
  2479. each(behaviours, function (behaviour) {
  2480. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  2481. });
  2482. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  2483. return {
  2484. name: name,
  2485. modification: modification
  2486. };
  2487. });
  2488. var combineObjects = function (objects) {
  2489. return foldr(objects, function (b, a) {
  2490. return __assign(__assign({}, a.modification), b);
  2491. }, {});
  2492. };
  2493. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  2494. return a.modification.concat(b);
  2495. }, []);
  2496. var combinedAttributes = combineObjects(byAspect.attributes);
  2497. var combinedStyles = combineObjects(byAspect.styles);
  2498. return nu$6({
  2499. classes: combinedClasses,
  2500. attributes: combinedAttributes,
  2501. styles: combinedStyles
  2502. });
  2503. };
  2504. var sortKeys = function (label, keyName, array, order) {
  2505. try {
  2506. var sorted = sort(array, function (a, b) {
  2507. var aKey = a[keyName]();
  2508. var bKey = b[keyName]();
  2509. var aIndex = order.indexOf(aKey);
  2510. var bIndex = order.indexOf(bKey);
  2511. if (aIndex === -1) {
  2512. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2513. }
  2514. if (bIndex === -1) {
  2515. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  2516. }
  2517. if (aIndex < bIndex) {
  2518. return -1;
  2519. } else if (bIndex < aIndex) {
  2520. return 1;
  2521. } else {
  2522. return 0;
  2523. }
  2524. });
  2525. return Result.value(sorted);
  2526. } catch (err) {
  2527. return Result.error([err]);
  2528. }
  2529. };
  2530. var uncurried = function (handler, purpose) {
  2531. return {
  2532. handler: handler,
  2533. purpose: constant(purpose)
  2534. };
  2535. };
  2536. var curried = function (handler, purpose) {
  2537. return {
  2538. cHandler: handler,
  2539. purpose: constant(purpose)
  2540. };
  2541. };
  2542. var curryArgs = function (descHandler, extraArgs) {
  2543. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
  2544. };
  2545. var getCurried = function (descHandler) {
  2546. return descHandler.cHandler;
  2547. };
  2548. var behaviourTuple = function (name, handler) {
  2549. return {
  2550. name: constant(name),
  2551. handler: constant(handler)
  2552. };
  2553. };
  2554. var nameToHandlers = function (behaviours, info) {
  2555. var r = {};
  2556. each(behaviours, function (behaviour) {
  2557. r[behaviour.name()] = behaviour.handlers(info);
  2558. });
  2559. return r;
  2560. };
  2561. var groupByEvents = function (info, behaviours, base) {
  2562. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  2563. return byInnerKey(behaviourEvents, behaviourTuple);
  2564. };
  2565. var combine$1 = function (info, eventOrder, behaviours, base) {
  2566. var byEventName = groupByEvents(info, behaviours, base);
  2567. return combineGroups(byEventName, eventOrder);
  2568. };
  2569. var assemble = function (rawHandler) {
  2570. var handler = read(rawHandler);
  2571. return function (component, simulatedEvent) {
  2572. var rest = [];
  2573. for (var _i = 2; _i < arguments.length; _i++) {
  2574. rest[_i - 2] = arguments[_i];
  2575. }
  2576. var args = [
  2577. component,
  2578. simulatedEvent
  2579. ].concat(rest);
  2580. if (handler.abort.apply(undefined, args)) {
  2581. simulatedEvent.stop();
  2582. } else if (handler.can.apply(undefined, args)) {
  2583. handler.run.apply(undefined, args);
  2584. }
  2585. };
  2586. };
  2587. var missingOrderError = function (eventName, tuples) {
  2588. return Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map(tuples, function (c) {
  2589. return c.name();
  2590. }), null, 2)]);
  2591. };
  2592. var fuse$1 = function (tuples, eventOrder, eventName) {
  2593. var order = eventOrder[eventName];
  2594. if (!order) {
  2595. return missingOrderError(eventName, tuples);
  2596. } else {
  2597. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  2598. var handlers = map(sortedTuples, function (tuple) {
  2599. return tuple.handler();
  2600. });
  2601. return fuse(handlers);
  2602. });
  2603. }
  2604. };
  2605. var combineGroups = function (byEventName, eventOrder) {
  2606. var r = mapToArray(byEventName, function (tuples, eventName) {
  2607. var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
  2608. return combined.map(function (handler) {
  2609. var assembled = assemble(handler);
  2610. var purpose = tuples.length > 1 ? filter(eventOrder[eventName], function (o) {
  2611. return exists(tuples, function (t) {
  2612. return t.name() === o;
  2613. });
  2614. }).join(' > ') : tuples[0].name();
  2615. return wrap$1(eventName, uncurried(assembled, purpose));
  2616. });
  2617. });
  2618. return consolidate(r, {});
  2619. };
  2620. var toInfo = function (spec) {
  2621. return asRaw('custom.definition', objOf([
  2622. field('dom', 'dom', strict(), objOf([
  2623. strict$1('tag'),
  2624. defaulted$1('styles', {}),
  2625. defaulted$1('classes', []),
  2626. defaulted$1('attributes', {}),
  2627. option('value'),
  2628. option('innerHtml')
  2629. ])),
  2630. strict$1('components'),
  2631. strict$1('uid'),
  2632. defaulted$1('events', {}),
  2633. defaulted$1('apis', {}),
  2634. field('eventOrder', 'eventOrder', mergeWith({
  2635. 'alloy.execute': [
  2636. 'disabling',
  2637. 'alloy.base.behaviour',
  2638. 'toggling',
  2639. 'typeaheadevents'
  2640. ],
  2641. 'alloy.focus': [
  2642. 'alloy.base.behaviour',
  2643. 'focusing',
  2644. 'keying'
  2645. ],
  2646. 'alloy.system.init': [
  2647. 'alloy.base.behaviour',
  2648. 'disabling',
  2649. 'toggling',
  2650. 'representing'
  2651. ],
  2652. 'input': [
  2653. 'alloy.base.behaviour',
  2654. 'representing',
  2655. 'streaming',
  2656. 'invalidating'
  2657. ],
  2658. 'alloy.system.detached': [
  2659. 'alloy.base.behaviour',
  2660. 'representing',
  2661. 'item-events',
  2662. 'tooltipping'
  2663. ],
  2664. 'mousedown': [
  2665. 'focusing',
  2666. 'alloy.base.behaviour',
  2667. 'item-type-events'
  2668. ],
  2669. 'touchstart': [
  2670. 'focusing',
  2671. 'alloy.base.behaviour',
  2672. 'item-type-events'
  2673. ],
  2674. 'mouseover': [
  2675. 'item-type-events',
  2676. 'tooltipping'
  2677. ],
  2678. 'alloy.receive': [
  2679. 'receiving',
  2680. 'reflecting'
  2681. ]
  2682. }), anyValue$1()),
  2683. option('domModification')
  2684. ]), spec);
  2685. };
  2686. var toDefinition = function (detail) {
  2687. return __assign(__assign({}, detail.dom), {
  2688. uid: detail.uid,
  2689. domChildren: map(detail.components, function (comp) {
  2690. return comp.element();
  2691. })
  2692. });
  2693. };
  2694. var toModification = function (detail) {
  2695. return detail.domModification.fold(function () {
  2696. return nu$6({});
  2697. }, nu$6);
  2698. };
  2699. var toEvents = function (info) {
  2700. return info.events;
  2701. };
  2702. var read$2 = function (element, attr) {
  2703. var value = get$2(element, attr);
  2704. return value === undefined || value === '' ? [] : value.split(' ');
  2705. };
  2706. var add = function (element, attr, id) {
  2707. var old = read$2(element, attr);
  2708. var nu = old.concat([id]);
  2709. set$1(element, attr, nu.join(' '));
  2710. return true;
  2711. };
  2712. var remove$2 = function (element, attr, id) {
  2713. var nu = filter(read$2(element, attr), function (v) {
  2714. return v !== id;
  2715. });
  2716. if (nu.length > 0) {
  2717. set$1(element, attr, nu.join(' '));
  2718. } else {
  2719. remove$1(element, attr);
  2720. }
  2721. return false;
  2722. };
  2723. var supports = function (element) {
  2724. return element.dom().classList !== undefined;
  2725. };
  2726. var get$3 = function (element) {
  2727. return read$2(element, 'class');
  2728. };
  2729. var add$1 = function (element, clazz) {
  2730. return add(element, 'class', clazz);
  2731. };
  2732. var remove$3 = function (element, clazz) {
  2733. return remove$2(element, 'class', clazz);
  2734. };
  2735. var add$2 = function (element, clazz) {
  2736. if (supports(element)) {
  2737. element.dom().classList.add(clazz);
  2738. } else {
  2739. add$1(element, clazz);
  2740. }
  2741. };
  2742. var cleanClass = function (element) {
  2743. var classList = supports(element) ? element.dom().classList : get$3(element);
  2744. if (classList.length === 0) {
  2745. remove$1(element, 'class');
  2746. }
  2747. };
  2748. var remove$4 = function (element, clazz) {
  2749. if (supports(element)) {
  2750. var classList = element.dom().classList;
  2751. classList.remove(clazz);
  2752. } else {
  2753. remove$3(element, clazz);
  2754. }
  2755. cleanClass(element);
  2756. };
  2757. var has$2 = function (element, clazz) {
  2758. return supports(element) && element.dom().classList.contains(clazz);
  2759. };
  2760. var add$3 = function (element, classes) {
  2761. each(classes, function (x) {
  2762. add$2(element, x);
  2763. });
  2764. };
  2765. var remove$5 = function (element, classes) {
  2766. each(classes, function (x) {
  2767. remove$4(element, x);
  2768. });
  2769. };
  2770. var isSupported = function (dom) {
  2771. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  2772. };
  2773. var inBody = function (element) {
  2774. var dom = isText(element) ? element.dom().parentNode : element.dom();
  2775. return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
  2776. };
  2777. var body = function () {
  2778. return getBody(Element.fromDom(domGlobals.document));
  2779. };
  2780. var getBody = function (doc) {
  2781. var b = doc.dom().body;
  2782. if (b === null || b === undefined) {
  2783. throw new Error('Body is not available yet');
  2784. }
  2785. return Element.fromDom(b);
  2786. };
  2787. var internalSet = function (dom, property, value) {
  2788. if (!isString(value)) {
  2789. domGlobals.console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  2790. throw new Error('CSS value must be a string: ' + value);
  2791. }
  2792. if (isSupported(dom)) {
  2793. dom.style.setProperty(property, value);
  2794. }
  2795. };
  2796. var internalRemove = function (dom, property) {
  2797. if (isSupported(dom)) {
  2798. dom.style.removeProperty(property);
  2799. }
  2800. };
  2801. var set$2 = function (element, property, value) {
  2802. var dom = element.dom();
  2803. internalSet(dom, property, value);
  2804. };
  2805. var setAll$1 = function (element, css) {
  2806. var dom = element.dom();
  2807. each$1(css, function (v, k) {
  2808. internalSet(dom, k, v);
  2809. });
  2810. };
  2811. var setOptions = function (element, css) {
  2812. var dom = element.dom();
  2813. each$1(css, function (v, k) {
  2814. v.fold(function () {
  2815. internalRemove(dom, k);
  2816. }, function (value) {
  2817. internalSet(dom, k, value);
  2818. });
  2819. });
  2820. };
  2821. var get$4 = function (element, property) {
  2822. var dom = element.dom();
  2823. var styles = domGlobals.window.getComputedStyle(dom);
  2824. var r = styles.getPropertyValue(property);
  2825. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  2826. };
  2827. var getUnsafeProperty = function (dom, property) {
  2828. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  2829. };
  2830. var getRaw = function (element, property) {
  2831. var dom = element.dom();
  2832. var raw = getUnsafeProperty(dom, property);
  2833. return Option.from(raw).filter(function (r) {
  2834. return r.length > 0;
  2835. });
  2836. };
  2837. var getAllRaw = function (element) {
  2838. var css = {};
  2839. var dom = element.dom();
  2840. if (isSupported(dom)) {
  2841. for (var i = 0; i < dom.style.length; i++) {
  2842. var ruleName = dom.style.item(i);
  2843. css[ruleName] = dom.style[ruleName];
  2844. }
  2845. }
  2846. return css;
  2847. };
  2848. var isValidValue = function (tag, property, value) {
  2849. var element = Element.fromTag(tag);
  2850. set$2(element, property, value);
  2851. var style = getRaw(element, property);
  2852. return style.isSome();
  2853. };
  2854. var remove$6 = function (element, property) {
  2855. var dom = element.dom();
  2856. internalRemove(dom, property);
  2857. if (getOpt(element, 'style').map(trim).is('')) {
  2858. remove$1(element, 'style');
  2859. }
  2860. };
  2861. var reflow = function (e) {
  2862. return e.dom().offsetWidth;
  2863. };
  2864. var get$5 = function (element) {
  2865. return element.dom().value;
  2866. };
  2867. var set$3 = function (element, value) {
  2868. if (value === undefined) {
  2869. throw new Error('Value.set was undefined');
  2870. }
  2871. element.dom().value = value;
  2872. };
  2873. var renderToDom = function (definition) {
  2874. var subject = Element.fromTag(definition.tag);
  2875. setAll(subject, definition.attributes);
  2876. add$3(subject, definition.classes);
  2877. setAll$1(subject, definition.styles);
  2878. definition.innerHtml.each(function (html) {
  2879. return set(subject, html);
  2880. });
  2881. var children = definition.domChildren;
  2882. append$1(subject, children);
  2883. definition.value.each(function (value) {
  2884. set$3(subject, value);
  2885. });
  2886. if (!definition.uid) {
  2887. debugger;
  2888. }
  2889. writeOnly(subject, definition.uid);
  2890. return subject;
  2891. };
  2892. var getBehaviours$1 = function (spec) {
  2893. var behaviours = get(spec, 'behaviours').getOr({});
  2894. var keys$1 = filter(keys(behaviours), function (k) {
  2895. return behaviours[k] !== undefined;
  2896. });
  2897. return map(keys$1, function (k) {
  2898. return behaviours[k].me;
  2899. });
  2900. };
  2901. var generateFrom$1 = function (spec, all) {
  2902. return generateFrom(spec, all);
  2903. };
  2904. var generate$3 = function (spec) {
  2905. var all = getBehaviours$1(spec);
  2906. return generateFrom$1(spec, all);
  2907. };
  2908. var getDomDefinition = function (info, bList, bData) {
  2909. var definition = toDefinition(info);
  2910. var infoModification = toModification(info);
  2911. var baseModification = { 'alloy.base.modification': infoModification };
  2912. var modification = bList.length > 0 ? combine(bData, baseModification, bList, definition) : infoModification;
  2913. return merge$1(definition, modification);
  2914. };
  2915. var getEvents = function (info, bList, bData) {
  2916. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  2917. return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie();
  2918. };
  2919. var build = function (spec) {
  2920. var getMe = function () {
  2921. return me;
  2922. };
  2923. var systemApi = Cell(singleton);
  2924. var info = getOrDie(toInfo(spec));
  2925. var bBlob = generate$3(spec);
  2926. var bList = getBehaviours(bBlob);
  2927. var bData = getData(bBlob);
  2928. var modDefinition = getDomDefinition(info, bList, bData);
  2929. var item = renderToDom(modDefinition);
  2930. var events = getEvents(info, bList, bData);
  2931. var subcomponents = Cell(info.components);
  2932. var connect = function (newApi) {
  2933. systemApi.set(newApi);
  2934. };
  2935. var disconnect = function () {
  2936. systemApi.set(NoContextApi(getMe));
  2937. };
  2938. var syncComponents = function () {
  2939. var children$1 = children(item);
  2940. var subs = bind(children$1, function (child) {
  2941. return systemApi.get().getByDom(child).fold(function () {
  2942. return [];
  2943. }, function (c) {
  2944. return [c];
  2945. });
  2946. });
  2947. subcomponents.set(subs);
  2948. };
  2949. var config = function (behaviour) {
  2950. var b = bData;
  2951. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  2952. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  2953. };
  2954. return f();
  2955. };
  2956. var hasConfigured = function (behaviour) {
  2957. return isFunction(bData[behaviour.name()]);
  2958. };
  2959. var getApis = function () {
  2960. return info.apis;
  2961. };
  2962. var readState = function (behaviourName) {
  2963. return bData[behaviourName]().map(function (b) {
  2964. return b.state.readState();
  2965. }).getOr('not enabled');
  2966. };
  2967. var me = {
  2968. getSystem: systemApi.get,
  2969. config: config,
  2970. hasConfigured: hasConfigured,
  2971. spec: constant(spec),
  2972. readState: readState,
  2973. getApis: getApis,
  2974. connect: connect,
  2975. disconnect: disconnect,
  2976. element: constant(item),
  2977. syncComponents: syncComponents,
  2978. components: subcomponents.get,
  2979. events: constant(events)
  2980. };
  2981. return me;
  2982. };
  2983. var buildSubcomponents = function (spec) {
  2984. var components = get(spec, 'components').getOr([]);
  2985. return map(components, build$1);
  2986. };
  2987. var buildFromSpec = function (userSpec) {
  2988. var _a = make(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  2989. var components = buildSubcomponents(spec);
  2990. var completeSpec = __assign(__assign({}, spec), {
  2991. events: __assign(__assign({}, DefaultEvents), specEvents),
  2992. components: components
  2993. });
  2994. return Result.value(build(completeSpec));
  2995. };
  2996. var text = function (textContent) {
  2997. var element = Element.fromText(textContent);
  2998. return external({ element: element });
  2999. };
  3000. var external = function (spec) {
  3001. var extSpec = asRawOrDie('external.component', objOfOnly([
  3002. strict$1('element'),
  3003. option('uid')
  3004. ]), spec);
  3005. var systemApi = Cell(NoContextApi());
  3006. var connect = function (newApi) {
  3007. systemApi.set(newApi);
  3008. };
  3009. var disconnect = function () {
  3010. systemApi.set(NoContextApi(function () {
  3011. return me;
  3012. }));
  3013. };
  3014. extSpec.uid.each(function (uid) {
  3015. writeOnly(extSpec.element, uid);
  3016. });
  3017. var me = {
  3018. getSystem: systemApi.get,
  3019. config: Option.none,
  3020. hasConfigured: constant(false),
  3021. connect: connect,
  3022. disconnect: disconnect,
  3023. getApis: function () {
  3024. return {};
  3025. },
  3026. element: constant(extSpec.element),
  3027. spec: constant(spec),
  3028. readState: constant('No state'),
  3029. syncComponents: noop,
  3030. components: constant([]),
  3031. events: constant({})
  3032. };
  3033. return premade(me);
  3034. };
  3035. var uids = generate$2;
  3036. var build$1 = function (spec) {
  3037. return getPremade(spec).fold(function () {
  3038. var userSpecWithUid = spec.hasOwnProperty('uid') ? spec : __assign({ uid: uids('') }, spec);
  3039. return buildFromSpec(userSpecWithUid).getOrDie();
  3040. }, function (prebuilt) {
  3041. return prebuilt;
  3042. });
  3043. };
  3044. var premade$1 = premade;
  3045. function Dimension (name, getOffset) {
  3046. var set = function (element, h) {
  3047. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3048. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3049. }
  3050. var dom = element.dom();
  3051. if (isSupported(dom)) {
  3052. dom.style[name] = h + 'px';
  3053. }
  3054. };
  3055. var get = function (element) {
  3056. var r = getOffset(element);
  3057. if (r <= 0 || r === null) {
  3058. var css = get$4(element, name);
  3059. return parseFloat(css) || 0;
  3060. }
  3061. return r;
  3062. };
  3063. var getOuter = get;
  3064. var aggregate = function (element, properties) {
  3065. return foldl(properties, function (acc, property) {
  3066. var val = get$4(element, property);
  3067. var value = val === undefined ? 0 : parseInt(val, 10);
  3068. return isNaN(value) ? acc : acc + value;
  3069. }, 0);
  3070. };
  3071. var max = function (element, value, properties) {
  3072. var cumulativeInclusions = aggregate(element, properties);
  3073. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3074. return absoluteMax;
  3075. };
  3076. return {
  3077. set: set,
  3078. get: get,
  3079. getOuter: getOuter,
  3080. aggregate: aggregate,
  3081. max: max
  3082. };
  3083. }
  3084. var api = Dimension('height', function (element) {
  3085. var dom = element.dom();
  3086. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3087. });
  3088. var get$6 = function (element) {
  3089. return api.get(element);
  3090. };
  3091. var getOuter$1 = function (element) {
  3092. return api.getOuter(element);
  3093. };
  3094. var setMax = function (element, value) {
  3095. var inclusions = [
  3096. 'margin-top',
  3097. 'border-top-width',
  3098. 'padding-top',
  3099. 'padding-bottom',
  3100. 'border-bottom-width',
  3101. 'margin-bottom'
  3102. ];
  3103. var absMax = api.max(element, value, inclusions);
  3104. set$2(element, 'max-height', absMax + 'px');
  3105. };
  3106. var r = function (left, top) {
  3107. var translate = function (x, y) {
  3108. return r(left + x, top + y);
  3109. };
  3110. return {
  3111. left: constant(left),
  3112. top: constant(top),
  3113. translate: translate
  3114. };
  3115. };
  3116. var Position = r;
  3117. var boxPosition = function (dom) {
  3118. var box = dom.getBoundingClientRect();
  3119. return Position(box.left, box.top);
  3120. };
  3121. var firstDefinedOrZero = function (a, b) {
  3122. if (a !== undefined) {
  3123. return a;
  3124. } else {
  3125. return b !== undefined ? b : 0;
  3126. }
  3127. };
  3128. var absolute = function (element) {
  3129. var doc = element.dom().ownerDocument;
  3130. var body = doc.body;
  3131. var win = doc.defaultView;
  3132. var html = doc.documentElement;
  3133. if (body === element.dom()) {
  3134. return Position(body.offsetLeft, body.offsetTop);
  3135. }
  3136. var scrollTop = firstDefinedOrZero(win.pageYOffset, html.scrollTop);
  3137. var scrollLeft = firstDefinedOrZero(win.pageXOffset, html.scrollLeft);
  3138. var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop);
  3139. var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft);
  3140. return viewport(element).translate(scrollLeft - clientLeft, scrollTop - clientTop);
  3141. };
  3142. var viewport = function (element) {
  3143. var dom = element.dom();
  3144. var doc = dom.ownerDocument;
  3145. var body = doc.body;
  3146. if (body === dom) {
  3147. return Position(body.offsetLeft, body.offsetTop);
  3148. }
  3149. if (!inBody(element)) {
  3150. return Position(0, 0);
  3151. }
  3152. return boxPosition(dom);
  3153. };
  3154. var api$1 = Dimension('width', function (element) {
  3155. return element.dom().offsetWidth;
  3156. });
  3157. var set$4 = function (element, h) {
  3158. return api$1.set(element, h);
  3159. };
  3160. var get$7 = function (element) {
  3161. return api$1.get(element);
  3162. };
  3163. var getOuter$2 = function (element) {
  3164. return api$1.getOuter(element);
  3165. };
  3166. var setMax$1 = function (element, value) {
  3167. var inclusions = [
  3168. 'margin-left',
  3169. 'border-left-width',
  3170. 'padding-left',
  3171. 'padding-right',
  3172. 'border-right-width',
  3173. 'margin-right'
  3174. ];
  3175. var absMax = api$1.max(element, value, inclusions);
  3176. set$2(element, 'max-width', absMax + 'px');
  3177. };
  3178. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  3179. return {
  3180. target: constant(target),
  3181. x: constant(x),
  3182. y: constant(y),
  3183. stop: stop,
  3184. prevent: prevent,
  3185. kill: kill,
  3186. raw: constant(raw)
  3187. };
  3188. };
  3189. var fromRawEvent = function (rawEvent) {
  3190. var target = Element.fromDom(rawEvent.target);
  3191. var stop = function () {
  3192. return rawEvent.stopPropagation();
  3193. };
  3194. var prevent = function () {
  3195. return rawEvent.preventDefault();
  3196. };
  3197. var kill = compose(prevent, stop);
  3198. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  3199. };
  3200. var handle = function (filter, handler) {
  3201. return function (rawEvent) {
  3202. if (filter(rawEvent)) {
  3203. handler(fromRawEvent(rawEvent));
  3204. }
  3205. };
  3206. };
  3207. var binder = function (element, event, filter, handler, useCapture) {
  3208. var wrapped = handle(filter, handler);
  3209. element.dom().addEventListener(event, wrapped, useCapture);
  3210. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  3211. };
  3212. var bind$2 = function (element, event, filter, handler) {
  3213. return binder(element, event, filter, handler, false);
  3214. };
  3215. var capture = function (element, event, filter, handler) {
  3216. return binder(element, event, filter, handler, true);
  3217. };
  3218. var unbind = function (element, event, handler, useCapture) {
  3219. element.dom().removeEventListener(event, handler, useCapture);
  3220. };
  3221. var get$8 = function (_DOC) {
  3222. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3223. var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
  3224. var y = doc.body.scrollTop || doc.documentElement.scrollTop;
  3225. return Position(x, y);
  3226. };
  3227. var to = function (x, y, _DOC) {
  3228. var doc = _DOC !== undefined ? _DOC.dom() : domGlobals.document;
  3229. var win = doc.defaultView;
  3230. win.scrollTo(x, y);
  3231. };
  3232. var get$9 = function (_win) {
  3233. var win = _win === undefined ? domGlobals.window : _win;
  3234. return Option.from(win['visualViewport']);
  3235. };
  3236. var bounds = function (x, y, width, height) {
  3237. return {
  3238. x: x,
  3239. y: y,
  3240. width: width,
  3241. height: height,
  3242. right: x + width,
  3243. bottom: y + height
  3244. };
  3245. };
  3246. var getBounds = function (_win) {
  3247. var win = _win === undefined ? domGlobals.window : _win;
  3248. var doc = win.document;
  3249. var scroll = get$8(Element.fromDom(doc));
  3250. return get$9(win).fold(function () {
  3251. var html = win.document.documentElement;
  3252. var width = html.clientWidth;
  3253. var height = html.clientHeight;
  3254. return bounds(scroll.left(), scroll.top(), width, height);
  3255. }, function (visualViewport) {
  3256. return bounds(Math.max(visualViewport.pageLeft, scroll.left()), Math.max(visualViewport.pageTop, scroll.top()), visualViewport.width, visualViewport.height);
  3257. });
  3258. };
  3259. var walkUp = function (navigation, doc) {
  3260. var frame = navigation.view(doc);
  3261. return frame.fold(constant([]), function (f) {
  3262. var parent = navigation.owner(f);
  3263. var rest = walkUp(navigation, parent);
  3264. return [f].concat(rest);
  3265. });
  3266. };
  3267. var pathTo = function (element, navigation) {
  3268. var d = navigation.owner(element);
  3269. var paths = walkUp(navigation, d);
  3270. return Option.some(paths);
  3271. };
  3272. var view = function (doc) {
  3273. var element = doc.dom() === domGlobals.document ? Option.none() : Option.from(doc.dom().defaultView.frameElement);
  3274. return element.map(Element.fromDom);
  3275. };
  3276. var owner$1 = function (element) {
  3277. return owner(element);
  3278. };
  3279. var Navigation = /*#__PURE__*/Object.freeze({
  3280. __proto__: null,
  3281. view: view,
  3282. owner: owner$1
  3283. });
  3284. var find$3 = function (element) {
  3285. var doc = Element.fromDom(domGlobals.document);
  3286. var scroll = get$8(doc);
  3287. var path = pathTo(element, Navigation);
  3288. return path.fold(curry(absolute, element), function (frames) {
  3289. var offset = viewport(element);
  3290. var r = foldr(frames, function (b, a) {
  3291. var loc = viewport(a);
  3292. return {
  3293. left: b.left + loc.left(),
  3294. top: b.top + loc.top()
  3295. };
  3296. }, {
  3297. left: 0,
  3298. top: 0
  3299. });
  3300. return Position(r.left + offset.left() + scroll.left(), r.top + offset.top() + scroll.top());
  3301. });
  3302. };
  3303. var pointed = function (point, width, height) {
  3304. return {
  3305. point: point,
  3306. width: width,
  3307. height: height
  3308. };
  3309. };
  3310. var rect = function (x, y, width, height) {
  3311. return {
  3312. x: x,
  3313. y: y,
  3314. width: width,
  3315. height: height
  3316. };
  3317. };
  3318. var bounds$1 = function (x, y, width, height) {
  3319. return {
  3320. x: x,
  3321. y: y,
  3322. width: width,
  3323. height: height,
  3324. right: x + width,
  3325. bottom: y + height
  3326. };
  3327. };
  3328. var box = function (element) {
  3329. var xy = absolute(element);
  3330. var w = getOuter$2(element);
  3331. var h = getOuter$1(element);
  3332. return bounds$1(xy.left(), xy.top(), w, h);
  3333. };
  3334. var absolute$1 = function (element) {
  3335. var position = find$3(element);
  3336. var width = getOuter$2(element);
  3337. var height = getOuter$1(element);
  3338. return bounds$1(position.left(), position.top(), width, height);
  3339. };
  3340. var win = function () {
  3341. return getBounds(domGlobals.window);
  3342. };
  3343. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3344. return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
  3345. }
  3346. var ancestor$1 = function (scope, predicate, isRoot) {
  3347. var element = scope.dom();
  3348. var stop = isFunction(isRoot) ? isRoot : constant(false);
  3349. while (element.parentNode) {
  3350. element = element.parentNode;
  3351. var el = Element.fromDom(element);
  3352. if (predicate(el)) {
  3353. return Option.some(el);
  3354. } else if (stop(el)) {
  3355. break;
  3356. }
  3357. }
  3358. return Option.none();
  3359. };
  3360. var closest$1 = function (scope, predicate, isRoot) {
  3361. var is = function (s, test) {
  3362. return test(s);
  3363. };
  3364. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3365. };
  3366. var descendant = function (scope, predicate) {
  3367. var descend = function (node) {
  3368. for (var i = 0; i < node.childNodes.length; i++) {
  3369. var child_1 = Element.fromDom(node.childNodes[i]);
  3370. if (predicate(child_1)) {
  3371. return Option.some(child_1);
  3372. }
  3373. var res = descend(node.childNodes[i]);
  3374. if (res.isSome()) {
  3375. return res;
  3376. }
  3377. }
  3378. return Option.none();
  3379. };
  3380. return descend(scope.dom());
  3381. };
  3382. var closest$2 = function (scope, predicate, isRoot) {
  3383. return closest$1(scope, predicate, isRoot).isSome();
  3384. };
  3385. var ancestor$2 = function (scope, selector, isRoot) {
  3386. return ancestor$1(scope, function (e) {
  3387. return is(e, selector);
  3388. }, isRoot);
  3389. };
  3390. var descendant$1 = function (scope, selector) {
  3391. return one(selector, scope);
  3392. };
  3393. var closest$3 = function (scope, selector, isRoot) {
  3394. var is$1 = function (element, selector) {
  3395. return is(element, selector);
  3396. };
  3397. return ClosestOrAncestor(is$1, ancestor$2, scope, selector, isRoot);
  3398. };
  3399. var find$4 = function (queryElem) {
  3400. var dependent = closest$1(queryElem, function (elem) {
  3401. if (!isElement(elem)) {
  3402. return false;
  3403. }
  3404. var id = get$2(elem, 'id');
  3405. return id !== undefined && id.indexOf('aria-owns') > -1;
  3406. });
  3407. return dependent.bind(function (dep) {
  3408. var id = get$2(dep, 'id');
  3409. var doc = owner(dep);
  3410. return descendant$1(doc, '[aria-owns="' + id + '"]');
  3411. });
  3412. };
  3413. var manager = function () {
  3414. var ariaId = generate$1('aria-owns');
  3415. var link = function (elem) {
  3416. set$1(elem, 'aria-owns', ariaId);
  3417. };
  3418. var unlink = function (elem) {
  3419. remove$1(elem, 'aria-owns');
  3420. };
  3421. return {
  3422. id: ariaId,
  3423. link: link,
  3424. unlink: unlink
  3425. };
  3426. };
  3427. var isAriaPartOf = function (component, queryElem) {
  3428. return find$4(queryElem).exists(function (owner) {
  3429. return isPartOf(component, owner);
  3430. });
  3431. };
  3432. var isPartOf = function (component, queryElem) {
  3433. return closest$2(queryElem, function (el) {
  3434. return eq$1(el, component.element());
  3435. }, constant(false)) || isAriaPartOf(component, queryElem);
  3436. };
  3437. var unknown$3 = 'unknown';
  3438. var EventConfiguration;
  3439. (function (EventConfiguration) {
  3440. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  3441. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  3442. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  3443. }(EventConfiguration || (EventConfiguration = {})));
  3444. var eventConfig = Cell({});
  3445. var makeEventLogger = function (eventName, initialTarget) {
  3446. var sequence = [];
  3447. var startTime = new Date().getTime();
  3448. return {
  3449. logEventCut: function (_name, target, purpose) {
  3450. sequence.push({
  3451. outcome: 'cut',
  3452. target: target,
  3453. purpose: purpose
  3454. });
  3455. },
  3456. logEventStopped: function (_name, target, purpose) {
  3457. sequence.push({
  3458. outcome: 'stopped',
  3459. target: target,
  3460. purpose: purpose
  3461. });
  3462. },
  3463. logNoParent: function (_name, target, purpose) {
  3464. sequence.push({
  3465. outcome: 'no-parent',
  3466. target: target,
  3467. purpose: purpose
  3468. });
  3469. },
  3470. logEventNoHandlers: function (_name, target) {
  3471. sequence.push({
  3472. outcome: 'no-handlers-left',
  3473. target: target
  3474. });
  3475. },
  3476. logEventResponse: function (_name, target, purpose) {
  3477. sequence.push({
  3478. outcome: 'response',
  3479. purpose: purpose,
  3480. target: target
  3481. });
  3482. },
  3483. write: function () {
  3484. var finishTime = new Date().getTime();
  3485. if (contains([
  3486. 'mousemove',
  3487. 'mouseover',
  3488. 'mouseout',
  3489. systemInit()
  3490. ], eventName)) {
  3491. return;
  3492. }
  3493. domGlobals.console.log(eventName, {
  3494. event: eventName,
  3495. time: finishTime - startTime,
  3496. target: initialTarget.dom(),
  3497. sequence: map(sequence, function (s) {
  3498. if (!contains([
  3499. 'cut',
  3500. 'stopped',
  3501. 'response'
  3502. ], s.outcome)) {
  3503. return s.outcome;
  3504. } else {
  3505. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  3506. }
  3507. })
  3508. });
  3509. }
  3510. };
  3511. };
  3512. var processEvent = function (eventName, initialTarget, f) {
  3513. var status = get(eventConfig.get(), eventName).orThunk(function () {
  3514. var patterns = keys(eventConfig.get());
  3515. return findMap(patterns, function (p) {
  3516. return eventName.indexOf(p) > -1 ? Option.some(eventConfig.get()[p]) : Option.none();
  3517. });
  3518. }).getOr(EventConfiguration.NORMAL);
  3519. switch (status) {
  3520. case EventConfiguration.NORMAL:
  3521. return f(noLogger());
  3522. case EventConfiguration.LOGGING: {
  3523. var logger = makeEventLogger(eventName, initialTarget);
  3524. var output = f(logger);
  3525. logger.write();
  3526. return output;
  3527. }
  3528. case EventConfiguration.STOP:
  3529. return true;
  3530. }
  3531. };
  3532. var path = [
  3533. 'alloy/data/Fields',
  3534. 'alloy/debugging/Debugging'
  3535. ];
  3536. var getTrace = function () {
  3537. var err = new Error();
  3538. if (err.stack !== undefined) {
  3539. var lines = err.stack.split('\n');
  3540. return find(lines, function (line) {
  3541. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  3542. return line.indexOf(p) > -1;
  3543. });
  3544. }).getOr(unknown$3);
  3545. } else {
  3546. return unknown$3;
  3547. }
  3548. };
  3549. var ignoreEvent = {
  3550. logEventCut: noop,
  3551. logEventStopped: noop,
  3552. logNoParent: noop,
  3553. logEventNoHandlers: noop,
  3554. logEventResponse: noop,
  3555. write: noop
  3556. };
  3557. var monitorEvent = function (eventName, initialTarget, f) {
  3558. return processEvent(eventName, initialTarget, f);
  3559. };
  3560. var noLogger = constant(ignoreEvent);
  3561. var menuFields = constant([
  3562. strict$1('menu'),
  3563. strict$1('selectedMenu')
  3564. ]);
  3565. var itemFields = constant([
  3566. strict$1('item'),
  3567. strict$1('selectedItem')
  3568. ]);
  3569. var schema = constant(objOf(itemFields().concat(menuFields())));
  3570. var itemSchema = constant(objOf(itemFields()));
  3571. var _initSize = strictObjOf('initSize', [
  3572. strict$1('numColumns'),
  3573. strict$1('numRows')
  3574. ]);
  3575. var itemMarkers = function () {
  3576. return strictOf('markers', itemSchema());
  3577. };
  3578. var tieredMenuMarkers = function () {
  3579. return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  3580. };
  3581. var markers = function (required) {
  3582. return strictObjOf('markers', map(required, strict$1));
  3583. };
  3584. var onPresenceHandler = function (label, fieldName, presence) {
  3585. var trace = getTrace();
  3586. return field(fieldName, fieldName, presence, valueOf(function (f) {
  3587. return Result.value(function () {
  3588. var args = [];
  3589. for (var _i = 0; _i < arguments.length; _i++) {
  3590. args[_i] = arguments[_i];
  3591. }
  3592. return f.apply(undefined, args);
  3593. });
  3594. }));
  3595. };
  3596. var onHandler = function (fieldName) {
  3597. return onPresenceHandler('onHandler', fieldName, defaulted(noop));
  3598. };
  3599. var onKeyboardHandler = function (fieldName) {
  3600. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
  3601. };
  3602. var onStrictHandler = function (fieldName) {
  3603. return onPresenceHandler('onHandler', fieldName, strict());
  3604. };
  3605. var onStrictKeyboardHandler = function (fieldName) {
  3606. return onPresenceHandler('onKeyboardHandler', fieldName, strict());
  3607. };
  3608. var output = function (name, value) {
  3609. return state$1(name, constant(value));
  3610. };
  3611. var snapshot = function (name) {
  3612. return state$1(name, identity);
  3613. };
  3614. var initSize = constant(_initSize);
  3615. var nu$7 = function (x, y, bubble, direction, boundsRestriction, label) {
  3616. return {
  3617. x: constant(x),
  3618. y: constant(y),
  3619. bubble: constant(bubble),
  3620. direction: constant(direction),
  3621. boundsRestriction: constant(boundsRestriction),
  3622. label: constant(label)
  3623. };
  3624. };
  3625. var adt$2 = Adt.generate([
  3626. { southeast: [] },
  3627. { southwest: [] },
  3628. { northeast: [] },
  3629. { northwest: [] },
  3630. { south: [] },
  3631. { north: [] },
  3632. { east: [] },
  3633. { west: [] }
  3634. ]);
  3635. var cata = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) {
  3636. return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west);
  3637. };
  3638. var cataVertical = function (subject, south, middle, north) {
  3639. return subject.fold(south, south, north, north, south, north, middle, middle);
  3640. };
  3641. var cataHorizontal = function (subject, east, middle, west) {
  3642. return subject.fold(east, west, east, west, middle, middle, east, west);
  3643. };
  3644. var southeast = adt$2.southeast;
  3645. var southwest = adt$2.southwest;
  3646. var northeast = adt$2.northeast;
  3647. var northwest = adt$2.northwest;
  3648. var south = adt$2.south;
  3649. var north = adt$2.north;
  3650. var east = adt$2.east;
  3651. var west = adt$2.west;
  3652. var getRestriction = function (anchor, restriction) {
  3653. switch (restriction) {
  3654. case 1:
  3655. return anchor.x;
  3656. case 0:
  3657. return anchor.x + anchor.width;
  3658. case 2:
  3659. return anchor.y;
  3660. case 3:
  3661. return anchor.y + anchor.height;
  3662. }
  3663. };
  3664. var boundsRestriction = function (anchor, restrictions) {
  3665. return mapToObject([
  3666. 'left',
  3667. 'right',
  3668. 'top',
  3669. 'bottom'
  3670. ], function (dir) {
  3671. return get(restrictions, dir).map(function (restriction) {
  3672. return getRestriction(anchor, restriction);
  3673. });
  3674. });
  3675. };
  3676. var adjustBounds = function (bounds, boundsRestrictions, bubbleOffsets) {
  3677. var applyRestriction = function (dir, current) {
  3678. var bubbleOffset = dir === 'top' || dir === 'bottom' ? bubbleOffsets.top() : bubbleOffsets.left();
  3679. return get(boundsRestrictions, dir).bind(identity).bind(function (restriction) {
  3680. if (dir === 'left' || dir === 'top') {
  3681. return restriction >= current ? Option.some(restriction) : Option.none();
  3682. } else {
  3683. return restriction <= current ? Option.some(restriction) : Option.none();
  3684. }
  3685. }).map(function (restriction) {
  3686. return restriction + bubbleOffset;
  3687. }).getOr(current);
  3688. };
  3689. var adjustedLeft = applyRestriction('left', bounds.x);
  3690. var adjustedTop = applyRestriction('top', bounds.y);
  3691. var adjustedRight = applyRestriction('right', bounds.right);
  3692. var adjustedBottom = applyRestriction('bottom', bounds.bottom);
  3693. return bounds$1(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop);
  3694. };
  3695. var eastX = function (anchor) {
  3696. return anchor.x;
  3697. };
  3698. var middleX = function (anchor, element) {
  3699. return anchor.x + anchor.width / 2 - element.width / 2;
  3700. };
  3701. var westX = function (anchor, element) {
  3702. return anchor.x + anchor.width - element.width;
  3703. };
  3704. var northY = function (anchor, element) {
  3705. return anchor.y - element.height;
  3706. };
  3707. var southY = function (anchor) {
  3708. return anchor.y + anchor.height;
  3709. };
  3710. var centreY = function (anchor, element) {
  3711. return anchor.y + anchor.height / 2 - element.height / 2;
  3712. };
  3713. var eastEdgeX = function (anchor) {
  3714. return anchor.x + anchor.width;
  3715. };
  3716. var westEdgeX = function (anchor, element) {
  3717. return anchor.x - element.width;
  3718. };
  3719. var southeast$1 = function (anchor, element, bubbles) {
  3720. return nu$7(eastX(anchor), southY(anchor), bubbles.southeast(), southeast(), boundsRestriction(anchor, {
  3721. left: 1,
  3722. top: 3
  3723. }), 'layout-se');
  3724. };
  3725. var southwest$1 = function (anchor, element, bubbles) {
  3726. return nu$7(westX(anchor, element), southY(anchor), bubbles.southwest(), southwest(), boundsRestriction(anchor, {
  3727. right: 0,
  3728. top: 3
  3729. }), 'layout-sw');
  3730. };
  3731. var northeast$1 = function (anchor, element, bubbles) {
  3732. return nu$7(eastX(anchor), northY(anchor, element), bubbles.northeast(), northeast(), boundsRestriction(anchor, {
  3733. left: 1,
  3734. bottom: 2
  3735. }), 'layout-ne');
  3736. };
  3737. var northwest$1 = function (anchor, element, bubbles) {
  3738. return nu$7(westX(anchor, element), northY(anchor, element), bubbles.northwest(), northwest(), boundsRestriction(anchor, {
  3739. right: 0,
  3740. bottom: 2
  3741. }), 'layout-nw');
  3742. };
  3743. var north$1 = function (anchor, element, bubbles) {
  3744. return nu$7(middleX(anchor, element), northY(anchor, element), bubbles.north(), north(), boundsRestriction(anchor, { bottom: 2 }), 'layout-n');
  3745. };
  3746. var south$1 = function (anchor, element, bubbles) {
  3747. return nu$7(middleX(anchor, element), southY(anchor), bubbles.south(), south(), boundsRestriction(anchor, { top: 3 }), 'layout-s');
  3748. };
  3749. var east$1 = function (anchor, element, bubbles) {
  3750. return nu$7(eastEdgeX(anchor), centreY(anchor, element), bubbles.east(), east(), boundsRestriction(anchor, { left: 0 }), 'layout-e');
  3751. };
  3752. var west$1 = function (anchor, element, bubbles) {
  3753. return nu$7(westEdgeX(anchor, element), centreY(anchor, element), bubbles.west(), west(), boundsRestriction(anchor, { right: 1 }), 'layout-w');
  3754. };
  3755. var all$2 = function () {
  3756. return [
  3757. southeast$1,
  3758. southwest$1,
  3759. northeast$1,
  3760. northwest$1,
  3761. south$1,
  3762. north$1,
  3763. east$1,
  3764. west$1
  3765. ];
  3766. };
  3767. var allRtl = function () {
  3768. return [
  3769. southwest$1,
  3770. southeast$1,
  3771. northwest$1,
  3772. northeast$1,
  3773. south$1,
  3774. north$1,
  3775. east$1,
  3776. west$1
  3777. ];
  3778. };
  3779. var aboveOrBelow = function () {
  3780. return [
  3781. northeast$1,
  3782. northwest$1,
  3783. southeast$1,
  3784. southwest$1,
  3785. north$1,
  3786. south$1
  3787. ];
  3788. };
  3789. var aboveOrBelowRtl = function () {
  3790. return [
  3791. northwest$1,
  3792. northeast$1,
  3793. southwest$1,
  3794. southeast$1,
  3795. north$1,
  3796. south$1
  3797. ];
  3798. };
  3799. var belowOrAbove = function () {
  3800. return [
  3801. southeast$1,
  3802. southwest$1,
  3803. northeast$1,
  3804. northwest$1,
  3805. south$1,
  3806. north$1
  3807. ];
  3808. };
  3809. var belowOrAboveRtl = function () {
  3810. return [
  3811. southwest$1,
  3812. southeast$1,
  3813. northwest$1,
  3814. northeast$1,
  3815. south$1,
  3816. north$1
  3817. ];
  3818. };
  3819. var executeEvent = function (bConfig, bState, executor) {
  3820. return runOnExecute(function (component) {
  3821. executor(component, bConfig, bState);
  3822. });
  3823. };
  3824. var loadEvent = function (bConfig, bState, f) {
  3825. return runOnInit(function (component, _simulatedEvent) {
  3826. f(component, bConfig, bState);
  3827. });
  3828. };
  3829. var create = function (schema, name, active, apis, extra, state) {
  3830. var configSchema = objOfOnly(schema);
  3831. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  3832. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3833. };
  3834. var createModes = function (modes, name, active, apis, extra, state) {
  3835. var configSchema = modes;
  3836. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  3837. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  3838. };
  3839. var wrapApi = function (bName, apiFunction, apiName) {
  3840. var f = function (component) {
  3841. var rest = [];
  3842. for (var _i = 1; _i < arguments.length; _i++) {
  3843. rest[_i - 1] = arguments[_i];
  3844. }
  3845. var args = [component].concat(rest);
  3846. return component.config({ name: constant(bName) }).fold(function () {
  3847. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  3848. }, function (info) {
  3849. var rest = Array.prototype.slice.call(args, 1);
  3850. return apiFunction.apply(undefined, [
  3851. component,
  3852. info.config,
  3853. info.state
  3854. ].concat(rest));
  3855. });
  3856. };
  3857. return markAsBehaviourApi(f, apiName, apiFunction);
  3858. };
  3859. var revokeBehaviour = function (name) {
  3860. return {
  3861. key: name,
  3862. value: undefined
  3863. };
  3864. };
  3865. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  3866. var getConfig = function (info) {
  3867. return hasNonNullableKey(info, name) ? info[name]() : Option.none();
  3868. };
  3869. var wrappedApis = map$1(apis, function (apiF, apiName) {
  3870. return wrapApi(name, apiF, apiName);
  3871. });
  3872. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  3873. return markAsExtraApi(extraF, extraName);
  3874. });
  3875. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  3876. revoke: curry(revokeBehaviour, name),
  3877. config: function (spec) {
  3878. var prepared = asRawOrDie(name + '-config', configSchema, spec);
  3879. return {
  3880. key: name,
  3881. value: {
  3882. config: prepared,
  3883. me: me,
  3884. configAsRaw: cached(function () {
  3885. return asRawOrDie(name + '-config', configSchema, spec);
  3886. }),
  3887. initialConfig: spec,
  3888. state: state
  3889. }
  3890. };
  3891. },
  3892. schema: function () {
  3893. return schemaSchema;
  3894. },
  3895. exhibit: function (info, base) {
  3896. return getConfig(info).bind(function (behaviourInfo) {
  3897. return get(active, 'exhibit').map(function (exhibitor) {
  3898. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  3899. });
  3900. }).getOr(nu$6({}));
  3901. },
  3902. name: function () {
  3903. return name;
  3904. },
  3905. handlers: function (info) {
  3906. return getConfig(info).map(function (behaviourInfo) {
  3907. var getEvents = get(active, 'events').getOr(function () {
  3908. return {};
  3909. });
  3910. return getEvents(behaviourInfo.config, behaviourInfo.state);
  3911. }).getOr({});
  3912. }
  3913. });
  3914. return me;
  3915. };
  3916. var derive$1 = function (capabilities) {
  3917. return wrapAll$1(capabilities);
  3918. };
  3919. var simpleSchema = objOfOnly([
  3920. strict$1('fields'),
  3921. strict$1('name'),
  3922. defaulted$1('active', {}),
  3923. defaulted$1('apis', {}),
  3924. defaulted$1('state', NoState),
  3925. defaulted$1('extra', {})
  3926. ]);
  3927. var create$1 = function (data) {
  3928. var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
  3929. return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  3930. };
  3931. var modeSchema = objOfOnly([
  3932. strict$1('branchKey'),
  3933. strict$1('branches'),
  3934. strict$1('name'),
  3935. defaulted$1('active', {}),
  3936. defaulted$1('apis', {}),
  3937. defaulted$1('state', NoState),
  3938. defaulted$1('extra', {})
  3939. ]);
  3940. var createModes$1 = function (data) {
  3941. var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
  3942. return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  3943. };
  3944. var revoke = constant(undefined);
  3945. var chooseChannels = function (channels, message) {
  3946. return message.universal() ? channels : filter(channels, function (ch) {
  3947. return contains(message.channels(), ch);
  3948. });
  3949. };
  3950. var events$1 = function (receiveConfig) {
  3951. return derive([run(receive(), function (component, message) {
  3952. var channelMap = receiveConfig.channels;
  3953. var channels = keys(channelMap);
  3954. var receivingData = message;
  3955. var targetChannels = chooseChannels(channels, receivingData);
  3956. each(targetChannels, function (ch) {
  3957. var channelInfo = channelMap[ch];
  3958. var channelSchema = channelInfo.schema;
  3959. var data = asRawOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, receivingData.data());
  3960. channelInfo.onReceive(component, data);
  3961. });
  3962. })]);
  3963. };
  3964. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  3965. __proto__: null,
  3966. events: events$1
  3967. });
  3968. var ReceivingSchema = [strictOf('channels', setOf$1(Result.value, objOfOnly([
  3969. onStrictHandler('onReceive'),
  3970. defaulted$1('schema', anyValue$1())
  3971. ])))];
  3972. var Receiving = create$1({
  3973. fields: ReceivingSchema,
  3974. name: 'receiving',
  3975. active: ActiveReceiving
  3976. });
  3977. var exhibit = function (base, posConfig) {
  3978. return nu$6({
  3979. classes: [],
  3980. styles: posConfig.useFixed() ? {} : { position: 'relative' }
  3981. });
  3982. };
  3983. var ActivePosition = /*#__PURE__*/Object.freeze({
  3984. __proto__: null,
  3985. exhibit: exhibit
  3986. });
  3987. var focus$1 = function (element) {
  3988. return element.dom().focus();
  3989. };
  3990. var blur = function (element) {
  3991. return element.dom().blur();
  3992. };
  3993. var hasFocus = function (element) {
  3994. var doc = owner(element).dom();
  3995. return element.dom() === doc.activeElement;
  3996. };
  3997. var active = function (_doc) {
  3998. var doc = _doc !== undefined ? _doc.dom() : domGlobals.document;
  3999. return Option.from(doc.activeElement).map(Element.fromDom);
  4000. };
  4001. var search = function (element) {
  4002. return active(owner(element)).filter(function (e) {
  4003. return element.dom().contains(e.dom());
  4004. });
  4005. };
  4006. var preserve = function (f, container) {
  4007. var ownerDoc = owner(container);
  4008. var refocus = active(ownerDoc).bind(function (focused) {
  4009. var hasFocus = function (elem) {
  4010. return eq$1(focused, elem);
  4011. };
  4012. return hasFocus(container) ? Option.some(container) : descendant(container, hasFocus);
  4013. });
  4014. var result = f(container);
  4015. refocus.each(function (oldFocus) {
  4016. active(ownerDoc).filter(function (newFocus) {
  4017. return eq$1(newFocus, oldFocus);
  4018. }).fold(function () {
  4019. focus$1(oldFocus);
  4020. }, noop);
  4021. });
  4022. return result;
  4023. };
  4024. var NuPositionCss = function (position, left, top, right, bottom) {
  4025. return {
  4026. position: constant(position),
  4027. left: constant(left),
  4028. top: constant(top),
  4029. right: constant(right),
  4030. bottom: constant(bottom)
  4031. };
  4032. };
  4033. var applyPositionCss = function (element, position) {
  4034. var addPx = function (num) {
  4035. return num + 'px';
  4036. };
  4037. setOptions(element, {
  4038. position: Option.some(position.position()),
  4039. left: position.left().map(addPx),
  4040. top: position.top().map(addPx),
  4041. right: position.right().map(addPx),
  4042. bottom: position.bottom().map(addPx)
  4043. });
  4044. };
  4045. var adt$3 = Adt.generate([
  4046. { none: [] },
  4047. {
  4048. relative: [
  4049. 'x',
  4050. 'y',
  4051. 'width',
  4052. 'height'
  4053. ]
  4054. },
  4055. {
  4056. fixed: [
  4057. 'x',
  4058. 'y',
  4059. 'width',
  4060. 'height'
  4061. ]
  4062. }
  4063. ]);
  4064. var positionWithDirection = function (posName, decision, x, y, width, height) {
  4065. var decisionX = decision.x - x;
  4066. var decisionY = decision.y - y;
  4067. var decisionWidth = decision.width;
  4068. var decisionHeight = decision.height;
  4069. var decisionRight = width - (decisionX + decisionWidth);
  4070. var decisionBottom = height - (decisionY + decisionHeight);
  4071. var left = Option.some(decisionX);
  4072. var top = Option.some(decisionY);
  4073. var right = Option.some(decisionRight);
  4074. var bottom = Option.some(decisionBottom);
  4075. var none = Option.none();
  4076. return cata(decision.direction, function () {
  4077. return NuPositionCss(posName, left, top, none, none);
  4078. }, function () {
  4079. return NuPositionCss(posName, none, top, right, none);
  4080. }, function () {
  4081. return NuPositionCss(posName, left, none, none, bottom);
  4082. }, function () {
  4083. return NuPositionCss(posName, none, none, right, bottom);
  4084. }, function () {
  4085. return NuPositionCss(posName, left, top, none, none);
  4086. }, function () {
  4087. return NuPositionCss(posName, left, none, none, bottom);
  4088. }, function () {
  4089. return NuPositionCss(posName, left, top, none, none);
  4090. }, function () {
  4091. return NuPositionCss(posName, none, top, right, none);
  4092. });
  4093. };
  4094. var reposition = function (origin, decision) {
  4095. return origin.fold(function () {
  4096. return NuPositionCss('absolute', Option.some(decision.x), Option.some(decision.y), Option.none(), Option.none());
  4097. }, function (x, y, width, height) {
  4098. return positionWithDirection('absolute', decision, x, y, width, height);
  4099. }, function (x, y, width, height) {
  4100. return positionWithDirection('fixed', decision, x, y, width, height);
  4101. });
  4102. };
  4103. var toBox = function (origin, element) {
  4104. var rel = curry(find$3, element);
  4105. var position = origin.fold(rel, rel, function () {
  4106. var scroll = get$8();
  4107. return find$3(element).translate(-scroll.left(), -scroll.top());
  4108. });
  4109. var width = getOuter$2(element);
  4110. var height = getOuter$1(element);
  4111. return bounds$1(position.left(), position.top(), width, height);
  4112. };
  4113. var viewport$1 = function (origin, getBounds) {
  4114. return getBounds.fold(function () {
  4115. return origin.fold(win, win, bounds$1);
  4116. }, function (b) {
  4117. return origin.fold(b, b, function () {
  4118. var bounds = b();
  4119. var pos = translate(origin, bounds.x, bounds.y);
  4120. return bounds$1(pos.left(), pos.top(), bounds.width, bounds.height);
  4121. });
  4122. });
  4123. };
  4124. var translate = function (origin, x, y) {
  4125. var pos = Position(x, y);
  4126. var removeScroll = function () {
  4127. var outerScroll = get$8();
  4128. return pos.translate(-outerScroll.left(), -outerScroll.top());
  4129. };
  4130. return origin.fold(constant(pos), constant(pos), removeScroll);
  4131. };
  4132. var cata$1 = function (subject, onNone, onRelative, onFixed) {
  4133. return subject.fold(onNone, onRelative, onFixed);
  4134. };
  4135. var none$1 = adt$3.none;
  4136. var relative = adt$3.relative;
  4137. var fixed = adt$3.fixed;
  4138. var anchor = function (anchorBox, origin) {
  4139. return {
  4140. anchorBox: constant(anchorBox),
  4141. origin: constant(origin)
  4142. };
  4143. };
  4144. var box$1 = function (anchorBox, origin) {
  4145. return anchor(anchorBox, origin);
  4146. };
  4147. var cycleBy = function (value, delta, min, max) {
  4148. var r = value + delta;
  4149. return r > max ? min : r < min ? max : r;
  4150. };
  4151. var clamp = function (value, min, max) {
  4152. return Math.min(Math.max(value, min), max);
  4153. };
  4154. var adt$4 = Adt.generate([
  4155. { fit: ['reposition'] },
  4156. {
  4157. nofit: [
  4158. 'reposition',
  4159. 'deltaW',
  4160. 'deltaH'
  4161. ]
  4162. }
  4163. ]);
  4164. var calcReposition = function (newX, newY, width, height, bounds) {
  4165. var boundsX = bounds.x;
  4166. var boundsY = bounds.y;
  4167. var boundsWidth = bounds.width;
  4168. var boundsHeight = bounds.height;
  4169. var xInBounds = newX >= boundsX;
  4170. var yInBounds = newY >= boundsY;
  4171. var originInBounds = xInBounds && yInBounds;
  4172. var xFit = newX + width <= boundsX + boundsWidth;
  4173. var yFit = newY + height <= boundsY + boundsHeight;
  4174. var sizeInBounds = xFit && yFit;
  4175. var deltaW = Math.abs(Math.min(width, xInBounds ? boundsX + boundsWidth - newX : boundsX - (newX + width)));
  4176. var deltaH = Math.abs(Math.min(height, yInBounds ? boundsY + boundsHeight - newY : boundsY - (newY + height)));
  4177. var maxX = Math.max(bounds.x, bounds.right - width);
  4178. var maxY = Math.max(bounds.y, bounds.bottom - height);
  4179. var limitX = clamp(newX, bounds.x, maxX);
  4180. var limitY = clamp(newY, bounds.y, maxY);
  4181. return {
  4182. originInBounds: originInBounds,
  4183. sizeInBounds: sizeInBounds,
  4184. limitX: limitX,
  4185. limitY: limitY,
  4186. deltaW: deltaW,
  4187. deltaH: deltaH
  4188. };
  4189. };
  4190. var attempt = function (candidate, width, height, bounds) {
  4191. var candidateX = candidate.x();
  4192. var candidateY = candidate.y();
  4193. var bubbleOffsets = candidate.bubble().offset();
  4194. var bubbleLeft = bubbleOffsets.left();
  4195. var bubbleTop = bubbleOffsets.top();
  4196. var adjustedBounds = adjustBounds(bounds, candidate.boundsRestriction(), bubbleOffsets);
  4197. var boundsY = adjustedBounds.y;
  4198. var boundsBottom = adjustedBounds.bottom;
  4199. var boundsX = adjustedBounds.x;
  4200. var boundsRight = adjustedBounds.right;
  4201. var newX = candidateX + bubbleLeft;
  4202. var newY = candidateY + bubbleTop;
  4203. var _a = calcReposition(newX, newY, width, height, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, limitX = _a.limitX, limitY = _a.limitY, deltaW = _a.deltaW, deltaH = _a.deltaH;
  4204. var upAvailable = constant(limitY + deltaH - boundsY);
  4205. var downAvailable = constant(boundsBottom - limitY);
  4206. var maxHeight = cataVertical(candidate.direction(), downAvailable, downAvailable, upAvailable);
  4207. var westAvailable = constant(limitX + deltaW - boundsX);
  4208. var eastAvailable = constant(boundsRight - limitX);
  4209. var maxWidth = cataHorizontal(candidate.direction(), eastAvailable, eastAvailable, westAvailable);
  4210. var reposition = {
  4211. x: limitX,
  4212. y: limitY,
  4213. width: deltaW,
  4214. height: deltaH,
  4215. maxHeight: maxHeight,
  4216. maxWidth: maxWidth,
  4217. direction: candidate.direction(),
  4218. classes: {
  4219. on: candidate.bubble().classesOn(),
  4220. off: candidate.bubble().classesOff()
  4221. },
  4222. label: candidate.label(),
  4223. candidateYforTest: newY
  4224. };
  4225. return originInBounds && sizeInBounds ? adt$4.fit(reposition) : adt$4.nofit(reposition, deltaW, deltaH);
  4226. };
  4227. var attempts = function (candidates, anchorBox, elementBox, bubbles, bounds) {
  4228. var panelWidth = elementBox.width;
  4229. var panelHeight = elementBox.height;
  4230. var attemptBestFit = function (layout, reposition, deltaW, deltaH) {
  4231. var next = layout(anchorBox, elementBox, bubbles);
  4232. var attemptLayout = attempt(next, panelWidth, panelHeight, bounds);
  4233. return attemptLayout.fold(adt$4.fit, function (newReposition, newDeltaW, newDeltaH) {
  4234. var improved = newDeltaH > deltaH || newDeltaW > deltaW;
  4235. return improved ? adt$4.nofit(newReposition, newDeltaW, newDeltaH) : adt$4.nofit(reposition, deltaW, deltaH);
  4236. });
  4237. };
  4238. var abc = foldl(candidates, function (b, a) {
  4239. var bestNext = curry(attemptBestFit, a);
  4240. return b.fold(adt$4.fit, bestNext);
  4241. }, adt$4.nofit({
  4242. x: anchorBox.x,
  4243. y: anchorBox.y,
  4244. width: elementBox.width,
  4245. height: elementBox.height,
  4246. maxHeight: elementBox.height,
  4247. maxWidth: elementBox.width,
  4248. direction: southeast(),
  4249. classes: {
  4250. on: [],
  4251. off: []
  4252. },
  4253. label: 'none',
  4254. candidateYforTest: anchorBox.y
  4255. }, -1, -1));
  4256. return abc.fold(identity, identity);
  4257. };
  4258. var elementSize = function (p) {
  4259. return {
  4260. width: getOuter$2(p),
  4261. height: getOuter$1(p)
  4262. };
  4263. };
  4264. var layout = function (anchorBox, element, bubbles, options) {
  4265. remove$6(element, 'max-height');
  4266. remove$6(element, 'max-width');
  4267. var elementBox = elementSize(element);
  4268. return attempts(options.preference, anchorBox, elementBox, bubbles, options.bounds);
  4269. };
  4270. var setClasses = function (element, decision) {
  4271. var classInfo = decision.classes;
  4272. remove$5(element, classInfo.off);
  4273. add$3(element, classInfo.on);
  4274. };
  4275. var setHeight = function (element, decision, options) {
  4276. var maxHeightFunction = options.maxHeightFunction;
  4277. maxHeightFunction(element, decision.maxHeight);
  4278. };
  4279. var setWidth = function (element, decision, options) {
  4280. var maxWidthFunction = options.maxWidthFunction;
  4281. maxWidthFunction(element, decision.maxWidth);
  4282. };
  4283. var position = function (element, decision, options) {
  4284. applyPositionCss(element, reposition(options.origin, decision));
  4285. };
  4286. var setMaxHeight = function (element, maxHeight) {
  4287. setMax(element, Math.floor(maxHeight));
  4288. };
  4289. var anchored = constant(function (element, available) {
  4290. setMaxHeight(element, available);
  4291. setAll$1(element, {
  4292. 'overflow-x': 'hidden',
  4293. 'overflow-y': 'auto'
  4294. });
  4295. });
  4296. var expandable = constant(function (element, available) {
  4297. setMaxHeight(element, available);
  4298. });
  4299. var defaultOr = function (options, key, dephault) {
  4300. return options[key] === undefined ? dephault : options[key];
  4301. };
  4302. var simple = function (anchor, element, bubble, layouts, getBounds, overrideOptions) {
  4303. var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored());
  4304. var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop);
  4305. var anchorBox = anchor.anchorBox();
  4306. var origin = anchor.origin();
  4307. var options = {
  4308. bounds: viewport$1(origin, getBounds),
  4309. origin: origin,
  4310. preference: layouts,
  4311. maxHeightFunction: maxHeightFunction,
  4312. maxWidthFunction: maxWidthFunction
  4313. };
  4314. go(anchorBox, element, bubble, options);
  4315. };
  4316. var go = function (anchorBox, element, bubble, options) {
  4317. var decision = layout(anchorBox, element, bubble, options);
  4318. position(element, decision, options);
  4319. setClasses(element, decision);
  4320. setHeight(element, decision, options);
  4321. setWidth(element, decision, options);
  4322. };
  4323. var allAlignments = [
  4324. 'valignCentre',
  4325. 'alignLeft',
  4326. 'alignRight',
  4327. 'alignCentre',
  4328. 'top',
  4329. 'bottom',
  4330. 'left',
  4331. 'right'
  4332. ];
  4333. var nu$8 = function (width, yoffset, classes) {
  4334. var getClasses = function (prop) {
  4335. return get(classes, prop).getOr([]);
  4336. };
  4337. var make = function (xDelta, yDelta, alignmentsOn) {
  4338. var alignmentsOff = difference(allAlignments, alignmentsOn);
  4339. return {
  4340. offset: function () {
  4341. return Position(xDelta, yDelta);
  4342. },
  4343. classesOn: function () {
  4344. return bind(alignmentsOn, getClasses);
  4345. },
  4346. classesOff: function () {
  4347. return bind(alignmentsOff, getClasses);
  4348. }
  4349. };
  4350. };
  4351. return {
  4352. southeast: function () {
  4353. return make(-width, yoffset, [
  4354. 'top',
  4355. 'alignLeft'
  4356. ]);
  4357. },
  4358. southwest: function () {
  4359. return make(width, yoffset, [
  4360. 'top',
  4361. 'alignRight'
  4362. ]);
  4363. },
  4364. south: function () {
  4365. return make(-width / 2, yoffset, [
  4366. 'top',
  4367. 'alignCentre'
  4368. ]);
  4369. },
  4370. northeast: function () {
  4371. return make(-width, -yoffset, [
  4372. 'bottom',
  4373. 'alignLeft'
  4374. ]);
  4375. },
  4376. northwest: function () {
  4377. return make(width, -yoffset, [
  4378. 'bottom',
  4379. 'alignRight'
  4380. ]);
  4381. },
  4382. north: function () {
  4383. return make(-width / 2, -yoffset, [
  4384. 'bottom',
  4385. 'alignCentre'
  4386. ]);
  4387. },
  4388. east: function () {
  4389. return make(width, -yoffset / 2, [
  4390. 'valignCentre',
  4391. 'left'
  4392. ]);
  4393. },
  4394. west: function () {
  4395. return make(-width, -yoffset / 2, [
  4396. 'valignCentre',
  4397. 'right'
  4398. ]);
  4399. },
  4400. innerNorthwest: function () {
  4401. return make(-width, yoffset, [
  4402. 'top',
  4403. 'alignRight'
  4404. ]);
  4405. },
  4406. innerNortheast: function () {
  4407. return make(width, yoffset, [
  4408. 'top',
  4409. 'alignLeft'
  4410. ]);
  4411. },
  4412. innerNorth: function () {
  4413. return make(-width / 2, yoffset, [
  4414. 'top',
  4415. 'alignCentre'
  4416. ]);
  4417. },
  4418. innerSouthwest: function () {
  4419. return make(-width, -yoffset, [
  4420. 'bottom',
  4421. 'alignRight'
  4422. ]);
  4423. },
  4424. innerSoutheast: function () {
  4425. return make(width, -yoffset, [
  4426. 'bottom',
  4427. 'alignLeft'
  4428. ]);
  4429. },
  4430. innerSouth: function () {
  4431. return make(-width / 2, -yoffset, [
  4432. 'bottom',
  4433. 'alignCentre'
  4434. ]);
  4435. },
  4436. innerWest: function () {
  4437. return make(width, -yoffset / 2, [
  4438. 'valignCentre',
  4439. 'right'
  4440. ]);
  4441. },
  4442. innerEast: function () {
  4443. return make(-width, -yoffset / 2, [
  4444. 'valignCentre',
  4445. 'left'
  4446. ]);
  4447. }
  4448. };
  4449. };
  4450. var fallback = function () {
  4451. return nu$8(0, 0, {});
  4452. };
  4453. var nu$9 = function (x) {
  4454. return x;
  4455. };
  4456. var onDirection = function (isLtr, isRtl) {
  4457. return function (element) {
  4458. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  4459. };
  4460. };
  4461. var getDirection = function (element) {
  4462. return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  4463. };
  4464. var AttributeValue;
  4465. (function (AttributeValue) {
  4466. AttributeValue['TopToBottom'] = 'toptobottom';
  4467. AttributeValue['BottomToTop'] = 'bottomtotop';
  4468. }(AttributeValue || (AttributeValue = {})));
  4469. var Attribute = 'data-alloy-vertical-dir';
  4470. var isBottomToTopDir = function (el) {
  4471. return closest$2(el, function (current) {
  4472. return isElement(current) && get$2(current, Attribute) === AttributeValue.BottomToTop;
  4473. });
  4474. };
  4475. var schema$1 = function () {
  4476. return optionObjOf('layouts', [
  4477. strict$1('onLtr'),
  4478. strict$1('onRtl'),
  4479. option('onBottomLtr'),
  4480. option('onBottomRtl')
  4481. ]);
  4482. };
  4483. var get$a = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) {
  4484. var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false);
  4485. var customLtr = info.layouts.map(function (ls) {
  4486. return ls.onLtr(elem);
  4487. });
  4488. var customRtl = info.layouts.map(function (ls) {
  4489. return ls.onRtl(elem);
  4490. });
  4491. var ltr = isBottomToTop ? info.layouts.bind(function (ls) {
  4492. return ls.onBottomLtr.map(function (f) {
  4493. return f(elem);
  4494. });
  4495. }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr);
  4496. var rtl = isBottomToTop ? info.layouts.bind(function (ls) {
  4497. return ls.onBottomRtl.map(function (f) {
  4498. return f(elem);
  4499. });
  4500. }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl);
  4501. var f = onDirection(ltr, rtl);
  4502. return f(elem);
  4503. };
  4504. var placement = function (component, anchorInfo, origin) {
  4505. var hotspot = anchorInfo.hotspot;
  4506. var anchorBox = toBox(origin, hotspot.element());
  4507. var layouts = get$a(component.element(), anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Option.some(anchorInfo.hotspot.element()));
  4508. return Option.some(nu$9({
  4509. anchorBox: anchorBox,
  4510. bubble: anchorInfo.bubble.getOr(fallback()),
  4511. overrides: anchorInfo.overrides,
  4512. layouts: layouts,
  4513. placer: Option.none()
  4514. }));
  4515. };
  4516. var HotspotAnchor = [
  4517. strict$1('hotspot'),
  4518. option('bubble'),
  4519. defaulted$1('overrides', {}),
  4520. schema$1(),
  4521. output('placement', placement)
  4522. ];
  4523. var placement$1 = function (component, anchorInfo, origin) {
  4524. var pos = translate(origin, anchorInfo.x, anchorInfo.y);
  4525. var anchorBox = bounds$1(pos.left(), pos.top(), anchorInfo.width, anchorInfo.height);
  4526. var layouts = get$a(component.element(), anchorInfo, all$2(), allRtl(), all$2(), allRtl(), Option.none());
  4527. return Option.some(nu$9({
  4528. anchorBox: anchorBox,
  4529. bubble: anchorInfo.bubble,
  4530. overrides: anchorInfo.overrides,
  4531. layouts: layouts,
  4532. placer: Option.none()
  4533. }));
  4534. };
  4535. var MakeshiftAnchor = [
  4536. strict$1('x'),
  4537. strict$1('y'),
  4538. defaulted$1('height', 0),
  4539. defaulted$1('width', 0),
  4540. defaulted$1('bubble', fallback()),
  4541. defaulted$1('overrides', {}),
  4542. schema$1(),
  4543. output('placement', placement$1)
  4544. ];
  4545. var zeroWidth = '\uFEFF';
  4546. var nbsp = '\xA0';
  4547. var create$2 = function (start, soffset, finish, foffset) {
  4548. return {
  4549. start: constant(start),
  4550. soffset: constant(soffset),
  4551. finish: constant(finish),
  4552. foffset: constant(foffset)
  4553. };
  4554. };
  4555. var SimRange = { create: create$2 };
  4556. var adt$5 = Adt.generate([
  4557. { before: ['element'] },
  4558. {
  4559. on: [
  4560. 'element',
  4561. 'offset'
  4562. ]
  4563. },
  4564. { after: ['element'] }
  4565. ]);
  4566. var cata$2 = function (subject, onBefore, onOn, onAfter) {
  4567. return subject.fold(onBefore, onOn, onAfter);
  4568. };
  4569. var getStart = function (situ) {
  4570. return situ.fold(identity, identity, identity);
  4571. };
  4572. var before$2 = adt$5.before;
  4573. var on = adt$5.on;
  4574. var after$1 = adt$5.after;
  4575. var Situ = {
  4576. before: before$2,
  4577. on: on,
  4578. after: after$1,
  4579. cata: cata$2,
  4580. getStart: getStart
  4581. };
  4582. var adt$6 = Adt.generate([
  4583. { domRange: ['rng'] },
  4584. {
  4585. relative: [
  4586. 'startSitu',
  4587. 'finishSitu'
  4588. ]
  4589. },
  4590. {
  4591. exact: [
  4592. 'start',
  4593. 'soffset',
  4594. 'finish',
  4595. 'foffset'
  4596. ]
  4597. }
  4598. ]);
  4599. var exactFromRange = function (simRange) {
  4600. return adt$6.exact(simRange.start(), simRange.soffset(), simRange.finish(), simRange.foffset());
  4601. };
  4602. var getStart$1 = function (selection) {
  4603. return selection.match({
  4604. domRange: function (rng) {
  4605. return Element.fromDom(rng.startContainer);
  4606. },
  4607. relative: function (startSitu, _finishSitu) {
  4608. return Situ.getStart(startSitu);
  4609. },
  4610. exact: function (start, _soffset, _finish, _foffset) {
  4611. return start;
  4612. }
  4613. });
  4614. };
  4615. var domRange = adt$6.domRange;
  4616. var relative$1 = adt$6.relative;
  4617. var exact = adt$6.exact;
  4618. var getWin = function (selection) {
  4619. var start = getStart$1(selection);
  4620. return defaultView(start);
  4621. };
  4622. var range$1 = SimRange.create;
  4623. var Selection = {
  4624. domRange: domRange,
  4625. relative: relative$1,
  4626. exact: exact,
  4627. exactFromRange: exactFromRange,
  4628. getWin: getWin,
  4629. range: range$1
  4630. };
  4631. var setStart = function (rng, situ) {
  4632. situ.fold(function (e) {
  4633. rng.setStartBefore(e.dom());
  4634. }, function (e, o) {
  4635. rng.setStart(e.dom(), o);
  4636. }, function (e) {
  4637. rng.setStartAfter(e.dom());
  4638. });
  4639. };
  4640. var setFinish = function (rng, situ) {
  4641. situ.fold(function (e) {
  4642. rng.setEndBefore(e.dom());
  4643. }, function (e, o) {
  4644. rng.setEnd(e.dom(), o);
  4645. }, function (e) {
  4646. rng.setEndAfter(e.dom());
  4647. });
  4648. };
  4649. var relativeToNative = function (win, startSitu, finishSitu) {
  4650. var range = win.document.createRange();
  4651. setStart(range, startSitu);
  4652. setFinish(range, finishSitu);
  4653. return range;
  4654. };
  4655. var exactToNative = function (win, start, soffset, finish, foffset) {
  4656. var rng = win.document.createRange();
  4657. rng.setStart(start.dom(), soffset);
  4658. rng.setEnd(finish.dom(), foffset);
  4659. return rng;
  4660. };
  4661. var toRect = function (rect) {
  4662. return {
  4663. left: constant(rect.left),
  4664. top: constant(rect.top),
  4665. right: constant(rect.right),
  4666. bottom: constant(rect.bottom),
  4667. width: constant(rect.width),
  4668. height: constant(rect.height)
  4669. };
  4670. };
  4671. var getFirstRect = function (rng) {
  4672. var rects = rng.getClientRects();
  4673. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  4674. return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
  4675. };
  4676. var adt$7 = Adt.generate([
  4677. {
  4678. ltr: [
  4679. 'start',
  4680. 'soffset',
  4681. 'finish',
  4682. 'foffset'
  4683. ]
  4684. },
  4685. {
  4686. rtl: [
  4687. 'start',
  4688. 'soffset',
  4689. 'finish',
  4690. 'foffset'
  4691. ]
  4692. }
  4693. ]);
  4694. var fromRange = function (win, type, range) {
  4695. return type(Element.fromDom(range.startContainer), range.startOffset, Element.fromDom(range.endContainer), range.endOffset);
  4696. };
  4697. var getRanges = function (win, selection) {
  4698. return selection.match({
  4699. domRange: function (rng) {
  4700. return {
  4701. ltr: constant(rng),
  4702. rtl: Option.none
  4703. };
  4704. },
  4705. relative: function (startSitu, finishSitu) {
  4706. return {
  4707. ltr: cached(function () {
  4708. return relativeToNative(win, startSitu, finishSitu);
  4709. }),
  4710. rtl: cached(function () {
  4711. return Option.some(relativeToNative(win, finishSitu, startSitu));
  4712. })
  4713. };
  4714. },
  4715. exact: function (start, soffset, finish, foffset) {
  4716. return {
  4717. ltr: cached(function () {
  4718. return exactToNative(win, start, soffset, finish, foffset);
  4719. }),
  4720. rtl: cached(function () {
  4721. return Option.some(exactToNative(win, finish, foffset, start, soffset));
  4722. })
  4723. };
  4724. }
  4725. });
  4726. };
  4727. var doDiagnose = function (win, ranges) {
  4728. var rng = ranges.ltr();
  4729. if (rng.collapsed) {
  4730. var reversed = ranges.rtl().filter(function (rev) {
  4731. return rev.collapsed === false;
  4732. });
  4733. return reversed.map(function (rev) {
  4734. return adt$7.rtl(Element.fromDom(rev.endContainer), rev.endOffset, Element.fromDom(rev.startContainer), rev.startOffset);
  4735. }).getOrThunk(function () {
  4736. return fromRange(win, adt$7.ltr, rng);
  4737. });
  4738. } else {
  4739. return fromRange(win, adt$7.ltr, rng);
  4740. }
  4741. };
  4742. var diagnose = function (win, selection) {
  4743. var ranges = getRanges(win, selection);
  4744. return doDiagnose(win, ranges);
  4745. };
  4746. var asLtrRange = function (win, selection) {
  4747. var diagnosis = diagnose(win, selection);
  4748. return diagnosis.match({
  4749. ltr: function (start, soffset, finish, foffset) {
  4750. var rng = win.document.createRange();
  4751. rng.setStart(start.dom(), soffset);
  4752. rng.setEnd(finish.dom(), foffset);
  4753. return rng;
  4754. },
  4755. rtl: function (start, soffset, finish, foffset) {
  4756. var rng = win.document.createRange();
  4757. rng.setStart(finish.dom(), foffset);
  4758. rng.setEnd(start.dom(), soffset);
  4759. return rng;
  4760. }
  4761. });
  4762. };
  4763. var ltr = adt$7.ltr;
  4764. var rtl = adt$7.rtl;
  4765. function NodeValue (is, name) {
  4766. var get = function (element) {
  4767. if (!is(element)) {
  4768. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  4769. }
  4770. return getOption(element).getOr('');
  4771. };
  4772. var getOption = function (element) {
  4773. return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
  4774. };
  4775. var set = function (element, value) {
  4776. if (!is(element)) {
  4777. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  4778. }
  4779. element.dom().nodeValue = value;
  4780. };
  4781. return {
  4782. get: get,
  4783. getOption: getOption,
  4784. set: set
  4785. };
  4786. }
  4787. var api$2 = NodeValue(isText, 'text');
  4788. var get$b = function (element) {
  4789. return api$2.get(element);
  4790. };
  4791. var getOption = function (element) {
  4792. return api$2.getOption(element);
  4793. };
  4794. var getEnd = function (element) {
  4795. return name(element) === 'img' ? 1 : getOption(element).fold(function () {
  4796. return children(element).length;
  4797. }, function (v) {
  4798. return v.length;
  4799. });
  4800. };
  4801. var isTextNodeWithCursorPosition = function (el) {
  4802. return getOption(el).filter(function (text) {
  4803. return text.trim().length !== 0 || text.indexOf(nbsp) > -1;
  4804. }).isSome();
  4805. };
  4806. var elementsWithCursorPosition = [
  4807. 'img',
  4808. 'br'
  4809. ];
  4810. var isCursorPosition = function (elem) {
  4811. var hasCursorPosition = isTextNodeWithCursorPosition(elem);
  4812. return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
  4813. };
  4814. var last$1 = function (element) {
  4815. return descendantRtl(element, isCursorPosition);
  4816. };
  4817. var descendantRtl = function (scope, predicate) {
  4818. var descend = function (element) {
  4819. var children$1 = children(element);
  4820. for (var i = children$1.length - 1; i >= 0; i--) {
  4821. var child = children$1[i];
  4822. if (predicate(child)) {
  4823. return Option.some(child);
  4824. }
  4825. var res = descend(child);
  4826. if (res.isSome()) {
  4827. return res;
  4828. }
  4829. }
  4830. return Option.none();
  4831. };
  4832. return descend(scope);
  4833. };
  4834. var descendants = function (scope, selector) {
  4835. return all(selector, scope);
  4836. };
  4837. var makeRange = function (start, soffset, finish, foffset) {
  4838. var doc = owner(start);
  4839. var rng = doc.dom().createRange();
  4840. rng.setStart(start.dom(), soffset);
  4841. rng.setEnd(finish.dom(), foffset);
  4842. return rng;
  4843. };
  4844. var after$2 = function (start, soffset, finish, foffset) {
  4845. var r = makeRange(start, soffset, finish, foffset);
  4846. var same = eq$1(start, finish) && soffset === foffset;
  4847. return r.collapsed && !same;
  4848. };
  4849. var readRange = function (selection) {
  4850. if (selection.rangeCount > 0) {
  4851. var firstRng = selection.getRangeAt(0);
  4852. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  4853. return Option.some(SimRange.create(Element.fromDom(firstRng.startContainer), firstRng.startOffset, Element.fromDom(lastRng.endContainer), lastRng.endOffset));
  4854. } else {
  4855. return Option.none();
  4856. }
  4857. };
  4858. var doGetExact = function (selection) {
  4859. var anchor = Element.fromDom(selection.anchorNode);
  4860. var focus = Element.fromDom(selection.focusNode);
  4861. return after$2(anchor, selection.anchorOffset, focus, selection.focusOffset) ? Option.some(SimRange.create(anchor, selection.anchorOffset, focus, selection.focusOffset)) : readRange(selection);
  4862. };
  4863. var getExact = function (win) {
  4864. return Option.from(win.getSelection()).filter(function (sel) {
  4865. return sel.rangeCount > 0;
  4866. }).bind(doGetExact);
  4867. };
  4868. var getFirstRect$1 = function (win, selection) {
  4869. var rng = asLtrRange(win, selection);
  4870. return getFirstRect(rng);
  4871. };
  4872. var point = function (element, offset) {
  4873. return {
  4874. element: element,
  4875. offset: offset
  4876. };
  4877. };
  4878. var descendOnce = function (element, offset) {
  4879. var children$1 = children(element);
  4880. if (children$1.length === 0) {
  4881. return point(element, offset);
  4882. } else if (offset < children$1.length) {
  4883. return point(children$1[offset], 0);
  4884. } else {
  4885. var last = children$1[children$1.length - 1];
  4886. var len = isText(last) ? get$b(last).length : children(last).length;
  4887. return point(last, len);
  4888. }
  4889. };
  4890. var adt$8 = Adt.generate([
  4891. { screen: ['point'] },
  4892. {
  4893. absolute: [
  4894. 'point',
  4895. 'scrollLeft',
  4896. 'scrollTop'
  4897. ]
  4898. }
  4899. ]);
  4900. var toFixed = function (pos) {
  4901. return pos.fold(identity, function (point, scrollLeft, scrollTop) {
  4902. return point.translate(-scrollLeft, -scrollTop);
  4903. });
  4904. };
  4905. var toAbsolute = function (pos) {
  4906. return pos.fold(identity, identity);
  4907. };
  4908. var sum = function (points) {
  4909. return foldl(points, function (b, a) {
  4910. return b.translate(a.left(), a.top());
  4911. }, Position(0, 0));
  4912. };
  4913. var sumAsFixed = function (positions) {
  4914. var points = map(positions, toFixed);
  4915. return sum(points);
  4916. };
  4917. var sumAsAbsolute = function (positions) {
  4918. var points = map(positions, toAbsolute);
  4919. return sum(points);
  4920. };
  4921. var screen = adt$8.screen;
  4922. var absolute$2 = adt$8.absolute;
  4923. var getOffset = function (component, origin, anchorInfo) {
  4924. var win = defaultView(anchorInfo.root).dom();
  4925. var hasSameOwner = function (frame) {
  4926. var frameOwner = owner(frame);
  4927. var compOwner = owner(component.element());
  4928. return eq$1(frameOwner, compOwner);
  4929. };
  4930. return Option.from(win.frameElement).map(Element.fromDom).filter(hasSameOwner).map(absolute);
  4931. };
  4932. var getRootPoint = function (component, origin, anchorInfo) {
  4933. var doc = owner(component.element());
  4934. var outerScroll = get$8(doc);
  4935. var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll);
  4936. return absolute$2(offset, outerScroll.left(), outerScroll.top());
  4937. };
  4938. var capRect = function (left, top, width, height) {
  4939. var newLeft = left, newTop = top, newWidth = width, newHeight = height;
  4940. if (left < 0) {
  4941. newLeft = 0;
  4942. newWidth = width + left;
  4943. }
  4944. if (top < 0) {
  4945. newTop = 0;
  4946. newHeight = height + top;
  4947. }
  4948. var point = screen(Position(newLeft, newTop));
  4949. return Option.some(pointed(point, newWidth, newHeight));
  4950. };
  4951. var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) {
  4952. return optBox.map(function (box) {
  4953. var points = [
  4954. rootPoint,
  4955. box.point
  4956. ];
  4957. var topLeft = cata$1(origin, function () {
  4958. return sumAsAbsolute(points);
  4959. }, function () {
  4960. return sumAsAbsolute(points);
  4961. }, function () {
  4962. return sumAsFixed(points);
  4963. });
  4964. var anchorBox = rect(topLeft.left(), topLeft.top(), box.width, box.height);
  4965. var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove();
  4966. var layoutsRtl = anchorInfo.showAbove ? belowOrAboveRtl() : belowOrAboveRtl();
  4967. var layouts = get$a(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Option.none());
  4968. return nu$9({
  4969. anchorBox: anchorBox,
  4970. bubble: anchorInfo.bubble.getOr(fallback()),
  4971. overrides: anchorInfo.overrides,
  4972. layouts: layouts,
  4973. placer: Option.none()
  4974. });
  4975. });
  4976. };
  4977. var point$1 = function (element, offset) {
  4978. return {
  4979. element: element,
  4980. offset: offset
  4981. };
  4982. };
  4983. var descendOnce$1 = function (element, offset) {
  4984. return isText(element) ? point$1(element, offset) : descendOnce(element, offset);
  4985. };
  4986. var getAnchorSelection = function (win, anchorInfo) {
  4987. var getSelection = anchorInfo.getSelection.getOrThunk(function () {
  4988. return function () {
  4989. return getExact(win);
  4990. };
  4991. });
  4992. return getSelection().map(function (sel) {
  4993. var modStart = descendOnce$1(sel.start(), sel.soffset());
  4994. var modFinish = descendOnce$1(sel.finish(), sel.foffset());
  4995. return Selection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
  4996. });
  4997. };
  4998. var placement$2 = function (component, anchorInfo, origin) {
  4999. var win = defaultView(anchorInfo.root).dom();
  5000. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5001. var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5002. var optRect = getFirstRect$1(win, Selection.exactFromRange(sel)).orThunk(function () {
  5003. var x = Element.fromText(zeroWidth);
  5004. before(sel.start(), x);
  5005. return getFirstRect$1(win, Selection.exact(x, 0, x, 1)).map(function (rect) {
  5006. remove(x);
  5007. return rect;
  5008. });
  5009. });
  5010. return optRect.bind(function (rawRect) {
  5011. return capRect(rawRect.left(), rawRect.top(), rawRect.width(), rawRect.height());
  5012. });
  5013. });
  5014. var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) {
  5015. return isElement(sel.start()) ? Option.some(sel.start()) : parent(sel.start());
  5016. });
  5017. var elem = targetElement.getOr(component.element());
  5018. return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
  5019. };
  5020. var SelectionAnchor = [
  5021. option('getSelection'),
  5022. strict$1('root'),
  5023. option('bubble'),
  5024. schema$1(),
  5025. defaulted$1('overrides', {}),
  5026. defaulted$1('showAbove', false),
  5027. output('placement', placement$2)
  5028. ];
  5029. var placement$3 = function (component, anchorInfo, origin) {
  5030. var rootPoint = getRootPoint(component, origin, anchorInfo);
  5031. return anchorInfo.node.bind(function (target) {
  5032. var rect = target.dom().getBoundingClientRect();
  5033. var nodeBox = capRect(rect.left, rect.top, rect.width, rect.height);
  5034. var elem = anchorInfo.node.getOr(component.element());
  5035. return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem);
  5036. });
  5037. };
  5038. var NodeAnchor = [
  5039. strict$1('node'),
  5040. strict$1('root'),
  5041. option('bubble'),
  5042. schema$1(),
  5043. defaulted$1('overrides', {}),
  5044. defaulted$1('showAbove', false),
  5045. output('placement', placement$3)
  5046. ];
  5047. var eastX$1 = function (anchor) {
  5048. return anchor.x + anchor.width;
  5049. };
  5050. var westX$1 = function (anchor, element) {
  5051. return anchor.x - element.width;
  5052. };
  5053. var northY$1 = function (anchor, element) {
  5054. return anchor.y - element.height + anchor.height;
  5055. };
  5056. var southY$1 = function (anchor) {
  5057. return anchor.y;
  5058. };
  5059. var southeast$2 = function (anchor, element, bubbles) {
  5060. return nu$7(eastX$1(anchor), southY$1(anchor), bubbles.southeast(), southeast(), boundsRestriction(anchor, {
  5061. left: 0,
  5062. top: 2
  5063. }), 'link-layout-se');
  5064. };
  5065. var southwest$2 = function (anchor, element, bubbles) {
  5066. return nu$7(westX$1(anchor, element), southY$1(anchor), bubbles.southwest(), southwest(), boundsRestriction(anchor, {
  5067. right: 1,
  5068. top: 2
  5069. }), 'link-layout-sw');
  5070. };
  5071. var northeast$2 = function (anchor, element, bubbles) {
  5072. return nu$7(eastX$1(anchor), northY$1(anchor, element), bubbles.northeast(), northeast(), boundsRestriction(anchor, {
  5073. left: 0,
  5074. bottom: 3
  5075. }), 'link-layout-ne');
  5076. };
  5077. var northwest$2 = function (anchor, element, bubbles) {
  5078. return nu$7(westX$1(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest(), boundsRestriction(anchor, {
  5079. right: 1,
  5080. bottom: 3
  5081. }), 'link-layout-nw');
  5082. };
  5083. var all$3 = function () {
  5084. return [
  5085. southeast$2,
  5086. southwest$2,
  5087. northeast$2,
  5088. northwest$2
  5089. ];
  5090. };
  5091. var allRtl$1 = function () {
  5092. return [
  5093. southwest$2,
  5094. southeast$2,
  5095. northwest$2,
  5096. northeast$2
  5097. ];
  5098. };
  5099. var placement$4 = function (component, submenuInfo, origin) {
  5100. var anchorBox = toBox(origin, submenuInfo.item.element());
  5101. var layouts = get$a(component.element(), submenuInfo, all$3(), allRtl$1(), all$3(), allRtl$1(), Option.none());
  5102. return Option.some(nu$9({
  5103. anchorBox: anchorBox,
  5104. bubble: fallback(),
  5105. overrides: submenuInfo.overrides,
  5106. layouts: layouts,
  5107. placer: Option.none()
  5108. }));
  5109. };
  5110. var SubmenuAnchor = [
  5111. strict$1('item'),
  5112. schema$1(),
  5113. defaulted$1('overrides', {}),
  5114. output('placement', placement$4)
  5115. ];
  5116. var AnchorSchema = choose$1('anchor', {
  5117. selection: SelectionAnchor,
  5118. node: NodeAnchor,
  5119. hotspot: HotspotAnchor,
  5120. submenu: SubmenuAnchor,
  5121. makeshift: MakeshiftAnchor
  5122. });
  5123. var getFixedOrigin = function () {
  5124. var html = domGlobals.document.documentElement;
  5125. return fixed(0, 0, html.clientWidth, html.clientHeight);
  5126. };
  5127. var getRelativeOrigin = function (component) {
  5128. var position = absolute(component.element());
  5129. var bounds = component.element().dom().getBoundingClientRect();
  5130. return relative(position.left(), position.top(), bounds.width, bounds.height);
  5131. };
  5132. var place = function (component, origin, anchoring, getBounds, placee) {
  5133. var anchor = box$1(anchoring.anchorBox, origin);
  5134. simple(anchor, placee.element(), anchoring.bubble, anchoring.layouts, getBounds, anchoring.overrides);
  5135. };
  5136. var position$1 = function (component, posConfig, posState, anchor, placee) {
  5137. positionWithin(component, posConfig, posState, anchor, placee, Option.none());
  5138. };
  5139. var positionWithin = function (component, posConfig, posState, anchor, placee, boxElement) {
  5140. var boundsBox = boxElement.map(box);
  5141. return positionWithinBounds(component, posConfig, posState, anchor, placee, boundsBox);
  5142. };
  5143. var positionWithinBounds = function (component, posConfig, posState, anchor, placee, bounds) {
  5144. var anchorage = asRawOrDie('positioning anchor.info', AnchorSchema, anchor);
  5145. preserve(function () {
  5146. set$2(placee.element(), 'position', 'fixed');
  5147. var oldVisibility = getRaw(placee.element(), 'visibility');
  5148. set$2(placee.element(), 'visibility', 'hidden');
  5149. var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component);
  5150. var placer = anchorage.placement;
  5151. var getBounds = bounds.map(constant).or(posConfig.getBounds);
  5152. placer(component, anchorage, origin).each(function (anchoring) {
  5153. var doPlace = anchoring.placer.getOr(place);
  5154. doPlace(component, origin, anchoring, getBounds, placee);
  5155. });
  5156. oldVisibility.fold(function () {
  5157. remove$6(placee.element(), 'visibility');
  5158. }, function (vis) {
  5159. set$2(placee.element(), 'visibility', vis);
  5160. });
  5161. if (getRaw(placee.element(), 'left').isNone() && getRaw(placee.element(), 'top').isNone() && getRaw(placee.element(), 'right').isNone() && getRaw(placee.element(), 'bottom').isNone() && getRaw(placee.element(), 'position').is('fixed')) {
  5162. remove$6(placee.element(), 'position');
  5163. }
  5164. }, placee.element());
  5165. };
  5166. var getMode = function (component, pConfig, _pState) {
  5167. return pConfig.useFixed() ? 'fixed' : 'absolute';
  5168. };
  5169. var PositionApis = /*#__PURE__*/Object.freeze({
  5170. __proto__: null,
  5171. position: position$1,
  5172. positionWithin: positionWithin,
  5173. positionWithinBounds: positionWithinBounds,
  5174. getMode: getMode
  5175. });
  5176. var PositionSchema = [
  5177. defaulted$1('useFixed', never),
  5178. option('getBounds')
  5179. ];
  5180. var Positioning = create$1({
  5181. fields: PositionSchema,
  5182. name: 'positioning',
  5183. active: ActivePosition,
  5184. apis: PositionApis
  5185. });
  5186. var fireDetaching = function (component) {
  5187. emit(component, detachedFromDom());
  5188. var children = component.components();
  5189. each(children, fireDetaching);
  5190. };
  5191. var fireAttaching = function (component) {
  5192. var children = component.components();
  5193. each(children, fireAttaching);
  5194. emit(component, attachedToDom());
  5195. };
  5196. var attach = function (parent, child) {
  5197. append(parent.element(), child.element());
  5198. };
  5199. var detachChildren = function (component) {
  5200. each(component.components(), function (childComp) {
  5201. return remove(childComp.element());
  5202. });
  5203. empty(component.element());
  5204. component.syncComponents();
  5205. };
  5206. var replaceChildren = function (component, newChildren) {
  5207. var subs = component.components();
  5208. detachChildren(component);
  5209. var deleted = difference(subs, newChildren);
  5210. each(deleted, function (comp) {
  5211. fireDetaching(comp);
  5212. component.getSystem().removeFromWorld(comp);
  5213. });
  5214. each(newChildren, function (childComp) {
  5215. if (!childComp.getSystem().isConnected()) {
  5216. component.getSystem().addToWorld(childComp);
  5217. attach(component, childComp);
  5218. if (inBody(component.element())) {
  5219. fireAttaching(childComp);
  5220. }
  5221. } else {
  5222. attach(component, childComp);
  5223. }
  5224. component.syncComponents();
  5225. });
  5226. };
  5227. var attach$1 = function (parent, child) {
  5228. attachWith(parent, child, append);
  5229. };
  5230. var attachWith = function (parent, child, insertion) {
  5231. parent.getSystem().addToWorld(child);
  5232. insertion(parent.element(), child.element());
  5233. if (inBody(parent.element())) {
  5234. fireAttaching(child);
  5235. }
  5236. parent.syncComponents();
  5237. };
  5238. var doDetach = function (component) {
  5239. fireDetaching(component);
  5240. remove(component.element());
  5241. component.getSystem().removeFromWorld(component);
  5242. };
  5243. var detach = function (component) {
  5244. var parent$1 = parent(component.element()).bind(function (p) {
  5245. return component.getSystem().getByDom(p).toOption();
  5246. });
  5247. doDetach(component);
  5248. parent$1.each(function (p) {
  5249. p.syncComponents();
  5250. });
  5251. };
  5252. var detachChildren$1 = function (component) {
  5253. var subs = component.components();
  5254. each(subs, doDetach);
  5255. empty(component.element());
  5256. component.syncComponents();
  5257. };
  5258. var attachSystem = function (element, guiSystem) {
  5259. attachSystemWith(element, guiSystem, append);
  5260. };
  5261. var attachSystemAfter = function (element, guiSystem) {
  5262. attachSystemWith(element, guiSystem, after);
  5263. };
  5264. var attachSystemWith = function (element, guiSystem, inserter) {
  5265. inserter(element, guiSystem.element());
  5266. var children$1 = children(guiSystem.element());
  5267. each(children$1, function (child) {
  5268. guiSystem.getByDom(child).each(fireAttaching);
  5269. });
  5270. };
  5271. var detachSystem = function (guiSystem) {
  5272. var children$1 = children(guiSystem.element());
  5273. each(children$1, function (child) {
  5274. guiSystem.getByDom(child).each(fireDetaching);
  5275. });
  5276. remove(guiSystem.element());
  5277. };
  5278. var rebuild = function (sandbox, sConfig, sState, data) {
  5279. sState.get().each(function (_data) {
  5280. detachChildren$1(sandbox);
  5281. });
  5282. var point = sConfig.getAttachPoint(sandbox);
  5283. attach$1(point, sandbox);
  5284. var built = sandbox.getSystem().build(data);
  5285. attach$1(sandbox, built);
  5286. sState.set(built);
  5287. return built;
  5288. };
  5289. var open = function (sandbox, sConfig, sState, data) {
  5290. var newState = rebuild(sandbox, sConfig, sState, data);
  5291. sConfig.onOpen(sandbox, newState);
  5292. return newState;
  5293. };
  5294. var setContent = function (sandbox, sConfig, sState, data) {
  5295. return sState.get().map(function () {
  5296. return rebuild(sandbox, sConfig, sState, data);
  5297. });
  5298. };
  5299. var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) {
  5300. cloak(sandbox, sConfig);
  5301. open(sandbox, sConfig, sState, data);
  5302. transaction();
  5303. decloak(sandbox, sConfig);
  5304. };
  5305. var close = function (sandbox, sConfig, sState) {
  5306. sState.get().each(function (data) {
  5307. detachChildren$1(sandbox);
  5308. detach(sandbox);
  5309. sConfig.onClose(sandbox, data);
  5310. sState.clear();
  5311. });
  5312. };
  5313. var isOpen = function (_sandbox, _sConfig, sState) {
  5314. return sState.isOpen();
  5315. };
  5316. var isPartOf$1 = function (sandbox, sConfig, sState, queryElem) {
  5317. return isOpen(sandbox, sConfig, sState) && sState.get().exists(function (data) {
  5318. return sConfig.isPartOf(sandbox, data, queryElem);
  5319. });
  5320. };
  5321. var getState = function (_sandbox, _sConfig, sState) {
  5322. return sState.get();
  5323. };
  5324. var store = function (sandbox, cssKey, attr, newValue) {
  5325. getRaw(sandbox.element(), cssKey).fold(function () {
  5326. remove$1(sandbox.element(), attr);
  5327. }, function (v) {
  5328. set$1(sandbox.element(), attr, v);
  5329. });
  5330. set$2(sandbox.element(), cssKey, newValue);
  5331. };
  5332. var restore = function (sandbox, cssKey, attr) {
  5333. getOpt(sandbox.element(), attr).fold(function () {
  5334. return remove$6(sandbox.element(), cssKey);
  5335. }, function (oldValue) {
  5336. return set$2(sandbox.element(), cssKey, oldValue);
  5337. });
  5338. };
  5339. var cloak = function (sandbox, sConfig, _sState) {
  5340. var sink = sConfig.getAttachPoint(sandbox);
  5341. set$2(sandbox.element(), 'position', Positioning.getMode(sink));
  5342. store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden');
  5343. };
  5344. var hasPosition = function (element) {
  5345. return exists([
  5346. 'top',
  5347. 'left',
  5348. 'right',
  5349. 'bottom'
  5350. ], function (pos) {
  5351. return getRaw(element, pos).isSome();
  5352. });
  5353. };
  5354. var decloak = function (sandbox, sConfig, _sState) {
  5355. if (!hasPosition(sandbox.element())) {
  5356. remove$6(sandbox.element(), 'position');
  5357. }
  5358. restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr);
  5359. };
  5360. var SandboxApis = /*#__PURE__*/Object.freeze({
  5361. __proto__: null,
  5362. cloak: cloak,
  5363. decloak: decloak,
  5364. open: open,
  5365. openWhileCloaked: openWhileCloaked,
  5366. close: close,
  5367. isOpen: isOpen,
  5368. isPartOf: isPartOf$1,
  5369. getState: getState,
  5370. setContent: setContent
  5371. });
  5372. var events$2 = function (sandboxConfig, sandboxState) {
  5373. return derive([run(sandboxClose(), function (sandbox, _simulatedEvent) {
  5374. close(sandbox, sandboxConfig, sandboxState);
  5375. })]);
  5376. };
  5377. var ActiveSandbox = /*#__PURE__*/Object.freeze({
  5378. __proto__: null,
  5379. events: events$2
  5380. });
  5381. var SandboxSchema = [
  5382. onHandler('onOpen'),
  5383. onHandler('onClose'),
  5384. strict$1('isPartOf'),
  5385. strict$1('getAttachPoint'),
  5386. defaulted$1('cloakVisibilityAttr', 'data-precloak-visibility')
  5387. ];
  5388. var init = function () {
  5389. var contents = Cell(Option.none());
  5390. var readState = constant('not-implemented');
  5391. var isOpen = function () {
  5392. return contents.get().isSome();
  5393. };
  5394. var set = function (comp) {
  5395. contents.set(Option.some(comp));
  5396. };
  5397. var get = function () {
  5398. return contents.get();
  5399. };
  5400. var clear = function () {
  5401. contents.set(Option.none());
  5402. };
  5403. return nu$5({
  5404. readState: readState,
  5405. isOpen: isOpen,
  5406. clear: clear,
  5407. set: set,
  5408. get: get
  5409. });
  5410. };
  5411. var SandboxState = /*#__PURE__*/Object.freeze({
  5412. __proto__: null,
  5413. init: init
  5414. });
  5415. var Sandboxing = create$1({
  5416. fields: SandboxSchema,
  5417. name: 'sandboxing',
  5418. active: ActiveSandbox,
  5419. apis: SandboxApis,
  5420. state: SandboxState
  5421. });
  5422. var dismissPopups = constant('dismiss.popups');
  5423. var repositionPopups = constant('reposition.popups');
  5424. var mouseReleased = constant('mouse.released');
  5425. var schema$2 = objOfOnly([
  5426. defaulted$1('isExtraPart', constant(false)),
  5427. optionObjOf('fireEventInstead', [defaulted$1('event', dismissRequested())])
  5428. ]);
  5429. var receivingChannel = function (rawSpec) {
  5430. var _a;
  5431. var detail = asRawOrDie('Dismissal', schema$2, rawSpec);
  5432. return _a = {}, _a[dismissPopups()] = {
  5433. schema: objOfOnly([strict$1('target')]),
  5434. onReceive: function (sandbox, data) {
  5435. if (Sandboxing.isOpen(sandbox)) {
  5436. var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
  5437. if (!isPart) {
  5438. detail.fireEventInstead.fold(function () {
  5439. return Sandboxing.close(sandbox);
  5440. }, function (fe) {
  5441. return emit(sandbox, fe.event);
  5442. });
  5443. }
  5444. }
  5445. }
  5446. }, _a;
  5447. };
  5448. var schema$3 = objOfOnly([
  5449. optionObjOf('fireEventInstead', [defaulted$1('event', repositionRequested())]),
  5450. strictFunction('doReposition')
  5451. ]);
  5452. var receivingChannel$1 = function (rawSpec) {
  5453. var _a;
  5454. var detail = asRawOrDie('Reposition', schema$3, rawSpec);
  5455. return _a = {}, _a[repositionPopups()] = {
  5456. onReceive: function (sandbox) {
  5457. if (Sandboxing.isOpen(sandbox)) {
  5458. detail.fireEventInstead.fold(function () {
  5459. return detail.doReposition(sandbox);
  5460. }, function (fe) {
  5461. return emit(sandbox, fe.event);
  5462. });
  5463. }
  5464. }
  5465. }, _a;
  5466. };
  5467. var onLoad = function (component, repConfig, repState) {
  5468. repConfig.store.manager.onLoad(component, repConfig, repState);
  5469. };
  5470. var onUnload = function (component, repConfig, repState) {
  5471. repConfig.store.manager.onUnload(component, repConfig, repState);
  5472. };
  5473. var setValue = function (component, repConfig, repState, data) {
  5474. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5475. };
  5476. var getValue = function (component, repConfig, repState) {
  5477. return repConfig.store.manager.getValue(component, repConfig, repState);
  5478. };
  5479. var getState$1 = function (component, repConfig, repState) {
  5480. return repState;
  5481. };
  5482. var RepresentApis = /*#__PURE__*/Object.freeze({
  5483. __proto__: null,
  5484. onLoad: onLoad,
  5485. onUnload: onUnload,
  5486. setValue: setValue,
  5487. getValue: getValue,
  5488. getState: getState$1
  5489. });
  5490. var events$3 = function (repConfig, repState) {
  5491. var es = repConfig.resetOnDom ? [
  5492. runOnAttached(function (comp, _se) {
  5493. onLoad(comp, repConfig, repState);
  5494. }),
  5495. runOnDetached(function (comp, _se) {
  5496. onUnload(comp, repConfig, repState);
  5497. })
  5498. ] : [loadEvent(repConfig, repState, onLoad)];
  5499. return derive(es);
  5500. };
  5501. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5502. __proto__: null,
  5503. events: events$3
  5504. });
  5505. var memory = function () {
  5506. var data = Cell(null);
  5507. var readState = function () {
  5508. return {
  5509. mode: 'memory',
  5510. value: data.get()
  5511. };
  5512. };
  5513. var isNotSet = function () {
  5514. return data.get() === null;
  5515. };
  5516. var clear = function () {
  5517. data.set(null);
  5518. };
  5519. return nu$5({
  5520. set: data.set,
  5521. get: data.get,
  5522. isNotSet: isNotSet,
  5523. clear: clear,
  5524. readState: readState
  5525. });
  5526. };
  5527. var manual = function () {
  5528. var readState = function () {
  5529. };
  5530. return nu$5({ readState: readState });
  5531. };
  5532. var dataset = function () {
  5533. var dataByValue = Cell({});
  5534. var dataByText = Cell({});
  5535. var readState = function () {
  5536. return {
  5537. mode: 'dataset',
  5538. dataByValue: dataByValue.get(),
  5539. dataByText: dataByText.get()
  5540. };
  5541. };
  5542. var clear = function () {
  5543. dataByValue.set({});
  5544. dataByText.set({});
  5545. };
  5546. var lookup = function (itemString) {
  5547. return get(dataByValue.get(), itemString).orThunk(function () {
  5548. return get(dataByText.get(), itemString);
  5549. });
  5550. };
  5551. var update = function (items) {
  5552. var currentDataByValue = dataByValue.get();
  5553. var currentDataByText = dataByText.get();
  5554. var newDataByValue = {};
  5555. var newDataByText = {};
  5556. each(items, function (item) {
  5557. newDataByValue[item.value] = item;
  5558. get(item, 'meta').each(function (meta) {
  5559. get(meta, 'text').each(function (text) {
  5560. newDataByText[text] = item;
  5561. });
  5562. });
  5563. });
  5564. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5565. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5566. };
  5567. return nu$5({
  5568. readState: readState,
  5569. lookup: lookup,
  5570. update: update,
  5571. clear: clear
  5572. });
  5573. };
  5574. var init$1 = function (spec) {
  5575. return spec.store.manager.state(spec);
  5576. };
  5577. var RepresentState = /*#__PURE__*/Object.freeze({
  5578. __proto__: null,
  5579. memory: memory,
  5580. dataset: dataset,
  5581. manual: manual,
  5582. init: init$1
  5583. });
  5584. var setValue$1 = function (component, repConfig, repState, data) {
  5585. var store = repConfig.store;
  5586. repState.update([data]);
  5587. store.setValue(component, data);
  5588. repConfig.onSetValue(component, data);
  5589. };
  5590. var getValue$1 = function (component, repConfig, repState) {
  5591. var store = repConfig.store;
  5592. var key = store.getDataKey(component);
  5593. return repState.lookup(key).fold(function () {
  5594. return store.getFallbackEntry(key);
  5595. }, function (data) {
  5596. return data;
  5597. });
  5598. };
  5599. var onLoad$1 = function (component, repConfig, repState) {
  5600. var store = repConfig.store;
  5601. store.initialValue.each(function (data) {
  5602. setValue$1(component, repConfig, repState, data);
  5603. });
  5604. };
  5605. var onUnload$1 = function (component, repConfig, repState) {
  5606. repState.clear();
  5607. };
  5608. var DatasetStore = [
  5609. option('initialValue'),
  5610. strict$1('getFallbackEntry'),
  5611. strict$1('getDataKey'),
  5612. strict$1('setValue'),
  5613. output('manager', {
  5614. setValue: setValue$1,
  5615. getValue: getValue$1,
  5616. onLoad: onLoad$1,
  5617. onUnload: onUnload$1,
  5618. state: dataset
  5619. })
  5620. ];
  5621. var getValue$2 = function (component, repConfig, _repState) {
  5622. return repConfig.store.getValue(component);
  5623. };
  5624. var setValue$2 = function (component, repConfig, _repState, data) {
  5625. repConfig.store.setValue(component, data);
  5626. repConfig.onSetValue(component, data);
  5627. };
  5628. var onLoad$2 = function (component, repConfig, _repState) {
  5629. repConfig.store.initialValue.each(function (data) {
  5630. repConfig.store.setValue(component, data);
  5631. });
  5632. };
  5633. var ManualStore = [
  5634. strict$1('getValue'),
  5635. defaulted$1('setValue', noop),
  5636. option('initialValue'),
  5637. output('manager', {
  5638. setValue: setValue$2,
  5639. getValue: getValue$2,
  5640. onLoad: onLoad$2,
  5641. onUnload: noop,
  5642. state: NoState.init
  5643. })
  5644. ];
  5645. var setValue$3 = function (component, repConfig, repState, data) {
  5646. repState.set(data);
  5647. repConfig.onSetValue(component, data);
  5648. };
  5649. var getValue$3 = function (component, repConfig, repState) {
  5650. return repState.get();
  5651. };
  5652. var onLoad$3 = function (component, repConfig, repState) {
  5653. repConfig.store.initialValue.each(function (initVal) {
  5654. if (repState.isNotSet()) {
  5655. repState.set(initVal);
  5656. }
  5657. });
  5658. };
  5659. var onUnload$2 = function (component, repConfig, repState) {
  5660. repState.clear();
  5661. };
  5662. var MemoryStore = [
  5663. option('initialValue'),
  5664. output('manager', {
  5665. setValue: setValue$3,
  5666. getValue: getValue$3,
  5667. onLoad: onLoad$3,
  5668. onUnload: onUnload$2,
  5669. state: memory
  5670. })
  5671. ];
  5672. var RepresentSchema = [
  5673. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5674. memory: MemoryStore,
  5675. manual: ManualStore,
  5676. dataset: DatasetStore
  5677. })),
  5678. onHandler('onSetValue'),
  5679. defaulted$1('resetOnDom', false)
  5680. ];
  5681. var Representing = create$1({
  5682. fields: RepresentSchema,
  5683. name: 'representing',
  5684. active: ActiveRepresenting,
  5685. apis: RepresentApis,
  5686. extra: {
  5687. setValueFrom: function (component, source) {
  5688. var value = Representing.getValue(source);
  5689. Representing.setValue(component, value);
  5690. }
  5691. },
  5692. state: RepresentState
  5693. });
  5694. var field$1 = function (name, forbidden) {
  5695. return defaultedObjOf(name, {}, map(forbidden, function (f) {
  5696. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  5697. }).concat([state$1('dump', identity)]));
  5698. };
  5699. var get$c = function (data) {
  5700. return data.dump;
  5701. };
  5702. var augment = function (data, original) {
  5703. return __assign(__assign({}, data.dump), derive$1(original));
  5704. };
  5705. var SketchBehaviours = {
  5706. field: field$1,
  5707. augment: augment,
  5708. get: get$c
  5709. };
  5710. var _placeholder = 'placeholder';
  5711. var adt$9 = Adt.generate([
  5712. {
  5713. single: [
  5714. 'required',
  5715. 'valueThunk'
  5716. ]
  5717. },
  5718. {
  5719. multiple: [
  5720. 'required',
  5721. 'valueThunks'
  5722. ]
  5723. }
  5724. ]);
  5725. var isSubstituted = function (spec) {
  5726. return has(spec, 'uiType');
  5727. };
  5728. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  5729. if (owner.exists(function (o) {
  5730. return o !== compSpec.owner;
  5731. })) {
  5732. return adt$9.single(true, constant(compSpec));
  5733. }
  5734. return get(placeholders, compSpec.name).fold(function () {
  5735. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  5736. }, function (newSpec) {
  5737. return newSpec.replace();
  5738. });
  5739. };
  5740. var scan = function (owner, detail, compSpec, placeholders) {
  5741. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  5742. return subPlaceholder(owner, detail, compSpec, placeholders);
  5743. } else {
  5744. return adt$9.single(false, constant(compSpec));
  5745. }
  5746. };
  5747. var substitute = function (owner, detail, compSpec, placeholders) {
  5748. var base = scan(owner, detail, compSpec, placeholders);
  5749. return base.fold(function (req, valueThunk) {
  5750. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  5751. var childSpecs = get(value, 'components').getOr([]);
  5752. var substituted = bind(childSpecs, function (c) {
  5753. return substitute(owner, detail, c, placeholders);
  5754. });
  5755. return [__assign(__assign({}, value), { components: substituted })];
  5756. }, function (req, valuesThunk) {
  5757. if (isSubstituted(compSpec)) {
  5758. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  5759. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  5760. return preprocessor(values);
  5761. } else {
  5762. return valuesThunk(detail);
  5763. }
  5764. });
  5765. };
  5766. var substituteAll = function (owner, detail, components, placeholders) {
  5767. return bind(components, function (c) {
  5768. return substitute(owner, detail, c, placeholders);
  5769. });
  5770. };
  5771. var oneReplace = function (label, replacements) {
  5772. var called = false;
  5773. var used = function () {
  5774. return called;
  5775. };
  5776. var replace = function () {
  5777. if (called) {
  5778. throw new Error('Trying to use the same placeholder more than once: ' + label);
  5779. }
  5780. called = true;
  5781. return replacements;
  5782. };
  5783. var required = function () {
  5784. return replacements.fold(function (req, _) {
  5785. return req;
  5786. }, function (req, _) {
  5787. return req;
  5788. });
  5789. };
  5790. return {
  5791. name: constant(label),
  5792. required: required,
  5793. used: used,
  5794. replace: replace
  5795. };
  5796. };
  5797. var substitutePlaces = function (owner, detail, components, placeholders) {
  5798. var ps = map$1(placeholders, function (ph, name) {
  5799. return oneReplace(name, ph);
  5800. });
  5801. var outcome = substituteAll(owner, detail, components, ps);
  5802. each$1(ps, function (p) {
  5803. if (p.used() === false && p.required()) {
  5804. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  5805. }
  5806. });
  5807. return outcome;
  5808. };
  5809. var single = adt$9.single;
  5810. var multiple = adt$9.multiple;
  5811. var placeholder = constant(_placeholder);
  5812. var adt$a = Adt.generate([
  5813. { required: ['data'] },
  5814. { external: ['data'] },
  5815. { optional: ['data'] },
  5816. { group: ['data'] }
  5817. ]);
  5818. var fFactory = defaulted$1('factory', { sketch: identity });
  5819. var fSchema = defaulted$1('schema', []);
  5820. var fName = strict$1('name');
  5821. var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
  5822. return '<alloy.' + generate$1(typeSpec.name) + '>';
  5823. }), anyValue$1());
  5824. var fGroupSchema = state$1('schema', function () {
  5825. return [option('preprocess')];
  5826. });
  5827. var fDefaults = defaulted$1('defaults', constant({}));
  5828. var fOverrides = defaulted$1('overrides', constant({}));
  5829. var requiredSpec = objOf([
  5830. fFactory,
  5831. fSchema,
  5832. fName,
  5833. fPname,
  5834. fDefaults,
  5835. fOverrides
  5836. ]);
  5837. var externalSpec = objOf([
  5838. fFactory,
  5839. fSchema,
  5840. fName,
  5841. fDefaults,
  5842. fOverrides
  5843. ]);
  5844. var optionalSpec = objOf([
  5845. fFactory,
  5846. fSchema,
  5847. fName,
  5848. fPname,
  5849. fDefaults,
  5850. fOverrides
  5851. ]);
  5852. var groupSpec = objOf([
  5853. fFactory,
  5854. fGroupSchema,
  5855. fName,
  5856. strict$1('unit'),
  5857. fPname,
  5858. fDefaults,
  5859. fOverrides
  5860. ]);
  5861. var asNamedPart = function (part) {
  5862. return part.fold(Option.some, Option.none, Option.some, Option.some);
  5863. };
  5864. var name$1 = function (part) {
  5865. var get = function (data) {
  5866. return data.name;
  5867. };
  5868. return part.fold(get, get, get, get);
  5869. };
  5870. var asCommon = function (part) {
  5871. return part.fold(identity, identity, identity, identity);
  5872. };
  5873. var convert = function (adtConstructor, partSchema) {
  5874. return function (spec) {
  5875. var data = asRawOrDie('Converting part type', partSchema, spec);
  5876. return adtConstructor(data);
  5877. };
  5878. };
  5879. var required = convert(adt$a.required, requiredSpec);
  5880. var external$1 = convert(adt$a.external, externalSpec);
  5881. var optional = convert(adt$a.optional, optionalSpec);
  5882. var group = convert(adt$a.group, groupSpec);
  5883. var original = constant('entirety');
  5884. var PartType = /*#__PURE__*/Object.freeze({
  5885. __proto__: null,
  5886. required: required,
  5887. external: external$1,
  5888. optional: optional,
  5889. group: group,
  5890. asNamedPart: asNamedPart,
  5891. name: name$1,
  5892. asCommon: asCommon,
  5893. original: original
  5894. });
  5895. var combine$2 = function (detail, data, partSpec, partValidated) {
  5896. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  5897. };
  5898. var subs = function (owner, detail, parts) {
  5899. var internals = {};
  5900. var externals = {};
  5901. each(parts, function (part) {
  5902. part.fold(function (data) {
  5903. internals[data.pname] = single(true, function (detail, partSpec, partValidated) {
  5904. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5905. });
  5906. }, function (data) {
  5907. var partSpec = detail.parts[data.name];
  5908. externals[data.name] = constant(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  5909. }, function (data) {
  5910. internals[data.pname] = single(false, function (detail, partSpec, partValidated) {
  5911. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  5912. });
  5913. }, function (data) {
  5914. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  5915. var units = detail[data.name];
  5916. return map(units, function (u) {
  5917. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  5918. });
  5919. });
  5920. });
  5921. });
  5922. return {
  5923. internals: constant(internals),
  5924. externals: constant(externals)
  5925. };
  5926. };
  5927. var generate$4 = function (owner, parts) {
  5928. var r = {};
  5929. each(parts, function (part) {
  5930. asNamedPart(part).each(function (np) {
  5931. var g = doGenerateOne(owner, np.pname);
  5932. r[np.name] = function (config) {
  5933. var validated = asRawOrDie('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  5934. return __assign(__assign({}, g), {
  5935. config: config,
  5936. validated: validated
  5937. });
  5938. };
  5939. });
  5940. });
  5941. return r;
  5942. };
  5943. var doGenerateOne = function (owner, pname) {
  5944. return {
  5945. uiType: placeholder(),
  5946. owner: owner,
  5947. name: pname
  5948. };
  5949. };
  5950. var generateOne = function (owner, pname, config) {
  5951. return {
  5952. uiType: placeholder(),
  5953. owner: owner,
  5954. name: pname,
  5955. config: config,
  5956. validated: {}
  5957. };
  5958. };
  5959. var schemas = function (parts) {
  5960. return bind(parts, function (part) {
  5961. return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
  5962. return strictObjOf(data.name, data.schema.concat([snapshot(original())]));
  5963. }).toArray();
  5964. });
  5965. };
  5966. var names = function (parts) {
  5967. return map(parts, name$1);
  5968. };
  5969. var substitutes = function (owner, detail, parts) {
  5970. return subs(owner, detail, parts);
  5971. };
  5972. var components = function (owner, detail, internals) {
  5973. return substitutePlaces(Option.some(owner), detail, detail.components, internals);
  5974. };
  5975. var getPart = function (component, detail, partKey) {
  5976. var uid = detail.partUids[partKey];
  5977. return component.getSystem().getByUid(uid).toOption();
  5978. };
  5979. var getPartOrDie = function (component, detail, partKey) {
  5980. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  5981. };
  5982. var getParts = function (component, detail, partKeys) {
  5983. var r = {};
  5984. var uids = detail.partUids;
  5985. var system = component.getSystem();
  5986. each(partKeys, function (pk) {
  5987. r[pk] = constant(system.getByUid(uids[pk]));
  5988. });
  5989. return r;
  5990. };
  5991. var getAllParts = function (component, detail) {
  5992. var system = component.getSystem();
  5993. return map$1(detail.partUids, function (pUid, _k) {
  5994. return constant(system.getByUid(pUid));
  5995. });
  5996. };
  5997. var getAllPartNames = function (detail) {
  5998. return keys(detail.partUids);
  5999. };
  6000. var getPartsOrDie = function (component, detail, partKeys) {
  6001. var r = {};
  6002. var uids = detail.partUids;
  6003. var system = component.getSystem();
  6004. each(partKeys, function (pk) {
  6005. r[pk] = constant(system.getByUid(uids[pk]).getOrDie());
  6006. });
  6007. return r;
  6008. };
  6009. var defaultUids = function (baseUid, partTypes) {
  6010. var partNames = names(partTypes);
  6011. return wrapAll$1(map(partNames, function (pn) {
  6012. return {
  6013. key: pn,
  6014. value: baseUid + '-' + pn
  6015. };
  6016. }));
  6017. };
  6018. var defaultUidsSchema = function (partTypes) {
  6019. return field('partUids', 'partUids', mergeWithThunk(function (spec) {
  6020. return defaultUids(spec.uid, partTypes);
  6021. }), anyValue$1());
  6022. };
  6023. var AlloyParts = /*#__PURE__*/Object.freeze({
  6024. __proto__: null,
  6025. generate: generate$4,
  6026. generateOne: generateOne,
  6027. schemas: schemas,
  6028. names: names,
  6029. substitutes: substitutes,
  6030. components: components,
  6031. defaultUids: defaultUids,
  6032. defaultUidsSchema: defaultUidsSchema,
  6033. getAllParts: getAllParts,
  6034. getAllPartNames: getAllPartNames,
  6035. getPart: getPart,
  6036. getPartOrDie: getPartOrDie,
  6037. getParts: getParts,
  6038. getPartsOrDie: getPartsOrDie
  6039. });
  6040. var base = function (partSchemas, partUidsSchemas) {
  6041. var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
  6042. return ps.concat([
  6043. strict$1('uid'),
  6044. defaulted$1('dom', {}),
  6045. defaulted$1('components', []),
  6046. snapshot('originalSpec'),
  6047. defaulted$1('debug.sketcher', {})
  6048. ]).concat(partUidsSchemas);
  6049. };
  6050. var asRawOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
  6051. var baseS = base(partSchemas, partUidsSchemas);
  6052. return asRawOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  6053. };
  6054. var single$1 = function (owner, schema, factory, spec) {
  6055. var specWithUid = supplyUid(spec);
  6056. var detail = asRawOrDie$1(owner, schema, specWithUid, [], []);
  6057. return factory(detail, specWithUid);
  6058. };
  6059. var composite = function (owner, schema, partTypes, factory, spec) {
  6060. var specWithUid = supplyUid(spec);
  6061. var partSchemas = schemas(partTypes);
  6062. var partUidsSchema = defaultUidsSchema(partTypes);
  6063. var detail = asRawOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  6064. var subs = substitutes(owner, detail, partTypes);
  6065. var components$1 = components(owner, detail, subs.internals());
  6066. return factory(detail, components$1, specWithUid, subs.externals());
  6067. };
  6068. var hasUid = function (spec) {
  6069. return has(spec, 'uid');
  6070. };
  6071. var supplyUid = function (spec) {
  6072. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  6073. };
  6074. function isSketchSpec(spec) {
  6075. return spec.uid !== undefined;
  6076. }
  6077. var singleSchema = objOfOnly([
  6078. strict$1('name'),
  6079. strict$1('factory'),
  6080. strict$1('configFields'),
  6081. defaulted$1('apis', {}),
  6082. defaulted$1('extraApis', {})
  6083. ]);
  6084. var compositeSchema = objOfOnly([
  6085. strict$1('name'),
  6086. strict$1('factory'),
  6087. strict$1('configFields'),
  6088. strict$1('partFields'),
  6089. defaulted$1('apis', {}),
  6090. defaulted$1('extraApis', {})
  6091. ]);
  6092. var single$2 = function (rawConfig) {
  6093. var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  6094. var sketch = function (spec) {
  6095. return single$1(config.name, config.configFields, config.factory, spec);
  6096. };
  6097. var apis = map$1(config.apis, makeApi);
  6098. var extraApis = map$1(config.extraApis, function (f, k) {
  6099. return markAsExtraApi(f, k);
  6100. });
  6101. return __assign(__assign({
  6102. name: constant(config.name),
  6103. configFields: constant(config.configFields),
  6104. sketch: sketch
  6105. }, apis), extraApis);
  6106. };
  6107. var composite$1 = function (rawConfig) {
  6108. var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  6109. var sketch = function (spec) {
  6110. return composite(config.name, config.configFields, config.partFields, config.factory, spec);
  6111. };
  6112. var parts = generate$4(config.name, config.partFields);
  6113. var apis = map$1(config.apis, makeApi);
  6114. var extraApis = map$1(config.extraApis, function (f, k) {
  6115. return markAsExtraApi(f, k);
  6116. });
  6117. return __assign(__assign({
  6118. name: constant(config.name),
  6119. partFields: constant(config.partFields),
  6120. configFields: constant(config.configFields),
  6121. sketch: sketch,
  6122. parts: constant(parts)
  6123. }, apis), extraApis);
  6124. };
  6125. var cat = function (arr) {
  6126. var r = [];
  6127. var push = function (x) {
  6128. r.push(x);
  6129. };
  6130. for (var i = 0; i < arr.length; i++) {
  6131. arr[i].each(push);
  6132. }
  6133. return r;
  6134. };
  6135. var sequence = function (arr) {
  6136. var r = [];
  6137. for (var i = 0; i < arr.length; i++) {
  6138. var x = arr[i];
  6139. if (x.isSome()) {
  6140. r.push(x.getOrDie());
  6141. } else {
  6142. return Option.none();
  6143. }
  6144. }
  6145. return Option.some(r);
  6146. };
  6147. var lift2 = function (oa, ob, f) {
  6148. return oa.isSome() && ob.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie())) : Option.none();
  6149. };
  6150. var lift3 = function (oa, ob, oc, f) {
  6151. return oa.isSome() && ob.isSome() && oc.isSome() ? Option.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Option.none();
  6152. };
  6153. var inside = function (target) {
  6154. return name(target) === 'input' && get$2(target, 'type') !== 'radio' || name(target) === 'textarea';
  6155. };
  6156. var getCurrent = function (component, composeConfig, _composeState) {
  6157. return composeConfig.find(component);
  6158. };
  6159. var ComposeApis = /*#__PURE__*/Object.freeze({
  6160. __proto__: null,
  6161. getCurrent: getCurrent
  6162. });
  6163. var ComposeSchema = [strict$1('find')];
  6164. var Composing = create$1({
  6165. fields: ComposeSchema,
  6166. name: 'composing',
  6167. apis: ComposeApis
  6168. });
  6169. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  6170. var highlighted = descendants(component.element(), '.' + hConfig.highlightClass);
  6171. each(highlighted, function (h) {
  6172. if (!exists(skip, function (skipComp) {
  6173. return skipComp.element() === h;
  6174. })) {
  6175. remove$4(h, hConfig.highlightClass);
  6176. component.getSystem().getByDom(h).each(function (target) {
  6177. hConfig.onDehighlight(component, target);
  6178. emit(target, dehighlight());
  6179. });
  6180. }
  6181. });
  6182. };
  6183. var dehighlightAll = function (component, hConfig, hState) {
  6184. return dehighlightAllExcept(component, hConfig, hState, []);
  6185. };
  6186. var dehighlight$1 = function (component, hConfig, hState, target) {
  6187. if (isHighlighted(component, hConfig, hState, target)) {
  6188. remove$4(target.element(), hConfig.highlightClass);
  6189. hConfig.onDehighlight(component, target);
  6190. emit(target, dehighlight());
  6191. }
  6192. };
  6193. var highlight$1 = function (component, hConfig, hState, target) {
  6194. dehighlightAllExcept(component, hConfig, hState, [target]);
  6195. if (!isHighlighted(component, hConfig, hState, target)) {
  6196. add$2(target.element(), hConfig.highlightClass);
  6197. hConfig.onHighlight(component, target);
  6198. emit(target, highlight());
  6199. }
  6200. };
  6201. var highlightFirst = function (component, hConfig, hState) {
  6202. getFirst(component, hConfig).each(function (firstComp) {
  6203. highlight$1(component, hConfig, hState, firstComp);
  6204. });
  6205. };
  6206. var highlightLast = function (component, hConfig, hState) {
  6207. getLast(component, hConfig).each(function (lastComp) {
  6208. highlight$1(component, hConfig, hState, lastComp);
  6209. });
  6210. };
  6211. var highlightAt = function (component, hConfig, hState, index) {
  6212. getByIndex(component, hConfig, hState, index).fold(function (err) {
  6213. throw new Error(err);
  6214. }, function (firstComp) {
  6215. highlight$1(component, hConfig, hState, firstComp);
  6216. });
  6217. };
  6218. var highlightBy = function (component, hConfig, hState, predicate) {
  6219. var candidates = getCandidates(component, hConfig);
  6220. var targetComp = find(candidates, predicate);
  6221. targetComp.each(function (c) {
  6222. highlight$1(component, hConfig, hState, c);
  6223. });
  6224. };
  6225. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  6226. return has$2(queryTarget.element(), hConfig.highlightClass);
  6227. };
  6228. var getHighlighted = function (component, hConfig, _hState) {
  6229. return descendant$1(component.element(), '.' + hConfig.highlightClass).bind(function (e) {
  6230. return component.getSystem().getByDom(e).toOption();
  6231. });
  6232. };
  6233. var getByIndex = function (component, hConfig, hState, index) {
  6234. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6235. return Option.from(items[index]).fold(function () {
  6236. return Result.error('No element found with index ' + index);
  6237. }, component.getSystem().getByDom);
  6238. };
  6239. var getFirst = function (component, hConfig, _hState) {
  6240. return descendant$1(component.element(), '.' + hConfig.itemClass).bind(function (e) {
  6241. return component.getSystem().getByDom(e).toOption();
  6242. });
  6243. };
  6244. var getLast = function (component, hConfig, _hState) {
  6245. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6246. var last = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
  6247. return last.bind(function (c) {
  6248. return component.getSystem().getByDom(c).toOption();
  6249. });
  6250. };
  6251. var getDelta = function (component, hConfig, hState, delta) {
  6252. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6253. var current = findIndex(items, function (item) {
  6254. return has$2(item, hConfig.highlightClass);
  6255. });
  6256. return current.bind(function (selected) {
  6257. var dest = cycleBy(selected, delta, 0, items.length - 1);
  6258. return component.getSystem().getByDom(items[dest]).toOption();
  6259. });
  6260. };
  6261. var getPrevious = function (component, hConfig, hState) {
  6262. return getDelta(component, hConfig, hState, -1);
  6263. };
  6264. var getNext = function (component, hConfig, hState) {
  6265. return getDelta(component, hConfig, hState, +1);
  6266. };
  6267. var getCandidates = function (component, hConfig, _hState) {
  6268. var items = descendants(component.element(), '.' + hConfig.itemClass);
  6269. return cat(map(items, function (i) {
  6270. return component.getSystem().getByDom(i).toOption();
  6271. }));
  6272. };
  6273. var HighlightApis = /*#__PURE__*/Object.freeze({
  6274. __proto__: null,
  6275. dehighlightAll: dehighlightAll,
  6276. dehighlight: dehighlight$1,
  6277. highlight: highlight$1,
  6278. highlightFirst: highlightFirst,
  6279. highlightLast: highlightLast,
  6280. highlightAt: highlightAt,
  6281. highlightBy: highlightBy,
  6282. isHighlighted: isHighlighted,
  6283. getHighlighted: getHighlighted,
  6284. getFirst: getFirst,
  6285. getLast: getLast,
  6286. getPrevious: getPrevious,
  6287. getNext: getNext,
  6288. getCandidates: getCandidates
  6289. });
  6290. var HighlightSchema = [
  6291. strict$1('highlightClass'),
  6292. strict$1('itemClass'),
  6293. onHandler('onHighlight'),
  6294. onHandler('onDehighlight')
  6295. ];
  6296. var Highlighting = create$1({
  6297. fields: HighlightSchema,
  6298. name: 'highlighting',
  6299. apis: HighlightApis
  6300. });
  6301. var BACKSPACE = function () {
  6302. return [8];
  6303. };
  6304. var TAB = function () {
  6305. return [9];
  6306. };
  6307. var ENTER = function () {
  6308. return [13];
  6309. };
  6310. var ESCAPE = function () {
  6311. return [27];
  6312. };
  6313. var SPACE = function () {
  6314. return [32];
  6315. };
  6316. var LEFT = function () {
  6317. return [37];
  6318. };
  6319. var UP = function () {
  6320. return [38];
  6321. };
  6322. var RIGHT = function () {
  6323. return [39];
  6324. };
  6325. var DOWN = function () {
  6326. return [40];
  6327. };
  6328. var cyclePrev = function (values, index, predicate) {
  6329. var before = reverse(values.slice(0, index));
  6330. var after = reverse(values.slice(index + 1));
  6331. return find(before.concat(after), predicate);
  6332. };
  6333. var tryPrev = function (values, index, predicate) {
  6334. var before = reverse(values.slice(0, index));
  6335. return find(before, predicate);
  6336. };
  6337. var cycleNext = function (values, index, predicate) {
  6338. var before = values.slice(0, index);
  6339. var after = values.slice(index + 1);
  6340. return find(after.concat(before), predicate);
  6341. };
  6342. var tryNext = function (values, index, predicate) {
  6343. var after = values.slice(index + 1);
  6344. return find(after, predicate);
  6345. };
  6346. var inSet = function (keys) {
  6347. return function (event) {
  6348. var raw = event.raw();
  6349. return contains(keys, raw.which);
  6350. };
  6351. };
  6352. var and = function (preds) {
  6353. return function (event) {
  6354. return forall(preds, function (pred) {
  6355. return pred(event);
  6356. });
  6357. };
  6358. };
  6359. var isShift = function (event) {
  6360. var raw = event.raw();
  6361. return raw.shiftKey === true;
  6362. };
  6363. var isControl = function (event) {
  6364. var raw = event.raw();
  6365. return raw.ctrlKey === true;
  6366. };
  6367. var isNotShift = not(isShift);
  6368. var rule = function (matches, action) {
  6369. return {
  6370. matches: matches,
  6371. classification: action
  6372. };
  6373. };
  6374. var choose$2 = function (transitions, event) {
  6375. var transition = find(transitions, function (t) {
  6376. return t.matches(event);
  6377. });
  6378. return transition.map(function (t) {
  6379. return t.classification;
  6380. });
  6381. };
  6382. var reportFocusShifting = function (component, prevFocus, newFocus) {
  6383. var noChange = prevFocus.exists(function (p) {
  6384. return newFocus.exists(function (n) {
  6385. return eq$1(n, p);
  6386. });
  6387. });
  6388. if (!noChange) {
  6389. emitWith(component, focusShifted(), {
  6390. prevFocus: prevFocus,
  6391. newFocus: newFocus
  6392. });
  6393. }
  6394. };
  6395. var dom = function () {
  6396. var get = function (component) {
  6397. return search(component.element());
  6398. };
  6399. var set = function (component, focusee) {
  6400. var prevFocus = get(component);
  6401. component.getSystem().triggerFocus(focusee, component.element());
  6402. var newFocus = get(component);
  6403. reportFocusShifting(component, prevFocus, newFocus);
  6404. };
  6405. return {
  6406. get: get,
  6407. set: set
  6408. };
  6409. };
  6410. var highlights = function () {
  6411. var get = function (component) {
  6412. return Highlighting.getHighlighted(component).map(function (item) {
  6413. return item.element();
  6414. });
  6415. };
  6416. var set = function (component, element) {
  6417. var prevFocus = get(component);
  6418. component.getSystem().getByDom(element).fold(noop, function (item) {
  6419. Highlighting.highlight(component, item);
  6420. });
  6421. var newFocus = get(component);
  6422. reportFocusShifting(component, prevFocus, newFocus);
  6423. };
  6424. return {
  6425. get: get,
  6426. set: set
  6427. };
  6428. };
  6429. var FocusInsideModes;
  6430. (function (FocusInsideModes) {
  6431. FocusInsideModes['OnFocusMode'] = 'onFocus';
  6432. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  6433. FocusInsideModes['OnApiMode'] = 'onApi';
  6434. }(FocusInsideModes || (FocusInsideModes = {})));
  6435. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  6436. var schema = function () {
  6437. return infoSchema.concat([
  6438. defaulted$1('focusManager', dom()),
  6439. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  6440. return contains([
  6441. 'onFocus',
  6442. 'onEnterOrSpace',
  6443. 'onApi'
  6444. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  6445. })),
  6446. output('handler', me),
  6447. output('state', stateInit),
  6448. output('sendFocusIn', optFocusIn)
  6449. ]);
  6450. };
  6451. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  6452. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  6453. return choose$2(rules, simulatedEvent.event()).bind(function (rule) {
  6454. return rule(component, simulatedEvent, keyingConfig, keyingState);
  6455. });
  6456. };
  6457. var toEvents = function (keyingConfig, keyingState) {
  6458. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Option.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  6459. return run(focus(), function (component, simulatedEvent) {
  6460. focusIn(component, keyingConfig, keyingState);
  6461. simulatedEvent.stop();
  6462. });
  6463. });
  6464. var tryGoInsideComponent = function (component, simulatedEvent) {
  6465. var isEnterOrSpace = inSet(SPACE().concat(ENTER()))(simulatedEvent.event());
  6466. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  6467. optFocusIn(keyingConfig).each(function (focusIn) {
  6468. focusIn(component, keyingConfig, keyingState);
  6469. simulatedEvent.stop();
  6470. });
  6471. }
  6472. };
  6473. var keyboardEvents = [
  6474. run(keydown(), function (component, simulatedEvent) {
  6475. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  6476. tryGoInsideComponent(component, simulatedEvent);
  6477. }, function (_) {
  6478. simulatedEvent.stop();
  6479. });
  6480. }),
  6481. run(keyup(), function (component, simulatedEvent) {
  6482. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  6483. simulatedEvent.stop();
  6484. });
  6485. })
  6486. ];
  6487. return derive(onFocusHandler.toArray().concat(keyboardEvents));
  6488. };
  6489. var me = {
  6490. schema: schema,
  6491. processKey: processKey,
  6492. toEvents: toEvents
  6493. };
  6494. return me;
  6495. };
  6496. var create$3 = function (cyclicField) {
  6497. var schema = [
  6498. option('onEscape'),
  6499. option('onEnter'),
  6500. defaulted$1('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  6501. defaulted$1('firstTabstop', 0),
  6502. defaulted$1('useTabstopAt', constant(true)),
  6503. option('visibilitySelector')
  6504. ].concat([cyclicField]);
  6505. var isVisible = function (tabbingConfig, element) {
  6506. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  6507. return closest$3(element, sel);
  6508. }).getOr(element);
  6509. return get$6(target) > 0;
  6510. };
  6511. var findInitial = function (component, tabbingConfig) {
  6512. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6513. var visibles = filter(tabstops, function (elem) {
  6514. return isVisible(tabbingConfig, elem);
  6515. });
  6516. return Option.from(visibles[tabbingConfig.firstTabstop]);
  6517. };
  6518. var findCurrent = function (component, tabbingConfig) {
  6519. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  6520. return closest$3(elem, tabbingConfig.selector);
  6521. });
  6522. };
  6523. var isTabstop = function (tabbingConfig, element) {
  6524. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  6525. };
  6526. var focusIn = function (component, tabbingConfig, _tabbingState) {
  6527. findInitial(component, tabbingConfig).each(function (target) {
  6528. tabbingConfig.focusManager.set(component, target);
  6529. });
  6530. };
  6531. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  6532. return cycle(tabstops, stopIndex, function (elem) {
  6533. return isTabstop(tabbingConfig, elem);
  6534. }).fold(function () {
  6535. return tabbingConfig.cyclic ? Option.some(true) : Option.none();
  6536. }, function (target) {
  6537. tabbingConfig.focusManager.set(component, target);
  6538. return Option.some(true);
  6539. });
  6540. };
  6541. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  6542. var tabstops = descendants(component.element(), tabbingConfig.selector);
  6543. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  6544. var optStopIndex = findIndex(tabstops, curry(eq$1, tabstop));
  6545. return optStopIndex.bind(function (stopIndex) {
  6546. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  6547. });
  6548. });
  6549. };
  6550. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  6551. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  6552. return go(component, simulatedEvent, tabbingConfig, navigate);
  6553. };
  6554. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  6555. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  6556. return go(component, simulatedEvent, tabbingConfig, navigate);
  6557. };
  6558. var execute = function (component, simulatedEvent, tabbingConfig) {
  6559. return tabbingConfig.onEnter.bind(function (f) {
  6560. return f(component, simulatedEvent);
  6561. });
  6562. };
  6563. var exit = function (component, simulatedEvent, tabbingConfig) {
  6564. return tabbingConfig.onEscape.bind(function (f) {
  6565. return f(component, simulatedEvent);
  6566. });
  6567. };
  6568. var getKeydownRules = constant([
  6569. rule(and([
  6570. isShift,
  6571. inSet(TAB())
  6572. ]), goBackwards),
  6573. rule(inSet(TAB()), goForwards),
  6574. rule(inSet(ESCAPE()), exit),
  6575. rule(and([
  6576. isNotShift,
  6577. inSet(ENTER())
  6578. ]), execute)
  6579. ]);
  6580. var getKeyupRules = constant([]);
  6581. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  6582. return Option.some(focusIn);
  6583. });
  6584. };
  6585. var AcyclicType = create$3(state$1('cyclic', constant(false)));
  6586. var CyclicType = create$3(state$1('cyclic', constant(true)));
  6587. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  6588. dispatch(component, focused, execute());
  6589. return Option.some(true);
  6590. };
  6591. var defaultExecute = function (component, simulatedEvent, focused) {
  6592. var isComplex = inside(focused) && inSet(SPACE())(simulatedEvent.event());
  6593. return isComplex ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
  6594. };
  6595. var stopEventForFirefox = function (_component, _simulatedEvent) {
  6596. return Option.some(true);
  6597. };
  6598. var schema$4 = [
  6599. defaulted$1('execute', defaultExecute),
  6600. defaulted$1('useSpace', false),
  6601. defaulted$1('useEnter', true),
  6602. defaulted$1('useControlEnter', false),
  6603. defaulted$1('useDown', false)
  6604. ];
  6605. var execute$1 = function (component, simulatedEvent, executeConfig) {
  6606. return executeConfig.execute(component, simulatedEvent, component.element());
  6607. };
  6608. var getKeydownRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  6609. var spaceExec = executeConfig.useSpace && !inside(component.element()) ? SPACE() : [];
  6610. var enterExec = executeConfig.useEnter ? ENTER() : [];
  6611. var downExec = executeConfig.useDown ? DOWN() : [];
  6612. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  6613. return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter ? [rule(and([
  6614. isControl,
  6615. inSet(ENTER())
  6616. ]), execute$1)] : []);
  6617. };
  6618. var getKeyupRules = function (component, _simulatedEvent, executeConfig, _executeState) {
  6619. return executeConfig.useSpace && !inside(component.element()) ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  6620. };
  6621. var ExecutionType = typical(schema$4, NoState.init, getKeydownRules, getKeyupRules, function () {
  6622. return Option.none();
  6623. });
  6624. var flatgrid = function () {
  6625. var dimensions = Cell(Option.none());
  6626. var setGridSize = function (numRows, numColumns) {
  6627. dimensions.set(Option.some({
  6628. numRows: numRows,
  6629. numColumns: numColumns
  6630. }));
  6631. };
  6632. var getNumRows = function () {
  6633. return dimensions.get().map(function (d) {
  6634. return d.numRows;
  6635. });
  6636. };
  6637. var getNumColumns = function () {
  6638. return dimensions.get().map(function (d) {
  6639. return d.numColumns;
  6640. });
  6641. };
  6642. return nu$5({
  6643. readState: function () {
  6644. return dimensions.get().map(function (d) {
  6645. return {
  6646. numRows: String(d.numRows),
  6647. numColumns: String(d.numColumns)
  6648. };
  6649. }).getOr({
  6650. numRows: '?',
  6651. numColumns: '?'
  6652. });
  6653. },
  6654. setGridSize: setGridSize,
  6655. getNumRows: getNumRows,
  6656. getNumColumns: getNumColumns
  6657. });
  6658. };
  6659. var init$2 = function (spec) {
  6660. return spec.state(spec);
  6661. };
  6662. var KeyingState = /*#__PURE__*/Object.freeze({
  6663. __proto__: null,
  6664. flatgrid: flatgrid,
  6665. init: init$2
  6666. });
  6667. var useH = function (movement) {
  6668. return function (component, simulatedEvent, config, state) {
  6669. var move = movement(component.element());
  6670. return use(move, component, simulatedEvent, config, state);
  6671. };
  6672. };
  6673. var west$2 = function (moveLeft, moveRight) {
  6674. var movement = onDirection(moveLeft, moveRight);
  6675. return useH(movement);
  6676. };
  6677. var east$2 = function (moveLeft, moveRight) {
  6678. var movement = onDirection(moveRight, moveLeft);
  6679. return useH(movement);
  6680. };
  6681. var useV = function (move) {
  6682. return function (component, simulatedEvent, config, state) {
  6683. return use(move, component, simulatedEvent, config, state);
  6684. };
  6685. };
  6686. var use = function (move, component, simulatedEvent, config, state) {
  6687. var outcome = config.focusManager.get(component).bind(function (focused) {
  6688. return move(component.element(), focused, config, state);
  6689. });
  6690. return outcome.map(function (newFocus) {
  6691. config.focusManager.set(component, newFocus);
  6692. return true;
  6693. });
  6694. };
  6695. var north$2 = useV;
  6696. var south$2 = useV;
  6697. var move = useV;
  6698. var isHidden = function (dom) {
  6699. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  6700. };
  6701. var isVisible = function (element) {
  6702. return !isHidden(element.dom());
  6703. };
  6704. var locate = function (candidates, predicate) {
  6705. return findIndex(candidates, predicate).map(function (index) {
  6706. return {
  6707. index: constant(index),
  6708. candidates: constant(candidates)
  6709. };
  6710. });
  6711. };
  6712. var locateVisible = function (container, current, selector) {
  6713. var predicate = function (x) {
  6714. return eq$1(x, current);
  6715. };
  6716. var candidates = descendants(container, selector);
  6717. var visible = filter(candidates, isVisible);
  6718. return locate(visible, predicate);
  6719. };
  6720. var findIndex$1 = function (elements, target) {
  6721. return findIndex(elements, function (elem) {
  6722. return eq$1(target, elem);
  6723. });
  6724. };
  6725. var withGrid = function (values, index, numCols, f) {
  6726. var oldRow = Math.floor(index / numCols);
  6727. var oldColumn = index % numCols;
  6728. return f(oldRow, oldColumn).bind(function (address) {
  6729. var newIndex = address.row() * numCols + address.column();
  6730. return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
  6731. });
  6732. };
  6733. var cycleHorizontal = function (values, index, numRows, numCols, delta) {
  6734. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6735. var onLastRow = oldRow === numRows - 1;
  6736. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  6737. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  6738. return Option.some({
  6739. row: constant(oldRow),
  6740. column: constant(newColumn)
  6741. });
  6742. });
  6743. };
  6744. var cycleVertical = function (values, index, numRows, numCols, delta) {
  6745. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  6746. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  6747. var onLastRow = newRow === numRows - 1;
  6748. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  6749. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  6750. return Option.some({
  6751. row: constant(newRow),
  6752. column: constant(newCol)
  6753. });
  6754. });
  6755. };
  6756. var cycleRight = function (values, index, numRows, numCols) {
  6757. return cycleHorizontal(values, index, numRows, numCols, +1);
  6758. };
  6759. var cycleLeft = function (values, index, numRows, numCols) {
  6760. return cycleHorizontal(values, index, numRows, numCols, -1);
  6761. };
  6762. var cycleUp = function (values, index, numRows, numCols) {
  6763. return cycleVertical(values, index, numRows, numCols, -1);
  6764. };
  6765. var cycleDown = function (values, index, numRows, numCols) {
  6766. return cycleVertical(values, index, numRows, numCols, +1);
  6767. };
  6768. var schema$5 = [
  6769. strict$1('selector'),
  6770. defaulted$1('execute', defaultExecute),
  6771. onKeyboardHandler('onEscape'),
  6772. defaulted$1('captureTab', false),
  6773. initSize()
  6774. ];
  6775. var focusIn = function (component, gridConfig, _gridState) {
  6776. descendant$1(component.element(), gridConfig.selector).each(function (first) {
  6777. gridConfig.focusManager.set(component, first);
  6778. });
  6779. };
  6780. var findCurrent = function (component, gridConfig) {
  6781. return gridConfig.focusManager.get(component).bind(function (elem) {
  6782. return closest$3(elem, gridConfig.selector);
  6783. });
  6784. };
  6785. var execute$2 = function (component, simulatedEvent, gridConfig, _gridState) {
  6786. return findCurrent(component, gridConfig).bind(function (focused) {
  6787. return gridConfig.execute(component, simulatedEvent, focused);
  6788. });
  6789. };
  6790. var doMove = function (cycle) {
  6791. return function (element, focused, gridConfig, gridState) {
  6792. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  6793. return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  6794. });
  6795. };
  6796. };
  6797. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  6798. return gridConfig.captureTab ? Option.some(true) : Option.none();
  6799. };
  6800. var doEscape = function (component, simulatedEvent, gridConfig) {
  6801. return gridConfig.onEscape(component, simulatedEvent);
  6802. };
  6803. var moveLeft = doMove(cycleLeft);
  6804. var moveRight = doMove(cycleRight);
  6805. var moveNorth = doMove(cycleUp);
  6806. var moveSouth = doMove(cycleDown);
  6807. var getKeydownRules$1 = constant([
  6808. rule(inSet(LEFT()), west$2(moveLeft, moveRight)),
  6809. rule(inSet(RIGHT()), east$2(moveLeft, moveRight)),
  6810. rule(inSet(UP()), north$2(moveNorth)),
  6811. rule(inSet(DOWN()), south$2(moveSouth)),
  6812. rule(and([
  6813. isShift,
  6814. inSet(TAB())
  6815. ]), handleTab),
  6816. rule(and([
  6817. isNotShift,
  6818. inSet(TAB())
  6819. ]), handleTab),
  6820. rule(inSet(ESCAPE()), doEscape),
  6821. rule(inSet(SPACE().concat(ENTER())), execute$2)
  6822. ]);
  6823. var getKeyupRules$1 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6824. var FlatgridType = typical(schema$5, flatgrid, getKeydownRules$1, getKeyupRules$1, function () {
  6825. return Option.some(focusIn);
  6826. });
  6827. var horizontal = function (container, selector, current, delta) {
  6828. var isDisabledButton = function (candidate) {
  6829. return name(candidate) === 'button' && get$2(candidate, 'disabled') === 'disabled';
  6830. };
  6831. var tryCycle = function (initial, index, candidates) {
  6832. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  6833. if (newIndex === initial) {
  6834. return Option.none();
  6835. } else {
  6836. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Option.from(candidates[newIndex]);
  6837. }
  6838. };
  6839. return locateVisible(container, current, selector).bind(function (identified) {
  6840. var index = identified.index();
  6841. var candidates = identified.candidates();
  6842. return tryCycle(index, index, candidates);
  6843. });
  6844. };
  6845. var schema$6 = [
  6846. strict$1('selector'),
  6847. defaulted$1('getInitial', Option.none),
  6848. defaulted$1('execute', defaultExecute),
  6849. onKeyboardHandler('onEscape'),
  6850. defaulted$1('executeOnMove', false),
  6851. defaulted$1('allowVertical', true)
  6852. ];
  6853. var findCurrent$1 = function (component, flowConfig) {
  6854. return flowConfig.focusManager.get(component).bind(function (elem) {
  6855. return closest$3(elem, flowConfig.selector);
  6856. });
  6857. };
  6858. var execute$3 = function (component, simulatedEvent, flowConfig) {
  6859. return findCurrent$1(component, flowConfig).bind(function (focused) {
  6860. return flowConfig.execute(component, simulatedEvent, focused);
  6861. });
  6862. };
  6863. var focusIn$1 = function (component, flowConfig, _state) {
  6864. flowConfig.getInitial(component).orThunk(function () {
  6865. return descendant$1(component.element(), flowConfig.selector);
  6866. }).each(function (first) {
  6867. flowConfig.focusManager.set(component, first);
  6868. });
  6869. };
  6870. var moveLeft$1 = function (element, focused, info) {
  6871. return horizontal(element, info.selector, focused, -1);
  6872. };
  6873. var moveRight$1 = function (element, focused, info) {
  6874. return horizontal(element, info.selector, focused, +1);
  6875. };
  6876. var doMove$1 = function (movement) {
  6877. return function (component, simulatedEvent, flowConfig, flowState) {
  6878. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  6879. return flowConfig.executeOnMove ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
  6880. });
  6881. };
  6882. };
  6883. var doEscape$1 = function (component, simulatedEvent, flowConfig) {
  6884. return flowConfig.onEscape(component, simulatedEvent);
  6885. };
  6886. var getKeydownRules$2 = function (_component, _se, flowConfig, _flowState) {
  6887. var westMovers = LEFT().concat(flowConfig.allowVertical ? UP() : []);
  6888. var eastMovers = RIGHT().concat(flowConfig.allowVertical ? DOWN() : []);
  6889. return [
  6890. rule(inSet(westMovers), doMove$1(west$2(moveLeft$1, moveRight$1))),
  6891. rule(inSet(eastMovers), doMove$1(east$2(moveLeft$1, moveRight$1))),
  6892. rule(inSet(ENTER()), execute$3),
  6893. rule(inSet(SPACE()), execute$3),
  6894. rule(inSet(ESCAPE()), doEscape$1)
  6895. ];
  6896. };
  6897. var getKeyupRules$2 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  6898. var FlowType = typical(schema$6, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  6899. return Option.some(focusIn$1);
  6900. });
  6901. var toCell = function (matrix, rowIndex, columnIndex) {
  6902. return Option.from(matrix[rowIndex]).bind(function (row) {
  6903. return Option.from(row[columnIndex]).map(function (cell) {
  6904. return {
  6905. rowIndex: rowIndex,
  6906. columnIndex: columnIndex,
  6907. cell: cell
  6908. };
  6909. });
  6910. });
  6911. };
  6912. var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
  6913. var row = matrix[rowIndex];
  6914. var colsInRow = row.length;
  6915. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  6916. return toCell(matrix, rowIndex, newColIndex);
  6917. };
  6918. var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
  6919. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  6920. var colsInNextRow = matrix[nextRowIndex].length;
  6921. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6922. return toCell(matrix, nextRowIndex, nextColIndex);
  6923. };
  6924. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  6925. var row = matrix[rowIndex];
  6926. var colsInRow = row.length;
  6927. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  6928. return toCell(matrix, rowIndex, newColIndex);
  6929. };
  6930. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  6931. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  6932. var colsInNextRow = matrix[nextRowIndex].length;
  6933. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  6934. return toCell(matrix, nextRowIndex, nextColIndex);
  6935. };
  6936. var cycleRight$1 = function (matrix, startRow, startCol) {
  6937. return cycleHorizontal$1(matrix, startRow, startCol, +1);
  6938. };
  6939. var cycleLeft$1 = function (matrix, startRow, startCol) {
  6940. return cycleHorizontal$1(matrix, startRow, startCol, -1);
  6941. };
  6942. var cycleUp$1 = function (matrix, startRow, startCol) {
  6943. return cycleVertical$1(matrix, startCol, startRow, -1);
  6944. };
  6945. var cycleDown$1 = function (matrix, startRow, startCol) {
  6946. return cycleVertical$1(matrix, startCol, startRow, +1);
  6947. };
  6948. var moveLeft$2 = function (matrix, startRow, startCol) {
  6949. return moveHorizontal(matrix, startRow, startCol, -1);
  6950. };
  6951. var moveRight$2 = function (matrix, startRow, startCol) {
  6952. return moveHorizontal(matrix, startRow, startCol, +1);
  6953. };
  6954. var moveUp = function (matrix, startRow, startCol) {
  6955. return moveVertical(matrix, startCol, startRow, -1);
  6956. };
  6957. var moveDown = function (matrix, startRow, startCol) {
  6958. return moveVertical(matrix, startCol, startRow, +1);
  6959. };
  6960. var schema$7 = [
  6961. strictObjOf('selectors', [
  6962. strict$1('row'),
  6963. strict$1('cell')
  6964. ]),
  6965. defaulted$1('cycles', true),
  6966. defaulted$1('previousSelector', Option.none),
  6967. defaulted$1('execute', defaultExecute)
  6968. ];
  6969. var focusIn$2 = function (component, matrixConfig, _state) {
  6970. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  6971. var selectors = matrixConfig.selectors;
  6972. return descendant$1(component.element(), selectors.cell);
  6973. });
  6974. focused.each(function (cell) {
  6975. matrixConfig.focusManager.set(component, cell);
  6976. });
  6977. };
  6978. var execute$4 = function (component, simulatedEvent, matrixConfig) {
  6979. return search(component.element()).bind(function (focused) {
  6980. return matrixConfig.execute(component, simulatedEvent, focused);
  6981. });
  6982. };
  6983. var toMatrix = function (rows, matrixConfig) {
  6984. return map(rows, function (row) {
  6985. return descendants(row, matrixConfig.selectors.cell);
  6986. });
  6987. };
  6988. var doMove$2 = function (ifCycle, ifMove) {
  6989. return function (element, focused, matrixConfig) {
  6990. var move = matrixConfig.cycles ? ifCycle : ifMove;
  6991. return closest$3(focused, matrixConfig.selectors.row).bind(function (inRow) {
  6992. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  6993. return findIndex$1(cellsInRow, focused).bind(function (colIndex) {
  6994. var allRows = descendants(element, matrixConfig.selectors.row);
  6995. return findIndex$1(allRows, inRow).bind(function (rowIndex) {
  6996. var matrix = toMatrix(allRows, matrixConfig);
  6997. return move(matrix, rowIndex, colIndex).map(function (next) {
  6998. return next.cell;
  6999. });
  7000. });
  7001. });
  7002. });
  7003. };
  7004. };
  7005. var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
  7006. var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
  7007. var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
  7008. var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
  7009. var getKeydownRules$3 = constant([
  7010. rule(inSet(LEFT()), west$2(moveLeft$3, moveRight$3)),
  7011. rule(inSet(RIGHT()), east$2(moveLeft$3, moveRight$3)),
  7012. rule(inSet(UP()), north$2(moveNorth$1)),
  7013. rule(inSet(DOWN()), south$2(moveSouth$1)),
  7014. rule(inSet(SPACE().concat(ENTER())), execute$4)
  7015. ]);
  7016. var getKeyupRules$3 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  7017. var MatrixType = typical(schema$7, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  7018. return Option.some(focusIn$2);
  7019. });
  7020. var schema$8 = [
  7021. strict$1('selector'),
  7022. defaulted$1('execute', defaultExecute),
  7023. defaulted$1('moveOnTab', false)
  7024. ];
  7025. var execute$5 = function (component, simulatedEvent, menuConfig) {
  7026. return menuConfig.focusManager.get(component).bind(function (focused) {
  7027. return menuConfig.execute(component, simulatedEvent, focused);
  7028. });
  7029. };
  7030. var focusIn$3 = function (component, menuConfig, _state) {
  7031. descendant$1(component.element(), menuConfig.selector).each(function (first) {
  7032. menuConfig.focusManager.set(component, first);
  7033. });
  7034. };
  7035. var moveUp$1 = function (element, focused, info) {
  7036. return horizontal(element, info.selector, focused, -1);
  7037. };
  7038. var moveDown$1 = function (element, focused, info) {
  7039. return horizontal(element, info.selector, focused, +1);
  7040. };
  7041. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  7042. return menuConfig.moveOnTab ? move(moveUp$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  7043. };
  7044. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  7045. return menuConfig.moveOnTab ? move(moveDown$1)(component, simulatedEvent, menuConfig, menuState) : Option.none();
  7046. };
  7047. var getKeydownRules$4 = constant([
  7048. rule(inSet(UP()), move(moveUp$1)),
  7049. rule(inSet(DOWN()), move(moveDown$1)),
  7050. rule(and([
  7051. isShift,
  7052. inSet(TAB())
  7053. ]), fireShiftTab),
  7054. rule(and([
  7055. isNotShift,
  7056. inSet(TAB())
  7057. ]), fireTab),
  7058. rule(inSet(ENTER()), execute$5),
  7059. rule(inSet(SPACE()), execute$5)
  7060. ]);
  7061. var getKeyupRules$4 = constant([rule(inSet(SPACE()), stopEventForFirefox)]);
  7062. var MenuType = typical(schema$8, NoState.init, getKeydownRules$4, getKeyupRules$4, function () {
  7063. return Option.some(focusIn$3);
  7064. });
  7065. var schema$9 = [
  7066. onKeyboardHandler('onSpace'),
  7067. onKeyboardHandler('onEnter'),
  7068. onKeyboardHandler('onShiftEnter'),
  7069. onKeyboardHandler('onLeft'),
  7070. onKeyboardHandler('onRight'),
  7071. onKeyboardHandler('onTab'),
  7072. onKeyboardHandler('onShiftTab'),
  7073. onKeyboardHandler('onUp'),
  7074. onKeyboardHandler('onDown'),
  7075. onKeyboardHandler('onEscape'),
  7076. defaulted$1('stopSpaceKeyup', false),
  7077. option('focusIn')
  7078. ];
  7079. var getKeydownRules$5 = function (component, simulatedEvent, specialInfo) {
  7080. return [
  7081. rule(inSet(SPACE()), specialInfo.onSpace),
  7082. rule(and([
  7083. isNotShift,
  7084. inSet(ENTER())
  7085. ]), specialInfo.onEnter),
  7086. rule(and([
  7087. isShift,
  7088. inSet(ENTER())
  7089. ]), specialInfo.onShiftEnter),
  7090. rule(and([
  7091. isShift,
  7092. inSet(TAB())
  7093. ]), specialInfo.onShiftTab),
  7094. rule(and([
  7095. isNotShift,
  7096. inSet(TAB())
  7097. ]), specialInfo.onTab),
  7098. rule(inSet(UP()), specialInfo.onUp),
  7099. rule(inSet(DOWN()), specialInfo.onDown),
  7100. rule(inSet(LEFT()), specialInfo.onLeft),
  7101. rule(inSet(RIGHT()), specialInfo.onRight),
  7102. rule(inSet(SPACE()), specialInfo.onSpace),
  7103. rule(inSet(ESCAPE()), specialInfo.onEscape)
  7104. ];
  7105. };
  7106. var getKeyupRules$5 = function (component, simulatedEvent, specialInfo) {
  7107. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE()), stopEventForFirefox)] : [];
  7108. };
  7109. var SpecialType = typical(schema$9, NoState.init, getKeydownRules$5, getKeyupRules$5, function (specialInfo) {
  7110. return specialInfo.focusIn;
  7111. });
  7112. var acyclic = AcyclicType.schema();
  7113. var cyclic = CyclicType.schema();
  7114. var flow = FlowType.schema();
  7115. var flatgrid$1 = FlatgridType.schema();
  7116. var matrix = MatrixType.schema();
  7117. var execution = ExecutionType.schema();
  7118. var menu = MenuType.schema();
  7119. var special = SpecialType.schema();
  7120. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  7121. __proto__: null,
  7122. acyclic: acyclic,
  7123. cyclic: cyclic,
  7124. flow: flow,
  7125. flatgrid: flatgrid$1,
  7126. matrix: matrix,
  7127. execution: execution,
  7128. menu: menu,
  7129. special: special
  7130. });
  7131. var isFlatgridState = function (keyState) {
  7132. return hasNonNullableKey(keyState, 'setGridSize');
  7133. };
  7134. var Keying = createModes$1({
  7135. branchKey: 'mode',
  7136. branches: KeyboardBranches,
  7137. name: 'keying',
  7138. active: {
  7139. events: function (keyingConfig, keyingState) {
  7140. var handler = keyingConfig.handler;
  7141. return handler.toEvents(keyingConfig, keyingState);
  7142. }
  7143. },
  7144. apis: {
  7145. focusIn: function (component, keyConfig, keyState) {
  7146. keyConfig.sendFocusIn(keyConfig).fold(function () {
  7147. component.getSystem().triggerFocus(component.element(), component.element());
  7148. }, function (sendFocusIn) {
  7149. sendFocusIn(component, keyConfig, keyState);
  7150. });
  7151. },
  7152. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  7153. if (!isFlatgridState(keyState)) {
  7154. domGlobals.console.error('Layout does not support setGridSize');
  7155. } else {
  7156. keyState.setGridSize(numRows, numColumns);
  7157. }
  7158. }
  7159. },
  7160. state: KeyingState
  7161. });
  7162. var set$5 = function (component, replaceConfig, replaceState, data) {
  7163. preserve(function () {
  7164. var newChildren = map(data, component.getSystem().build);
  7165. replaceChildren(component, newChildren);
  7166. }, component.element());
  7167. };
  7168. var insert = function (component, replaceConfig, insertion, childSpec) {
  7169. var child = component.getSystem().build(childSpec);
  7170. attachWith(component, child, insertion);
  7171. };
  7172. var append$2 = function (component, replaceConfig, replaceState, appendee) {
  7173. insert(component, replaceConfig, append, appendee);
  7174. };
  7175. var prepend$1 = function (component, replaceConfig, replaceState, prependee) {
  7176. insert(component, replaceConfig, prepend, prependee);
  7177. };
  7178. var remove$7 = function (component, replaceConfig, replaceState, removee) {
  7179. var children = contents(component);
  7180. var foundChild = find(children, function (child) {
  7181. return eq$1(removee.element(), child.element());
  7182. });
  7183. foundChild.each(detach);
  7184. };
  7185. var contents = function (component, _replaceConfig) {
  7186. return component.components();
  7187. };
  7188. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  7189. var children = contents(component);
  7190. return Option.from(children[replaceeIndex]).map(function (replacee) {
  7191. remove$7(component, replaceConfig, replaceState, replacee);
  7192. replacer.each(function (r) {
  7193. insert(component, replaceConfig, function (p, c) {
  7194. appendAt(p, c, replaceeIndex);
  7195. }, r);
  7196. });
  7197. return replacee;
  7198. });
  7199. };
  7200. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  7201. var children = contents(component);
  7202. return findIndex(children, replaceePred).bind(function (replaceeIndex) {
  7203. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  7204. });
  7205. };
  7206. var ReplaceApis = /*#__PURE__*/Object.freeze({
  7207. __proto__: null,
  7208. append: append$2,
  7209. prepend: prepend$1,
  7210. remove: remove$7,
  7211. replaceAt: replaceAt,
  7212. replaceBy: replaceBy,
  7213. set: set$5,
  7214. contents: contents
  7215. });
  7216. var Replacing = create$1({
  7217. fields: [],
  7218. name: 'replacing',
  7219. apis: ReplaceApis
  7220. });
  7221. var events$4 = function (name, eventHandlers) {
  7222. var events = derive(eventHandlers);
  7223. return create$1({
  7224. fields: [strict$1('enabled')],
  7225. name: name,
  7226. active: { events: constant(events) }
  7227. });
  7228. };
  7229. var config = function (name, eventHandlers) {
  7230. var me = events$4(name, eventHandlers);
  7231. return {
  7232. key: name,
  7233. value: {
  7234. config: {},
  7235. me: me,
  7236. configAsRaw: constant({}),
  7237. initialConfig: {},
  7238. state: NoState
  7239. }
  7240. };
  7241. };
  7242. var focus$2 = function (component, focusConfig) {
  7243. if (!focusConfig.ignore) {
  7244. focus$1(component.element());
  7245. focusConfig.onFocus(component);
  7246. }
  7247. };
  7248. var blur$1 = function (component, focusConfig) {
  7249. if (!focusConfig.ignore) {
  7250. blur(component.element());
  7251. }
  7252. };
  7253. var isFocused = function (component) {
  7254. return hasFocus(component.element());
  7255. };
  7256. var FocusApis = /*#__PURE__*/Object.freeze({
  7257. __proto__: null,
  7258. focus: focus$2,
  7259. blur: blur$1,
  7260. isFocused: isFocused
  7261. });
  7262. var exhibit$1 = function (base, focusConfig) {
  7263. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  7264. return nu$6(mod);
  7265. };
  7266. var events$5 = function (focusConfig) {
  7267. return derive([run(focus(), function (component, simulatedEvent) {
  7268. focus$2(component, focusConfig);
  7269. simulatedEvent.stop();
  7270. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  7271. simulatedEvent.event().prevent();
  7272. })] : []));
  7273. };
  7274. var ActiveFocus = /*#__PURE__*/Object.freeze({
  7275. __proto__: null,
  7276. exhibit: exhibit$1,
  7277. events: events$5
  7278. });
  7279. var FocusSchema = [
  7280. onHandler('onFocus'),
  7281. defaulted$1('stopMousedown', false),
  7282. defaulted$1('ignore', false)
  7283. ];
  7284. var Focusing = create$1({
  7285. fields: FocusSchema,
  7286. name: 'focusing',
  7287. active: ActiveFocus,
  7288. apis: FocusApis
  7289. });
  7290. var updateAriaState = function (component, toggleConfig, toggleState) {
  7291. var ariaInfo = toggleConfig.aria;
  7292. ariaInfo.update(component, ariaInfo, toggleState.get());
  7293. };
  7294. var updateClass = function (component, toggleConfig, toggleState) {
  7295. toggleConfig.toggleClass.each(function (toggleClass) {
  7296. if (toggleState.get()) {
  7297. add$2(component.element(), toggleClass);
  7298. } else {
  7299. remove$4(component.element(), toggleClass);
  7300. }
  7301. });
  7302. };
  7303. var toggle = function (component, toggleConfig, toggleState) {
  7304. set$6(component, toggleConfig, toggleState, !toggleState.get());
  7305. };
  7306. var on$1 = function (component, toggleConfig, toggleState) {
  7307. toggleState.set(true);
  7308. updateClass(component, toggleConfig, toggleState);
  7309. updateAriaState(component, toggleConfig, toggleState);
  7310. };
  7311. var off = function (component, toggleConfig, toggleState) {
  7312. toggleState.set(false);
  7313. updateClass(component, toggleConfig, toggleState);
  7314. updateAriaState(component, toggleConfig, toggleState);
  7315. };
  7316. var set$6 = function (component, toggleConfig, toggleState, state) {
  7317. var action = state ? on$1 : off;
  7318. action(component, toggleConfig, toggleState);
  7319. };
  7320. var isOn = function (component, toggleConfig, toggleState) {
  7321. return toggleState.get();
  7322. };
  7323. var onLoad$4 = function (component, toggleConfig, toggleState) {
  7324. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  7325. };
  7326. var ToggleApis = /*#__PURE__*/Object.freeze({
  7327. __proto__: null,
  7328. onLoad: onLoad$4,
  7329. toggle: toggle,
  7330. isOn: isOn,
  7331. on: on$1,
  7332. off: off,
  7333. set: set$6
  7334. });
  7335. var exhibit$2 = function () {
  7336. return nu$6({});
  7337. };
  7338. var events$6 = function (toggleConfig, toggleState) {
  7339. var execute = executeEvent(toggleConfig, toggleState, toggle);
  7340. var load = loadEvent(toggleConfig, toggleState, onLoad$4);
  7341. return derive(flatten([
  7342. toggleConfig.toggleOnExecute ? [execute] : [],
  7343. [load]
  7344. ]));
  7345. };
  7346. var ActiveToggle = /*#__PURE__*/Object.freeze({
  7347. __proto__: null,
  7348. exhibit: exhibit$2,
  7349. events: events$6
  7350. });
  7351. var SetupBehaviourCellState = function (initialState) {
  7352. var init = function () {
  7353. var cell = Cell(initialState);
  7354. var get = function () {
  7355. return cell.get();
  7356. };
  7357. var set = function (newState) {
  7358. return cell.set(newState);
  7359. };
  7360. var clear = function () {
  7361. return cell.set(initialState);
  7362. };
  7363. var readState = function () {
  7364. return cell.get();
  7365. };
  7366. return {
  7367. get: get,
  7368. set: set,
  7369. clear: clear,
  7370. readState: readState
  7371. };
  7372. };
  7373. return { init: init };
  7374. };
  7375. var updatePressed = function (component, ariaInfo, status) {
  7376. set$1(component.element(), 'aria-pressed', status);
  7377. if (ariaInfo.syncWithExpanded) {
  7378. updateExpanded(component, ariaInfo, status);
  7379. }
  7380. };
  7381. var updateSelected = function (component, ariaInfo, status) {
  7382. set$1(component.element(), 'aria-selected', status);
  7383. };
  7384. var updateChecked = function (component, ariaInfo, status) {
  7385. set$1(component.element(), 'aria-checked', status);
  7386. };
  7387. var updateExpanded = function (component, ariaInfo, status) {
  7388. set$1(component.element(), 'aria-expanded', status);
  7389. };
  7390. var ToggleSchema = [
  7391. defaulted$1('selected', false),
  7392. option('toggleClass'),
  7393. defaulted$1('toggleOnExecute', true),
  7394. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  7395. pressed: [
  7396. defaulted$1('syncWithExpanded', false),
  7397. output('update', updatePressed)
  7398. ],
  7399. checked: [output('update', updateChecked)],
  7400. expanded: [output('update', updateExpanded)],
  7401. selected: [output('update', updateSelected)],
  7402. none: [output('update', noop)]
  7403. }))
  7404. ];
  7405. var Toggling = create$1({
  7406. fields: ToggleSchema,
  7407. name: 'toggling',
  7408. active: ActiveToggle,
  7409. apis: ToggleApis,
  7410. state: SetupBehaviourCellState(false)
  7411. });
  7412. var pointerEvents = function () {
  7413. var onClick = function (component, simulatedEvent) {
  7414. simulatedEvent.stop();
  7415. emitExecute(component);
  7416. };
  7417. return [
  7418. run(click(), onClick),
  7419. run(tap(), onClick),
  7420. cutter(touchstart()),
  7421. cutter(mousedown())
  7422. ];
  7423. };
  7424. var events$7 = function (optAction) {
  7425. var executeHandler = function (action) {
  7426. return runOnExecute(function (component, simulatedEvent) {
  7427. action(component);
  7428. simulatedEvent.stop();
  7429. });
  7430. };
  7431. return derive(flatten([
  7432. optAction.map(executeHandler).toArray(),
  7433. pointerEvents()
  7434. ]));
  7435. };
  7436. var hoverEvent = 'alloy.item-hover';
  7437. var focusEvent = 'alloy.item-focus';
  7438. var onHover = function (item) {
  7439. if (search(item.element()).isNone() || Focusing.isFocused(item)) {
  7440. if (!Focusing.isFocused(item)) {
  7441. Focusing.focus(item);
  7442. }
  7443. emitWith(item, hoverEvent, { item: item });
  7444. }
  7445. };
  7446. var onFocus = function (item) {
  7447. emitWith(item, focusEvent, { item: item });
  7448. };
  7449. var hover = constant(hoverEvent);
  7450. var focus$3 = constant(focusEvent);
  7451. var builder = function (detail) {
  7452. return {
  7453. dom: detail.dom,
  7454. 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 } : {}) }),
  7455. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7456. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7457. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7458. }),
  7459. Focusing.config({
  7460. ignore: detail.ignoreFocus,
  7461. stopMousedown: detail.ignoreFocus,
  7462. onFocus: function (component) {
  7463. onFocus(component);
  7464. }
  7465. }),
  7466. Keying.config({ mode: 'execution' }),
  7467. Representing.config({
  7468. store: {
  7469. mode: 'memory',
  7470. initialValue: detail.data
  7471. }
  7472. }),
  7473. config('item-type-events', __spreadArrays(pointerEvents(), [
  7474. run(mouseover(), onHover),
  7475. run(focusItem(), Focusing.focus)
  7476. ]))
  7477. ]),
  7478. components: detail.components,
  7479. eventOrder: detail.eventOrder
  7480. };
  7481. };
  7482. var schema$a = [
  7483. strict$1('data'),
  7484. strict$1('components'),
  7485. strict$1('dom'),
  7486. defaulted$1('hasSubmenu', false),
  7487. option('toggling'),
  7488. SketchBehaviours.field('itemBehaviours', [
  7489. Toggling,
  7490. Focusing,
  7491. Keying,
  7492. Representing
  7493. ]),
  7494. defaulted$1('ignoreFocus', false),
  7495. defaulted$1('domModification', {}),
  7496. output('builder', builder),
  7497. defaulted$1('eventOrder', {})
  7498. ];
  7499. var builder$1 = function (detail) {
  7500. return {
  7501. dom: detail.dom,
  7502. components: detail.components,
  7503. events: derive([stopper(focusItem())])
  7504. };
  7505. };
  7506. var schema$b = [
  7507. strict$1('dom'),
  7508. strict$1('components'),
  7509. output('builder', builder$1)
  7510. ];
  7511. var owner$2 = function () {
  7512. return 'item-widget';
  7513. };
  7514. var parts = constant([required({
  7515. name: 'widget',
  7516. overrides: function (detail) {
  7517. return {
  7518. behaviours: derive$1([Representing.config({
  7519. store: {
  7520. mode: 'manual',
  7521. getValue: function (_component) {
  7522. return detail.data;
  7523. },
  7524. setValue: function () {
  7525. }
  7526. }
  7527. })])
  7528. };
  7529. }
  7530. })]);
  7531. var builder$2 = function (detail) {
  7532. var subs = substitutes(owner$2(), detail, parts());
  7533. var components$1 = components(owner$2(), detail, subs.internals());
  7534. var focusWidget = function (component) {
  7535. return getPart(component, detail, 'widget').map(function (widget) {
  7536. Keying.focusIn(widget);
  7537. return widget;
  7538. });
  7539. };
  7540. var onHorizontalArrow = function (component, simulatedEvent) {
  7541. return inside(simulatedEvent.event().target()) ? Option.none() : function () {
  7542. if (detail.autofocus) {
  7543. simulatedEvent.setSource(component.element());
  7544. return Option.none();
  7545. } else {
  7546. return Option.none();
  7547. }
  7548. }();
  7549. };
  7550. return {
  7551. dom: detail.dom,
  7552. components: components$1,
  7553. domModification: detail.domModification,
  7554. events: derive([
  7555. runOnExecute(function (component, simulatedEvent) {
  7556. focusWidget(component).each(function (_widget) {
  7557. simulatedEvent.stop();
  7558. });
  7559. }),
  7560. run(mouseover(), onHover),
  7561. run(focusItem(), function (component, _simulatedEvent) {
  7562. if (detail.autofocus) {
  7563. focusWidget(component);
  7564. } else {
  7565. Focusing.focus(component);
  7566. }
  7567. })
  7568. ]),
  7569. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7570. Representing.config({
  7571. store: {
  7572. mode: 'memory',
  7573. initialValue: detail.data
  7574. }
  7575. }),
  7576. Focusing.config({
  7577. ignore: detail.ignoreFocus,
  7578. onFocus: function (component) {
  7579. onFocus(component);
  7580. }
  7581. }),
  7582. Keying.config({
  7583. mode: 'special',
  7584. focusIn: detail.autofocus ? function (component) {
  7585. focusWidget(component);
  7586. } : revoke(),
  7587. onLeft: onHorizontalArrow,
  7588. onRight: onHorizontalArrow,
  7589. onEscape: function (component, simulatedEvent) {
  7590. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7591. Focusing.focus(component);
  7592. return Option.some(true);
  7593. } else if (detail.autofocus) {
  7594. simulatedEvent.setSource(component.element());
  7595. return Option.none();
  7596. } else {
  7597. return Option.none();
  7598. }
  7599. }
  7600. })
  7601. ])
  7602. };
  7603. };
  7604. var schema$c = [
  7605. strict$1('uid'),
  7606. strict$1('data'),
  7607. strict$1('components'),
  7608. strict$1('dom'),
  7609. defaulted$1('autofocus', false),
  7610. defaulted$1('ignoreFocus', false),
  7611. SketchBehaviours.field('widgetBehaviours', [
  7612. Representing,
  7613. Focusing,
  7614. Keying
  7615. ]),
  7616. defaulted$1('domModification', {}),
  7617. defaultUidsSchema(parts()),
  7618. output('builder', builder$2)
  7619. ];
  7620. var itemSchema$1 = choose$1('type', {
  7621. widget: schema$c,
  7622. item: schema$a,
  7623. separator: schema$b
  7624. });
  7625. var configureGrid = function (detail, movementInfo) {
  7626. return {
  7627. mode: 'flatgrid',
  7628. selector: '.' + detail.markers.item,
  7629. initSize: {
  7630. numColumns: movementInfo.initSize.numColumns,
  7631. numRows: movementInfo.initSize.numRows
  7632. },
  7633. focusManager: detail.focusManager
  7634. };
  7635. };
  7636. var configureMatrix = function (detail, movementInfo) {
  7637. return {
  7638. mode: 'matrix',
  7639. selectors: {
  7640. row: movementInfo.rowSelector,
  7641. cell: '.' + detail.markers.item
  7642. },
  7643. focusManager: detail.focusManager
  7644. };
  7645. };
  7646. var configureMenu = function (detail, movementInfo) {
  7647. return {
  7648. mode: 'menu',
  7649. selector: '.' + detail.markers.item,
  7650. moveOnTab: movementInfo.moveOnTab,
  7651. focusManager: detail.focusManager
  7652. };
  7653. };
  7654. var parts$1 = constant([group({
  7655. factory: {
  7656. sketch: function (spec) {
  7657. var itemInfo = asRawOrDie('menu.spec item', itemSchema$1, spec);
  7658. return itemInfo.builder(itemInfo);
  7659. }
  7660. },
  7661. name: 'items',
  7662. unit: 'item',
  7663. defaults: function (detail, u) {
  7664. return u.hasOwnProperty('uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  7665. },
  7666. overrides: function (detail, u) {
  7667. return {
  7668. type: u.type,
  7669. ignoreFocus: detail.fakeFocus,
  7670. domModification: { classes: [detail.markers.item] }
  7671. };
  7672. }
  7673. })]);
  7674. var schema$d = constant([
  7675. strict$1('value'),
  7676. strict$1('items'),
  7677. strict$1('dom'),
  7678. strict$1('components'),
  7679. defaulted$1('eventOrder', {}),
  7680. field$1('menuBehaviours', [
  7681. Highlighting,
  7682. Representing,
  7683. Composing,
  7684. Keying
  7685. ]),
  7686. defaultedOf('movement', {
  7687. mode: 'menu',
  7688. moveOnTab: true
  7689. }, choose$1('mode', {
  7690. grid: [
  7691. initSize(),
  7692. output('config', configureGrid)
  7693. ],
  7694. matrix: [
  7695. output('config', configureMatrix),
  7696. strict$1('rowSelector')
  7697. ],
  7698. menu: [
  7699. defaulted$1('moveOnTab', true),
  7700. output('config', configureMenu)
  7701. ]
  7702. })),
  7703. itemMarkers(),
  7704. defaulted$1('fakeFocus', false),
  7705. defaulted$1('focusManager', dom()),
  7706. onHandler('onHighlight')
  7707. ]);
  7708. var focus$4 = constant('alloy.menu-focus');
  7709. var make$1 = function (detail, components, _spec, _externals) {
  7710. return {
  7711. uid: detail.uid,
  7712. dom: detail.dom,
  7713. markers: detail.markers,
  7714. behaviours: augment(detail.menuBehaviours, [
  7715. Highlighting.config({
  7716. highlightClass: detail.markers.selectedItem,
  7717. itemClass: detail.markers.item,
  7718. onHighlight: detail.onHighlight
  7719. }),
  7720. Representing.config({
  7721. store: {
  7722. mode: 'memory',
  7723. initialValue: detail.value
  7724. }
  7725. }),
  7726. Composing.config({ find: Option.some }),
  7727. Keying.config(detail.movement.config(detail, detail.movement))
  7728. ]),
  7729. events: derive([
  7730. run(focus$3(), function (menu, simulatedEvent) {
  7731. var event = simulatedEvent.event();
  7732. menu.getSystem().getByDom(event.target()).each(function (item) {
  7733. Highlighting.highlight(menu, item);
  7734. simulatedEvent.stop();
  7735. emitWith(menu, focus$4(), {
  7736. menu: menu,
  7737. item: item
  7738. });
  7739. });
  7740. }),
  7741. run(hover(), function (menu, simulatedEvent) {
  7742. var item = simulatedEvent.event().item();
  7743. Highlighting.highlight(menu, item);
  7744. })
  7745. ]),
  7746. components: components,
  7747. eventOrder: detail.eventOrder,
  7748. domModification: { attributes: { role: 'menu' } }
  7749. };
  7750. };
  7751. var Menu = composite$1({
  7752. name: 'Menu',
  7753. configFields: schema$d(),
  7754. partFields: parts$1(),
  7755. factory: make$1
  7756. });
  7757. var transpose = function (obj) {
  7758. return tupleMap(obj, function (v, k) {
  7759. return {
  7760. k: v,
  7761. v: k
  7762. };
  7763. });
  7764. };
  7765. var trace = function (items, byItem, byMenu, finish) {
  7766. return get(byMenu, finish).bind(function (triggerItem) {
  7767. return get(items, triggerItem).bind(function (triggerMenu) {
  7768. var rest = trace(items, byItem, byMenu, triggerMenu);
  7769. return Option.some([triggerMenu].concat(rest));
  7770. });
  7771. }).getOr([]);
  7772. };
  7773. var generate$5 = function (menus, expansions) {
  7774. var items = {};
  7775. each$1(menus, function (menuItems, menu) {
  7776. each(menuItems, function (item) {
  7777. items[item] = menu;
  7778. });
  7779. });
  7780. var byItem = expansions;
  7781. var byMenu = transpose(expansions);
  7782. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  7783. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  7784. });
  7785. return map$1(items, function (menu) {
  7786. return get(menuPaths, menu).getOr([menu]);
  7787. });
  7788. };
  7789. var init$3 = function () {
  7790. var expansions = Cell({});
  7791. var menus = Cell({});
  7792. var paths = Cell({});
  7793. var primary = Cell(Option.none());
  7794. var directory = Cell({});
  7795. var clear = function () {
  7796. expansions.set({});
  7797. menus.set({});
  7798. paths.set({});
  7799. primary.set(Option.none());
  7800. };
  7801. var isClear = function () {
  7802. return primary.get().isNone();
  7803. };
  7804. var setMenuBuilt = function (menuName, built) {
  7805. var _a;
  7806. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  7807. type: 'prepared',
  7808. menu: built
  7809. }, _a)));
  7810. };
  7811. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  7812. primary.set(Option.some(sPrimary));
  7813. expansions.set(sExpansions);
  7814. menus.set(sMenus);
  7815. directory.set(dir);
  7816. var sPaths = generate$5(dir, sExpansions);
  7817. paths.set(sPaths);
  7818. };
  7819. var getTriggeringItem = function (menuValue) {
  7820. return find$1(expansions.get(), function (v, _k) {
  7821. return v === menuValue;
  7822. });
  7823. };
  7824. var getTriggerData = function (menuValue, getItemByValue, path) {
  7825. return getPreparedMenu(menuValue).bind(function (menu) {
  7826. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  7827. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  7828. return {
  7829. triggeredMenu: menu,
  7830. triggeringItem: triggeredItem,
  7831. triggeringPath: path
  7832. };
  7833. });
  7834. });
  7835. });
  7836. };
  7837. var getTriggeringPath = function (itemValue, getItemByValue) {
  7838. var extraPath = filter(lookupItem(itemValue).toArray(), function (menuValue) {
  7839. return getPreparedMenu(menuValue).isSome();
  7840. });
  7841. return get(paths.get(), itemValue).bind(function (path) {
  7842. var revPath = reverse(extraPath.concat(path));
  7843. var triggers = bind(revPath, function (menuValue, menuIndex) {
  7844. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  7845. return primary.get().is(menuValue) ? [] : [Option.none()];
  7846. }, function (data) {
  7847. return [Option.some(data)];
  7848. });
  7849. });
  7850. return sequence(triggers);
  7851. });
  7852. };
  7853. var expand = function (itemValue) {
  7854. return get(expansions.get(), itemValue).map(function (menu) {
  7855. var current = get(paths.get(), itemValue).getOr([]);
  7856. return [menu].concat(current);
  7857. });
  7858. };
  7859. var collapse = function (itemValue) {
  7860. return get(paths.get(), itemValue).bind(function (path) {
  7861. return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
  7862. });
  7863. };
  7864. var refresh = function (itemValue) {
  7865. return get(paths.get(), itemValue);
  7866. };
  7867. var getPreparedMenu = function (menuValue) {
  7868. return lookupMenu(menuValue).bind(extractPreparedMenu);
  7869. };
  7870. var lookupMenu = function (menuValue) {
  7871. return get(menus.get(), menuValue);
  7872. };
  7873. var lookupItem = function (itemValue) {
  7874. return get(expansions.get(), itemValue);
  7875. };
  7876. var otherMenus = function (path) {
  7877. var menuValues = directory.get();
  7878. return difference(keys(menuValues), path);
  7879. };
  7880. var getPrimary = function () {
  7881. return primary.get().bind(getPreparedMenu);
  7882. };
  7883. var getMenus = function () {
  7884. return menus.get();
  7885. };
  7886. return {
  7887. setMenuBuilt: setMenuBuilt,
  7888. setContents: setContents,
  7889. expand: expand,
  7890. refresh: refresh,
  7891. collapse: collapse,
  7892. lookupMenu: lookupMenu,
  7893. lookupItem: lookupItem,
  7894. otherMenus: otherMenus,
  7895. getPrimary: getPrimary,
  7896. getMenus: getMenus,
  7897. clear: clear,
  7898. isClear: isClear,
  7899. getTriggeringPath: getTriggeringPath
  7900. };
  7901. };
  7902. var extractPreparedMenu = function (prep) {
  7903. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7904. };
  7905. var LayeredState = {
  7906. init: init$3,
  7907. extractPreparedMenu: extractPreparedMenu
  7908. };
  7909. var make$2 = function (detail, _rawUiSpec) {
  7910. var submenuParentItems = Cell(Option.none());
  7911. var buildMenus = function (container, primaryName, menus) {
  7912. return map$1(menus, function (spec, name) {
  7913. var makeSketch = function () {
  7914. return Menu.sketch(__assign(__assign({ dom: spec.dom }, spec), {
  7915. value: name,
  7916. items: spec.items,
  7917. markers: detail.markers,
  7918. fakeFocus: detail.fakeFocus,
  7919. onHighlight: detail.onHighlight,
  7920. focusManager: detail.fakeFocus ? highlights() : dom()
  7921. }));
  7922. };
  7923. return name === primaryName ? {
  7924. type: 'prepared',
  7925. menu: container.getSystem().build(makeSketch())
  7926. } : {
  7927. type: 'notbuilt',
  7928. nbMenu: makeSketch
  7929. };
  7930. });
  7931. };
  7932. var layeredState = LayeredState.init();
  7933. var setup = function (container) {
  7934. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  7935. var directory = toDirectory();
  7936. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  7937. return layeredState.getPrimary();
  7938. };
  7939. var getItemValue = function (item) {
  7940. return Representing.getValue(item).value;
  7941. };
  7942. var getItemByValue = function (_container, menus, itemValue) {
  7943. return findMap(menus, function (menu) {
  7944. if (!menu.getSystem().isConnected()) {
  7945. return Option.none();
  7946. }
  7947. var candidates = Highlighting.getCandidates(menu);
  7948. return find(candidates, function (c) {
  7949. return getItemValue(c) === itemValue;
  7950. });
  7951. });
  7952. };
  7953. var toDirectory = function (_container) {
  7954. return map$1(detail.data.menus, function (data, _menuName) {
  7955. return bind(data.items, function (item) {
  7956. return item.type === 'separator' ? [] : [item.data.value];
  7957. });
  7958. });
  7959. };
  7960. var setActiveMenu = function (container, menu) {
  7961. Highlighting.highlight(container, menu);
  7962. Highlighting.getHighlighted(menu).orThunk(function () {
  7963. return Highlighting.getFirst(menu);
  7964. }).each(function (item) {
  7965. dispatch(container, item.element(), focusItem());
  7966. });
  7967. };
  7968. var getMenus = function (state, menuValues) {
  7969. return cat(map(menuValues, function (mv) {
  7970. return state.lookupMenu(mv).bind(function (prep) {
  7971. return prep.type === 'prepared' ? Option.some(prep.menu) : Option.none();
  7972. });
  7973. }));
  7974. };
  7975. var closeOthers = function (container, state, path) {
  7976. var others = getMenus(state, state.otherMenus(path));
  7977. each(others, function (o) {
  7978. remove$5(o.element(), [detail.markers.backgroundMenu]);
  7979. if (!detail.stayInDom) {
  7980. Replacing.remove(container, o);
  7981. }
  7982. });
  7983. };
  7984. var getSubmenuParents = function (container) {
  7985. return submenuParentItems.get().getOrThunk(function () {
  7986. var r = {};
  7987. var items = descendants(container.element(), '.' + detail.markers.item);
  7988. var parentItems = filter(items, function (i) {
  7989. return get$2(i, 'aria-haspopup') === 'true';
  7990. });
  7991. each(parentItems, function (i) {
  7992. container.getSystem().getByDom(i).each(function (itemComp) {
  7993. var key = getItemValue(itemComp);
  7994. r[key] = itemComp;
  7995. });
  7996. });
  7997. submenuParentItems.set(Option.some(r));
  7998. return r;
  7999. });
  8000. };
  8001. var updateAriaExpansions = function (container, path) {
  8002. var parentItems = getSubmenuParents(container);
  8003. each$1(parentItems, function (v, k) {
  8004. var expanded = contains(path, k);
  8005. set$1(v.element(), 'aria-expanded', expanded);
  8006. });
  8007. };
  8008. var updateMenuPath = function (container, state, path) {
  8009. return Option.from(path[0]).bind(function (latestMenuName) {
  8010. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8011. if (menuPrep.type === 'notbuilt') {
  8012. return Option.none();
  8013. } else {
  8014. var activeMenu = menuPrep.menu;
  8015. var rest = getMenus(state, path.slice(1));
  8016. each(rest, function (r) {
  8017. add$2(r.element(), detail.markers.backgroundMenu);
  8018. });
  8019. if (!inBody(activeMenu.element())) {
  8020. Replacing.append(container, premade$1(activeMenu));
  8021. }
  8022. remove$5(activeMenu.element(), [detail.markers.backgroundMenu]);
  8023. setActiveMenu(container, activeMenu);
  8024. closeOthers(container, state, path);
  8025. return Option.some(activeMenu);
  8026. }
  8027. });
  8028. });
  8029. };
  8030. var ExpandHighlightDecision;
  8031. (function (ExpandHighlightDecision) {
  8032. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8033. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8034. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8035. var buildIfRequired = function (container, menuName, menuPrep) {
  8036. if (menuPrep.type === 'notbuilt') {
  8037. var menu = container.getSystem().build(menuPrep.nbMenu());
  8038. layeredState.setMenuBuilt(menuName, menu);
  8039. return menu;
  8040. } else {
  8041. return menuPrep.menu;
  8042. }
  8043. };
  8044. var expandRight = function (container, item, decision) {
  8045. if (decision === void 0) {
  8046. decision = ExpandHighlightDecision.HighlightSubmenu;
  8047. }
  8048. var value = getItemValue(item);
  8049. return layeredState.expand(value).bind(function (path) {
  8050. updateAriaExpansions(container, path);
  8051. return Option.from(path[0]).bind(function (menuName) {
  8052. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8053. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8054. if (!inBody(activeMenu.element())) {
  8055. Replacing.append(container, premade$1(activeMenu));
  8056. }
  8057. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8058. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8059. Highlighting.highlightFirst(activeMenu);
  8060. return updateMenuPath(container, layeredState, path);
  8061. } else {
  8062. Highlighting.dehighlightAll(activeMenu);
  8063. return Option.some(item);
  8064. }
  8065. });
  8066. });
  8067. });
  8068. };
  8069. var collapseLeft = function (container, item) {
  8070. var value = getItemValue(item);
  8071. return layeredState.collapse(value).bind(function (path) {
  8072. updateAriaExpansions(container, path);
  8073. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8074. detail.onCollapseMenu(container, item, activeMenu);
  8075. return activeMenu;
  8076. });
  8077. });
  8078. };
  8079. var updateView = function (container, item) {
  8080. var value = getItemValue(item);
  8081. return layeredState.refresh(value).bind(function (path) {
  8082. updateAriaExpansions(container, path);
  8083. return updateMenuPath(container, layeredState, path);
  8084. });
  8085. };
  8086. var onRight = function (container, item) {
  8087. return inside(item.element()) ? Option.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8088. };
  8089. var onLeft = function (container, item) {
  8090. return inside(item.element()) ? Option.none() : collapseLeft(container, item);
  8091. };
  8092. var onEscape = function (container, item) {
  8093. return collapseLeft(container, item).orThunk(function () {
  8094. return detail.onEscape(container, item).map(function () {
  8095. return container;
  8096. });
  8097. });
  8098. };
  8099. var keyOnItem = function (f) {
  8100. return function (container, simulatedEvent) {
  8101. return closest$3(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8102. return container.getSystem().getByDom(target).toOption().bind(function (item) {
  8103. return f(container, item).map(function () {
  8104. return true;
  8105. });
  8106. });
  8107. });
  8108. };
  8109. };
  8110. var events = derive([
  8111. run(focus$4(), function (sandbox, simulatedEvent) {
  8112. var item = simulatedEvent.event().item();
  8113. layeredState.lookupItem(getItemValue(item)).each(function () {
  8114. var menu = simulatedEvent.event().menu();
  8115. Highlighting.highlight(sandbox, menu);
  8116. var value = getItemValue(simulatedEvent.event().item());
  8117. layeredState.refresh(value).each(function (path) {
  8118. return closeOthers(sandbox, layeredState, path);
  8119. });
  8120. });
  8121. }),
  8122. runOnExecute(function (component, simulatedEvent) {
  8123. var target = simulatedEvent.event().target();
  8124. component.getSystem().getByDom(target).each(function (item) {
  8125. var itemValue = getItemValue(item);
  8126. if (itemValue.indexOf('collapse-item') === 0) {
  8127. collapseLeft(component, item);
  8128. }
  8129. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8130. detail.onExecute(component, item);
  8131. }, function () {
  8132. });
  8133. });
  8134. }),
  8135. runOnAttached(function (container, _simulatedEvent) {
  8136. setup(container).each(function (primary) {
  8137. Replacing.append(container, premade$1(primary));
  8138. detail.onOpenMenu(container, primary);
  8139. if (detail.highlightImmediately) {
  8140. setActiveMenu(container, primary);
  8141. }
  8142. });
  8143. })
  8144. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8145. var item = simulatedEvent.event().item();
  8146. updateView(sandbox, item);
  8147. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8148. detail.onHover(sandbox, item);
  8149. })] : []));
  8150. var getActiveItem = function (container) {
  8151. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8152. };
  8153. var collapseMenuApi = function (container) {
  8154. getActiveItem(container).each(function (currentItem) {
  8155. collapseLeft(container, currentItem);
  8156. });
  8157. };
  8158. var highlightPrimary = function (container) {
  8159. layeredState.getPrimary().each(function (primary) {
  8160. setActiveMenu(container, primary);
  8161. });
  8162. };
  8163. var extractMenuFromContainer = function (container) {
  8164. return Option.from(container.components()[0]).filter(function (comp) {
  8165. return get$2(comp.element(), 'role') === 'menu';
  8166. });
  8167. };
  8168. var repositionMenus = function (container) {
  8169. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8170. return getActiveItem(container).bind(function (currentItem) {
  8171. var itemValue = getItemValue(currentItem);
  8172. var allMenus = values(layeredState.getMenus());
  8173. var preparedMenus = cat(map(allMenus, LayeredState.extractPreparedMenu));
  8174. return layeredState.getTriggeringPath(itemValue, function (v) {
  8175. return getItemByValue(container, preparedMenus, v);
  8176. });
  8177. }).map(function (triggeringPath) {
  8178. return {
  8179. primary: primary,
  8180. triggeringPath: triggeringPath
  8181. };
  8182. });
  8183. });
  8184. maybeActivePrimary.fold(function () {
  8185. extractMenuFromContainer(container).each(function (primaryMenu) {
  8186. detail.onRepositionMenu(container, primaryMenu, []);
  8187. });
  8188. }, function (_a) {
  8189. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8190. detail.onRepositionMenu(container, primary, triggeringPath);
  8191. });
  8192. };
  8193. var apis = {
  8194. collapseMenu: collapseMenuApi,
  8195. highlightPrimary: highlightPrimary,
  8196. repositionMenus: repositionMenus
  8197. };
  8198. return {
  8199. uid: detail.uid,
  8200. dom: detail.dom,
  8201. markers: detail.markers,
  8202. behaviours: augment(detail.tmenuBehaviours, [
  8203. Keying.config({
  8204. mode: 'special',
  8205. onRight: keyOnItem(onRight),
  8206. onLeft: keyOnItem(onLeft),
  8207. onEscape: keyOnItem(onEscape),
  8208. focusIn: function (container, _keyInfo) {
  8209. layeredState.getPrimary().each(function (primary) {
  8210. dispatch(container, primary.element(), focusItem());
  8211. });
  8212. }
  8213. }),
  8214. Highlighting.config({
  8215. highlightClass: detail.markers.selectedMenu,
  8216. itemClass: detail.markers.menu
  8217. }),
  8218. Composing.config({
  8219. find: function (container) {
  8220. return Highlighting.getHighlighted(container);
  8221. }
  8222. }),
  8223. Replacing.config({})
  8224. ]),
  8225. eventOrder: detail.eventOrder,
  8226. apis: apis,
  8227. events: events
  8228. };
  8229. };
  8230. var collapseItem = constant('collapse-item');
  8231. var tieredData = function (primary, menus, expansions) {
  8232. return {
  8233. primary: primary,
  8234. menus: menus,
  8235. expansions: expansions
  8236. };
  8237. };
  8238. var singleData = function (name, menu) {
  8239. return {
  8240. primary: name,
  8241. menus: wrap$1(name, menu),
  8242. expansions: {}
  8243. };
  8244. };
  8245. var collapseItem$1 = function (text) {
  8246. return {
  8247. value: generate$1(collapseItem()),
  8248. meta: { text: text }
  8249. };
  8250. };
  8251. var tieredMenu = single$2({
  8252. name: 'TieredMenu',
  8253. configFields: [
  8254. onStrictKeyboardHandler('onExecute'),
  8255. onStrictKeyboardHandler('onEscape'),
  8256. onStrictHandler('onOpenMenu'),
  8257. onStrictHandler('onOpenSubmenu'),
  8258. onHandler('onRepositionMenu'),
  8259. onHandler('onCollapseMenu'),
  8260. defaulted$1('highlightImmediately', true),
  8261. strictObjOf('data', [
  8262. strict$1('primary'),
  8263. strict$1('menus'),
  8264. strict$1('expansions')
  8265. ]),
  8266. defaulted$1('fakeFocus', false),
  8267. onHandler('onHighlight'),
  8268. onHandler('onHover'),
  8269. tieredMenuMarkers(),
  8270. strict$1('dom'),
  8271. defaulted$1('navigateOnHover', true),
  8272. defaulted$1('stayInDom', false),
  8273. field$1('tmenuBehaviours', [
  8274. Keying,
  8275. Highlighting,
  8276. Composing,
  8277. Replacing
  8278. ]),
  8279. defaulted$1('eventOrder', {})
  8280. ],
  8281. apis: {
  8282. collapseMenu: function (apis, tmenu) {
  8283. apis.collapseMenu(tmenu);
  8284. },
  8285. highlightPrimary: function (apis, tmenu) {
  8286. apis.highlightPrimary(tmenu);
  8287. },
  8288. repositionMenus: function (apis, tmenu) {
  8289. apis.repositionMenus(tmenu);
  8290. }
  8291. },
  8292. factory: make$2,
  8293. extraApis: {
  8294. tieredData: tieredData,
  8295. singleData: singleData,
  8296. collapseItem: collapseItem$1
  8297. }
  8298. });
  8299. var makeMenu = function (detail, menuSandbox, anchor, menuSpec, getBounds) {
  8300. var lazySink = function () {
  8301. return detail.lazySink(menuSandbox);
  8302. };
  8303. var layouts = menuSpec.type === 'horizontal' ? {
  8304. layouts: {
  8305. onLtr: function () {
  8306. return belowOrAbove();
  8307. },
  8308. onRtl: function () {
  8309. return belowOrAboveRtl();
  8310. }
  8311. }
  8312. } : {};
  8313. var isFirstTierSubmenu = function (triggeringPaths) {
  8314. return triggeringPaths.length === 2;
  8315. };
  8316. var getSubmenuLayouts = function (triggeringPaths) {
  8317. return isFirstTierSubmenu(triggeringPaths) ? layouts : {};
  8318. };
  8319. return tieredMenu.sketch({
  8320. dom: { tag: 'div' },
  8321. data: menuSpec.data,
  8322. markers: menuSpec.menu.markers,
  8323. highlightImmediately: menuSpec.menu.highlightImmediately,
  8324. onEscape: function () {
  8325. Sandboxing.close(menuSandbox);
  8326. detail.onEscape.map(function (handler) {
  8327. return handler(menuSandbox);
  8328. });
  8329. return Option.some(true);
  8330. },
  8331. onExecute: function () {
  8332. return Option.some(true);
  8333. },
  8334. onOpenMenu: function (tmenu, menu) {
  8335. Positioning.positionWithinBounds(lazySink().getOrDie(), anchor, menu, getBounds());
  8336. },
  8337. onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) {
  8338. var sink = lazySink().getOrDie();
  8339. Positioning.position(sink, __assign({
  8340. anchor: 'submenu',
  8341. item: item
  8342. }, getSubmenuLayouts(triggeringPaths)), submenu);
  8343. },
  8344. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  8345. var sink = lazySink().getOrDie();
  8346. Positioning.positionWithinBounds(sink, anchor, primaryMenu, getBounds());
  8347. each(submenuTriggers, function (st) {
  8348. var submenuLayouts = getSubmenuLayouts(st.triggeringPath);
  8349. Positioning.position(sink, __assign({
  8350. anchor: 'submenu',
  8351. item: st.triggeringItem
  8352. }, submenuLayouts), st.triggeredMenu);
  8353. });
  8354. }
  8355. });
  8356. };
  8357. var factory = function (detail, spec) {
  8358. var isPartOfRelated = function (sandbox, queryElem) {
  8359. var related = detail.getRelated(sandbox);
  8360. return related.exists(function (rel) {
  8361. return isPartOf(rel, queryElem);
  8362. });
  8363. };
  8364. var setContent = function (sandbox, thing) {
  8365. Sandboxing.setContent(sandbox, thing);
  8366. };
  8367. var showAt = function (sandbox, anchor, thing) {
  8368. showWithin(sandbox, anchor, thing, Option.none());
  8369. };
  8370. var showWithin = function (sandbox, anchor, thing, boxElement) {
  8371. showWithinBounds(sandbox, anchor, thing, function () {
  8372. return boxElement.map(function (elem) {
  8373. return box(elem);
  8374. });
  8375. });
  8376. };
  8377. var showWithinBounds = function (sandbox, anchor, thing, getBounds) {
  8378. var sink = detail.lazySink(sandbox).getOrDie();
  8379. Sandboxing.openWhileCloaked(sandbox, thing, function () {
  8380. return Positioning.positionWithinBounds(sink, anchor, sandbox, getBounds());
  8381. });
  8382. Representing.setValue(sandbox, Option.some({
  8383. mode: 'position',
  8384. anchor: anchor,
  8385. getBounds: getBounds
  8386. }));
  8387. };
  8388. var showMenuAt = function (sandbox, anchor, menuSpec) {
  8389. showMenuWithinBounds(sandbox, anchor, menuSpec, function () {
  8390. return Option.none();
  8391. });
  8392. };
  8393. var showMenuWithinBounds = function (sandbox, anchor, menuSpec, getBounds) {
  8394. var menu = makeMenu(detail, sandbox, anchor, menuSpec, getBounds);
  8395. Sandboxing.open(sandbox, menu);
  8396. Representing.setValue(sandbox, Option.some({
  8397. mode: 'menu',
  8398. menu: menu
  8399. }));
  8400. };
  8401. var hide = function (sandbox) {
  8402. if (Sandboxing.isOpen(sandbox)) {
  8403. Representing.setValue(sandbox, Option.none());
  8404. Sandboxing.close(sandbox);
  8405. }
  8406. };
  8407. var getContent = function (sandbox) {
  8408. return Sandboxing.getState(sandbox);
  8409. };
  8410. var reposition = function (sandbox) {
  8411. if (Sandboxing.isOpen(sandbox)) {
  8412. Representing.getValue(sandbox).each(function (state) {
  8413. switch (state.mode) {
  8414. case 'menu':
  8415. Sandboxing.getState(sandbox).each(function (tmenu) {
  8416. tieredMenu.repositionMenus(tmenu);
  8417. });
  8418. break;
  8419. case 'position':
  8420. var sink = detail.lazySink(sandbox).getOrDie();
  8421. Positioning.positionWithinBounds(sink, state.anchor, sandbox, state.getBounds());
  8422. break;
  8423. }
  8424. });
  8425. }
  8426. };
  8427. var apis = {
  8428. setContent: setContent,
  8429. showAt: showAt,
  8430. showWithin: showWithin,
  8431. showWithinBounds: showWithinBounds,
  8432. showMenuAt: showMenuAt,
  8433. showMenuWithinBounds: showMenuWithinBounds,
  8434. hide: hide,
  8435. getContent: getContent,
  8436. reposition: reposition,
  8437. isOpen: Sandboxing.isOpen
  8438. };
  8439. return {
  8440. uid: detail.uid,
  8441. dom: detail.dom,
  8442. behaviours: augment(detail.inlineBehaviours, [
  8443. Sandboxing.config({
  8444. isPartOf: function (sandbox, data, queryElem) {
  8445. return isPartOf(data, queryElem) || isPartOfRelated(sandbox, queryElem);
  8446. },
  8447. getAttachPoint: function (sandbox) {
  8448. return detail.lazySink(sandbox).getOrDie();
  8449. },
  8450. onOpen: function (sandbox) {
  8451. detail.onShow(sandbox);
  8452. },
  8453. onClose: function (sandbox) {
  8454. detail.onHide(sandbox);
  8455. }
  8456. }),
  8457. Representing.config({
  8458. store: {
  8459. mode: 'memory',
  8460. initialValue: Option.none()
  8461. }
  8462. }),
  8463. Receiving.config({
  8464. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) {
  8465. return { fireEventInstead: { event: fe.event } };
  8466. }).getOr({})))), receivingChannel$1(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) {
  8467. return { fireEventInstead: { event: fe.event } };
  8468. }).getOr({})), { doReposition: reposition })))
  8469. })
  8470. ]),
  8471. eventOrder: detail.eventOrder,
  8472. apis: apis
  8473. };
  8474. };
  8475. var InlineView = single$2({
  8476. name: 'InlineView',
  8477. configFields: [
  8478. strict$1('lazySink'),
  8479. onHandler('onShow'),
  8480. onHandler('onHide'),
  8481. optionFunction('onEscape'),
  8482. field$1('inlineBehaviours', [
  8483. Sandboxing,
  8484. Representing,
  8485. Receiving
  8486. ]),
  8487. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  8488. optionObjOf('fireRepositionEventInstead', [defaulted$1('event', repositionRequested())]),
  8489. defaulted$1('getRelated', Option.none),
  8490. defaulted$1('isExtraPart', never),
  8491. defaulted$1('eventOrder', Option.none)
  8492. ],
  8493. factory: factory,
  8494. apis: {
  8495. showAt: function (apis, component, anchor, thing) {
  8496. apis.showAt(component, anchor, thing);
  8497. },
  8498. showWithin: function (apis, component, anchor, thing, boxElement) {
  8499. apis.showWithin(component, anchor, thing, boxElement);
  8500. },
  8501. showWithinBounds: function (apis, component, anchor, thing, bounds) {
  8502. apis.showWithinBounds(component, anchor, thing, bounds);
  8503. },
  8504. showMenuAt: function (apis, component, anchor, menuSpec) {
  8505. apis.showMenuAt(component, anchor, menuSpec);
  8506. },
  8507. showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) {
  8508. apis.showMenuWithinBounds(component, anchor, menuSpec, bounds);
  8509. },
  8510. hide: function (apis, component) {
  8511. apis.hide(component);
  8512. },
  8513. isOpen: function (apis, component) {
  8514. return apis.isOpen(component);
  8515. },
  8516. getContent: function (apis, component) {
  8517. return apis.getContent(component);
  8518. },
  8519. setContent: function (apis, component, thing) {
  8520. apis.setContent(component, thing);
  8521. },
  8522. reposition: function (apis, component) {
  8523. apis.reposition(component);
  8524. }
  8525. }
  8526. });
  8527. var westEdgeX$1 = function (anchor) {
  8528. return anchor.x;
  8529. };
  8530. var middleX$1 = function (anchor, element) {
  8531. return anchor.x + anchor.width / 2 - element.width / 2;
  8532. };
  8533. var eastEdgeX$1 = function (anchor, element) {
  8534. return anchor.x + anchor.width - element.width;
  8535. };
  8536. var northY$2 = function (anchor) {
  8537. return anchor.y;
  8538. };
  8539. var southY$2 = function (anchor, element) {
  8540. return anchor.y + anchor.height - element.height;
  8541. };
  8542. var southeast$3 = function (anchor, element, bubbles) {
  8543. return nu$7(eastEdgeX$1(anchor, element), southY$2(anchor, element), bubbles.innerSoutheast(), northwest(), boundsRestriction(anchor, {
  8544. right: 0,
  8545. bottom: 3
  8546. }), 'layout-inner-se');
  8547. };
  8548. var southwest$3 = function (anchor, element, bubbles) {
  8549. return nu$7(westEdgeX$1(anchor), southY$2(anchor, element), bubbles.innerSouthwest(), northeast(), boundsRestriction(anchor, {
  8550. left: 1,
  8551. bottom: 3
  8552. }), 'layout-inner-sw');
  8553. };
  8554. var northeast$3 = function (anchor, element, bubbles) {
  8555. return nu$7(eastEdgeX$1(anchor, element), northY$2(anchor), bubbles.innerNortheast(), southwest(), boundsRestriction(anchor, {
  8556. right: 0,
  8557. top: 2
  8558. }), 'layout-inner-ne');
  8559. };
  8560. var northwest$3 = function (anchor, element, bubbles) {
  8561. return nu$7(westEdgeX$1(anchor), northY$2(anchor), bubbles.innerNorthwest(), southeast(), boundsRestriction(anchor, {
  8562. left: 1,
  8563. top: 2
  8564. }), 'layout-inner-nw');
  8565. };
  8566. var north$3 = function (anchor, element, bubbles) {
  8567. return nu$7(middleX$1(anchor, element), northY$2(anchor), bubbles.innerNorth(), south(), boundsRestriction(anchor, { top: 2 }), 'layout-inner-n');
  8568. };
  8569. var south$3 = function (anchor, element, bubbles) {
  8570. return nu$7(middleX$1(anchor, element), southY$2(anchor, element), bubbles.innerSouth(), north(), boundsRestriction(anchor, { bottom: 3 }), 'layout-inner-s');
  8571. };
  8572. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  8573. var factory$1 = function (detail) {
  8574. var events = events$7(detail.action);
  8575. var tag = detail.dom.tag;
  8576. var lookupAttr = function (attr) {
  8577. return get(detail.dom, 'attributes').bind(function (attrs) {
  8578. return get(attrs, attr);
  8579. });
  8580. };
  8581. var getModAttributes = function () {
  8582. if (tag === 'button') {
  8583. var type = lookupAttr('type').getOr('button');
  8584. var roleAttrs = lookupAttr('role').map(function (role) {
  8585. return { role: role };
  8586. }).getOr({});
  8587. return __assign({ type: type }, roleAttrs);
  8588. } else {
  8589. var role = lookupAttr('role').getOr('button');
  8590. return { role: role };
  8591. }
  8592. };
  8593. return {
  8594. uid: detail.uid,
  8595. dom: detail.dom,
  8596. components: detail.components,
  8597. events: events,
  8598. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  8599. Focusing.config({}),
  8600. Keying.config({
  8601. mode: 'execution',
  8602. useSpace: true,
  8603. useEnter: true
  8604. })
  8605. ]),
  8606. domModification: { attributes: getModAttributes() },
  8607. eventOrder: detail.eventOrder
  8608. };
  8609. };
  8610. var Button = single$2({
  8611. name: 'Button',
  8612. factory: factory$1,
  8613. configFields: [
  8614. defaulted$1('uid', undefined),
  8615. strict$1('dom'),
  8616. defaulted$1('components', []),
  8617. SketchBehaviours.field('buttonBehaviours', [
  8618. Focusing,
  8619. Keying
  8620. ]),
  8621. option('action'),
  8622. option('role'),
  8623. defaulted$1('eventOrder', {})
  8624. ]
  8625. });
  8626. var record = function (spec) {
  8627. var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  8628. var get = function (anyInSystem) {
  8629. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  8630. };
  8631. var getOpt = function (anyInSystem) {
  8632. return anyInSystem.getSystem().getByUid(uid).toOption();
  8633. };
  8634. var asSpec = function () {
  8635. return __assign(__assign({}, spec), { uid: uid });
  8636. };
  8637. return {
  8638. get: get,
  8639. getOpt: getOpt,
  8640. asSpec: asSpec
  8641. };
  8642. };
  8643. var defaultIcon = function (icons) {
  8644. return Option.from(icons()['temporary-placeholder']).getOr('!not found!');
  8645. };
  8646. var get$d = function (name, icons) {
  8647. return Option.from(icons()[name]).getOrThunk(function () {
  8648. return defaultIcon(icons);
  8649. });
  8650. };
  8651. var getOr = function (name, icons, fallback) {
  8652. return Option.from(icons()[name]).or(fallback).getOrThunk(function () {
  8653. return defaultIcon(icons);
  8654. });
  8655. };
  8656. var getFirst$1 = function (names, icons) {
  8657. return findMap(names, function (name) {
  8658. return Option.from(icons()[name]);
  8659. }).getOrThunk(function () {
  8660. return defaultIcon(icons);
  8661. });
  8662. };
  8663. var notificationIconMap = {
  8664. success: 'checkmark',
  8665. error: 'warning',
  8666. err: 'error',
  8667. warning: 'warning',
  8668. warn: 'warning',
  8669. info: 'info'
  8670. };
  8671. var factory$2 = function (detail) {
  8672. var memBannerText = record({
  8673. dom: {
  8674. tag: 'p',
  8675. innerHtml: detail.translationProvider(detail.text)
  8676. },
  8677. behaviours: derive$1([Replacing.config({})])
  8678. });
  8679. var renderPercentBar = function (percent) {
  8680. return {
  8681. dom: {
  8682. tag: 'div',
  8683. classes: ['tox-bar'],
  8684. attributes: { style: 'width: ' + percent + '%' }
  8685. }
  8686. };
  8687. };
  8688. var renderPercentText = function (percent) {
  8689. return {
  8690. dom: {
  8691. tag: 'div',
  8692. classes: ['tox-text'],
  8693. innerHtml: percent + '%'
  8694. }
  8695. };
  8696. };
  8697. var memBannerProgress = record({
  8698. dom: {
  8699. tag: 'div',
  8700. classes: detail.progress ? [
  8701. 'tox-progress-bar',
  8702. 'tox-progress-indicator'
  8703. ] : ['tox-progress-bar']
  8704. },
  8705. components: [
  8706. {
  8707. dom: {
  8708. tag: 'div',
  8709. classes: ['tox-bar-container']
  8710. },
  8711. components: [renderPercentBar(0)]
  8712. },
  8713. renderPercentText(0)
  8714. ],
  8715. behaviours: derive$1([Replacing.config({})])
  8716. });
  8717. var updateProgress = function (comp, percent) {
  8718. if (comp.getSystem().isConnected()) {
  8719. memBannerProgress.getOpt(comp).each(function (progress) {
  8720. Replacing.set(progress, [
  8721. {
  8722. dom: {
  8723. tag: 'div',
  8724. classes: ['tox-bar-container']
  8725. },
  8726. components: [renderPercentBar(percent)]
  8727. },
  8728. renderPercentText(percent)
  8729. ]);
  8730. });
  8731. }
  8732. };
  8733. var updateText = function (comp, text$1) {
  8734. if (comp.getSystem().isConnected()) {
  8735. var banner = memBannerText.get(comp);
  8736. Replacing.set(banner, [text(text$1)]);
  8737. }
  8738. };
  8739. var apis = {
  8740. updateProgress: updateProgress,
  8741. updateText: updateText
  8742. };
  8743. var iconChoices = flatten([
  8744. detail.icon.toArray(),
  8745. detail.level.toArray(),
  8746. detail.level.bind(function (level) {
  8747. return Option.from(notificationIconMap[level]);
  8748. }).toArray()
  8749. ]);
  8750. return {
  8751. uid: detail.uid,
  8752. dom: {
  8753. tag: 'div',
  8754. attributes: { role: 'alert' },
  8755. classes: detail.level.map(function (level) {
  8756. return [
  8757. 'tox-notification',
  8758. 'tox-notification--in',
  8759. 'tox-notification--' + level
  8760. ];
  8761. }).getOr([
  8762. 'tox-notification',
  8763. 'tox-notification--in'
  8764. ])
  8765. },
  8766. components: [
  8767. {
  8768. dom: {
  8769. tag: 'div',
  8770. classes: ['tox-notification__icon'],
  8771. innerHtml: getFirst$1(iconChoices, detail.iconProvider)
  8772. }
  8773. },
  8774. {
  8775. dom: {
  8776. tag: 'div',
  8777. classes: ['tox-notification__body']
  8778. },
  8779. components: [memBannerText.asSpec()],
  8780. behaviours: derive$1([Replacing.config({})])
  8781. }
  8782. ].concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [Button.sketch({
  8783. dom: {
  8784. tag: 'button',
  8785. classes: [
  8786. 'tox-notification__dismiss',
  8787. 'tox-button',
  8788. 'tox-button--naked',
  8789. 'tox-button--icon'
  8790. ]
  8791. },
  8792. components: [{
  8793. dom: {
  8794. tag: 'div',
  8795. classes: ['tox-icon'],
  8796. innerHtml: get$d('close', detail.iconProvider),
  8797. attributes: { 'aria-label': detail.translationProvider('Close') }
  8798. }
  8799. }],
  8800. action: function (comp) {
  8801. detail.onAction(comp);
  8802. }
  8803. })]),
  8804. apis: apis
  8805. };
  8806. };
  8807. var Notification = single$2({
  8808. name: 'Notification',
  8809. factory: factory$2,
  8810. configFields: [
  8811. option('level'),
  8812. strict$1('progress'),
  8813. strict$1('icon'),
  8814. strict$1('onAction'),
  8815. strict$1('text'),
  8816. strict$1('iconProvider'),
  8817. strict$1('translationProvider'),
  8818. defaultedBoolean('closeButton', true)
  8819. ],
  8820. apis: {
  8821. updateProgress: function (apis, comp, percent) {
  8822. apis.updateProgress(comp, percent);
  8823. },
  8824. updateText: function (apis, comp, text) {
  8825. apis.updateText(comp, text);
  8826. }
  8827. }
  8828. });
  8829. function NotificationManagerImpl (editor, extras, uiMothership) {
  8830. var backstage = extras.backstage;
  8831. var getLayoutDirection = function (rel) {
  8832. switch (rel) {
  8833. case 'bc-bc':
  8834. return south$3;
  8835. case 'tc-tc':
  8836. return north$3;
  8837. case 'tc-bc':
  8838. return north$1;
  8839. case 'bc-tc':
  8840. default:
  8841. return south$1;
  8842. }
  8843. };
  8844. var prePositionNotifications = function (notifications) {
  8845. each(notifications, function (notification) {
  8846. return notification.moveTo(0, 0);
  8847. });
  8848. };
  8849. var positionNotifications = function (notifications) {
  8850. if (notifications.length > 0) {
  8851. head(notifications).each(function (firstItem) {
  8852. return firstItem.moveRel(null, 'banner');
  8853. });
  8854. each(notifications, function (notification, index) {
  8855. if (index > 0) {
  8856. notification.moveRel(notifications[index - 1].getEl(), 'bc-tc');
  8857. }
  8858. });
  8859. }
  8860. };
  8861. var reposition = function (notifications) {
  8862. prePositionNotifications(notifications);
  8863. positionNotifications(notifications);
  8864. };
  8865. var open = function (settings, closeCallback) {
  8866. var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0);
  8867. var close = function () {
  8868. closeCallback();
  8869. InlineView.hide(notificationWrapper);
  8870. };
  8871. var notification = build$1(Notification.sketch({
  8872. text: settings.text,
  8873. level: contains([
  8874. 'success',
  8875. 'error',
  8876. 'warning',
  8877. 'warn',
  8878. 'info'
  8879. ], settings.type) ? settings.type : undefined,
  8880. progress: settings.progressBar === true,
  8881. icon: Option.from(settings.icon),
  8882. closeButton: !hideCloseButton,
  8883. onAction: close,
  8884. iconProvider: backstage.shared.providers.icons,
  8885. translationProvider: backstage.shared.providers.translate
  8886. }));
  8887. var notificationWrapper = build$1(InlineView.sketch(__assign({
  8888. dom: {
  8889. tag: 'div',
  8890. classes: ['tox-notifications-container']
  8891. },
  8892. lazySink: extras.backstage.shared.getSink,
  8893. fireDismissalEventInstead: {}
  8894. }, backstage.shared.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} })));
  8895. uiMothership.add(notificationWrapper);
  8896. if (settings.timeout > 0) {
  8897. global$2.setTimeout(function () {
  8898. close();
  8899. }, settings.timeout);
  8900. }
  8901. return {
  8902. close: close,
  8903. moveTo: function (x, y) {
  8904. InlineView.showAt(notificationWrapper, {
  8905. anchor: 'makeshift',
  8906. x: x,
  8907. y: y
  8908. }, premade$1(notification));
  8909. },
  8910. moveRel: function (element, rel) {
  8911. if (rel !== 'banner') {
  8912. var layoutDirection_1 = getLayoutDirection(rel);
  8913. var nodeAnchor = {
  8914. anchor: 'node',
  8915. root: body(),
  8916. node: Option.some(Element.fromDom(element)),
  8917. layouts: {
  8918. onRtl: function () {
  8919. return [layoutDirection_1];
  8920. },
  8921. onLtr: function () {
  8922. return [layoutDirection_1];
  8923. }
  8924. }
  8925. };
  8926. InlineView.showAt(notificationWrapper, nodeAnchor, premade$1(notification));
  8927. } else {
  8928. InlineView.showAt(notificationWrapper, extras.backstage.shared.anchors.banner(), premade$1(notification));
  8929. }
  8930. },
  8931. text: function (nuText) {
  8932. Notification.updateText(notification, nuText);
  8933. },
  8934. settings: settings,
  8935. getEl: function () {
  8936. return notification.element().dom();
  8937. },
  8938. progressBar: {
  8939. value: function (percent) {
  8940. Notification.updateProgress(notification, percent);
  8941. }
  8942. }
  8943. };
  8944. };
  8945. var close = function (notification) {
  8946. notification.close();
  8947. };
  8948. var getArgs = function (notification) {
  8949. return notification.settings;
  8950. };
  8951. return {
  8952. open: open,
  8953. close: close,
  8954. reposition: reposition,
  8955. getArgs: getArgs
  8956. };
  8957. }
  8958. var first = function (fn, rate) {
  8959. var timer = null;
  8960. var cancel = function () {
  8961. if (timer !== null) {
  8962. domGlobals.clearTimeout(timer);
  8963. timer = null;
  8964. }
  8965. };
  8966. var throttle = function () {
  8967. var args = [];
  8968. for (var _i = 0; _i < arguments.length; _i++) {
  8969. args[_i] = arguments[_i];
  8970. }
  8971. if (timer === null) {
  8972. timer = domGlobals.setTimeout(function () {
  8973. fn.apply(null, args);
  8974. timer = null;
  8975. }, rate);
  8976. }
  8977. };
  8978. return {
  8979. cancel: cancel,
  8980. throttle: throttle
  8981. };
  8982. };
  8983. var last$2 = function (fn, rate) {
  8984. var timer = null;
  8985. var cancel = function () {
  8986. if (timer !== null) {
  8987. domGlobals.clearTimeout(timer);
  8988. timer = null;
  8989. }
  8990. };
  8991. var throttle = function () {
  8992. var args = [];
  8993. for (var _i = 0; _i < arguments.length; _i++) {
  8994. args[_i] = arguments[_i];
  8995. }
  8996. if (timer !== null) {
  8997. domGlobals.clearTimeout(timer);
  8998. }
  8999. timer = domGlobals.setTimeout(function () {
  9000. fn.apply(null, args);
  9001. timer = null;
  9002. }, rate);
  9003. };
  9004. return {
  9005. cancel: cancel,
  9006. throttle: throttle
  9007. };
  9008. };
  9009. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker');
  9010. var isBoundary = function (dom, node) {
  9011. return dom.isBlock(node) || contains([
  9012. 'BR',
  9013. 'IMG',
  9014. 'HR',
  9015. 'INPUT'
  9016. ], node.nodeName) || dom.getContentEditable(node) === 'false';
  9017. };
  9018. var repeatLeft = function (dom, node, offset, process, rootNode) {
  9019. var search = global$3(dom, function (node) {
  9020. return isBoundary(dom, node);
  9021. });
  9022. return Option.from(search.backwards(node, offset, process, rootNode));
  9023. };
  9024. var autocompleteSelector = '[data-mce-autocompleter]';
  9025. var create$4 = function (editor, range) {
  9026. return detect$4(Element.fromDom(editor.selection.getNode())).getOrThunk(function () {
  9027. var wrapper = Element.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc());
  9028. append(wrapper, Element.fromDom(range.extractContents()));
  9029. range.insertNode(wrapper.dom());
  9030. parent(wrapper).each(function (elm) {
  9031. return elm.dom().normalize();
  9032. });
  9033. last$1(wrapper).map(function (last) {
  9034. editor.selection.setCursorLocation(last.dom(), getEnd(last));
  9035. });
  9036. return wrapper;
  9037. });
  9038. };
  9039. var detect$4 = function (elm) {
  9040. return closest$3(elm, autocompleteSelector);
  9041. };
  9042. var isValidTextRange = function (rng) {
  9043. return rng.collapsed && rng.startContainer.nodeType === 3;
  9044. };
  9045. var getText = function (rng) {
  9046. return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, '');
  9047. };
  9048. var isWhitespace = function (chr) {
  9049. return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1;
  9050. };
  9051. var stripTriggerChar = function (text, triggerCh) {
  9052. return text.substring(triggerCh.length);
  9053. };
  9054. var findChar = function (text, index, ch) {
  9055. var i;
  9056. for (i = index - 1; i >= 0; i--) {
  9057. var char = text.charAt(i);
  9058. if (isWhitespace(char)) {
  9059. return Option.none();
  9060. }
  9061. if (char === ch) {
  9062. break;
  9063. }
  9064. }
  9065. return Option.some(i);
  9066. };
  9067. var findStart = function (dom, initRange, ch, minChars) {
  9068. if (minChars === void 0) {
  9069. minChars = 0;
  9070. }
  9071. if (!isValidTextRange(initRange)) {
  9072. return Option.none();
  9073. }
  9074. var findTriggerChIndex = function (element, offset, text) {
  9075. return findChar(text, offset, ch).getOr(offset);
  9076. };
  9077. var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot();
  9078. return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) {
  9079. var range = initRange.cloneRange();
  9080. range.setStart(spot.container, spot.offset);
  9081. range.setEnd(initRange.endContainer, initRange.endOffset);
  9082. if (range.collapsed) {
  9083. return Option.none();
  9084. }
  9085. var text = getText(range);
  9086. var triggerCharIndex = text.lastIndexOf(ch);
  9087. if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) {
  9088. return Option.none();
  9089. } else {
  9090. return Option.some({
  9091. text: stripTriggerChar(text, ch),
  9092. range: range,
  9093. triggerChar: ch
  9094. });
  9095. }
  9096. });
  9097. };
  9098. var getContext = function (dom, initRange, ch, minChars) {
  9099. if (minChars === void 0) {
  9100. minChars = 0;
  9101. }
  9102. return detect$4(Element.fromDom(initRange.startContainer)).fold(function () {
  9103. return findStart(dom, initRange, ch, minChars);
  9104. }, function (elm) {
  9105. var range = dom.createRng();
  9106. range.selectNode(elm.dom());
  9107. var text = getText(range);
  9108. return Option.some({
  9109. range: range,
  9110. text: stripTriggerChar(text, ch),
  9111. triggerChar: ch
  9112. });
  9113. });
  9114. };
  9115. var setup = function (api, editor) {
  9116. editor.on('keypress compositionend', api.onKeypress.throttle);
  9117. editor.on('remove', api.onKeypress.cancel);
  9118. var redirectKeyToItem = function (item, e) {
  9119. emitWith(item, keydown(), { raw: e });
  9120. };
  9121. editor.on('keydown', function (e) {
  9122. var getItem = function () {
  9123. return api.getView().bind(Highlighting.getHighlighted);
  9124. };
  9125. if (e.which === 8) {
  9126. api.onKeypress.throttle(e);
  9127. }
  9128. if (api.isActive()) {
  9129. if (e.which === 27) {
  9130. api.cancelIfNecessary();
  9131. }
  9132. if (api.isMenuOpen()) {
  9133. if (e.which === 13) {
  9134. getItem().each(emitExecute);
  9135. e.preventDefault();
  9136. } else if (e.which === 40) {
  9137. getItem().fold(function () {
  9138. api.getView().each(Highlighting.highlightFirst);
  9139. }, function (item) {
  9140. redirectKeyToItem(item, e);
  9141. });
  9142. e.preventDefault();
  9143. e.stopImmediatePropagation();
  9144. } else if (e.which === 37 || e.which === 38 || e.which === 39) {
  9145. getItem().each(function (item) {
  9146. redirectKeyToItem(item, e);
  9147. e.preventDefault();
  9148. e.stopImmediatePropagation();
  9149. });
  9150. }
  9151. } else {
  9152. if (e.which === 13 || e.which === 38 || e.which === 40) {
  9153. api.cancelIfNecessary();
  9154. }
  9155. }
  9156. }
  9157. });
  9158. editor.on('NodeChange', function (e) {
  9159. if (api.isActive() && !api.isProcessingAction() && detect$4(Element.fromDom(e.element)).isNone()) {
  9160. api.cancelIfNecessary();
  9161. }
  9162. });
  9163. };
  9164. var AutocompleterEditorEvents = { setup: setup };
  9165. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Promise');
  9166. var point$2 = function (container, offset) {
  9167. return {
  9168. container: container,
  9169. offset: offset
  9170. };
  9171. };
  9172. var isText$1 = function (node) {
  9173. return node.nodeType === domGlobals.Node.TEXT_NODE;
  9174. };
  9175. var isElement$1 = function (node) {
  9176. return node.nodeType === domGlobals.Node.ELEMENT_NODE;
  9177. };
  9178. var toLast = function (node) {
  9179. if (isText$1(node)) {
  9180. return point$2(node, node.data.length);
  9181. } else {
  9182. var children = node.childNodes;
  9183. return children.length > 0 ? toLast(children[children.length - 1]) : point$2(node, children.length);
  9184. }
  9185. };
  9186. var toLeaf = function (node, offset) {
  9187. var children = node.childNodes;
  9188. if (children.length > 0 && offset < children.length) {
  9189. return toLeaf(children[offset], 0);
  9190. } else if (children.length > 0 && isElement$1(node) && children.length === offset) {
  9191. return toLast(children[children.length - 1]);
  9192. } else {
  9193. return point$2(node, offset);
  9194. }
  9195. };
  9196. var isPreviousCharContent = function (dom, leaf) {
  9197. return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) {
  9198. return offset === 0 ? -1 : offset;
  9199. }, dom.getRoot()).filter(function (spot) {
  9200. var char = spot.container.data.charAt(spot.offset - 1);
  9201. return !isWhitespace(char);
  9202. }).isSome();
  9203. };
  9204. var isStartOfWord = function (dom) {
  9205. return function (rng) {
  9206. var leaf = toLeaf(rng.startContainer, rng.startOffset);
  9207. return !isPreviousCharContent(dom, leaf);
  9208. };
  9209. };
  9210. var getTriggerContext = function (dom, initRange, database) {
  9211. return findMap(database.triggerChars, function (ch) {
  9212. return getContext(dom, initRange, ch);
  9213. });
  9214. };
  9215. var lookup = function (editor, getDatabase) {
  9216. var database = getDatabase();
  9217. var rng = editor.selection.getRng();
  9218. return getTriggerContext(editor.dom, rng, database).bind(function (context) {
  9219. return lookupWithContext(editor, getDatabase, context);
  9220. });
  9221. };
  9222. var lookupWithContext = function (editor, getDatabase, context, fetchOptions) {
  9223. if (fetchOptions === void 0) {
  9224. fetchOptions = {};
  9225. }
  9226. var database = getDatabase();
  9227. var rng = editor.selection.getRng();
  9228. var startText = rng.startContainer.nodeValue;
  9229. var autocompleters = filter(database.lookupByChar(context.triggerChar), function (autocompleter) {
  9230. return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () {
  9231. return isStartOfWord(editor.dom);
  9232. })(context.range, startText, context.text);
  9233. });
  9234. if (autocompleters.length === 0) {
  9235. return Option.none();
  9236. }
  9237. var lookupData = global$4.all(map(autocompleters, function (ac) {
  9238. var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions);
  9239. return fetchResult.then(function (results) {
  9240. return {
  9241. matchText: context.text,
  9242. items: results,
  9243. columns: ac.columns,
  9244. onAction: ac.onAction
  9245. };
  9246. });
  9247. }));
  9248. return Option.some({
  9249. lookupData: lookupData,
  9250. context: context
  9251. });
  9252. };
  9253. var separatorMenuItemSchema = objOf([
  9254. strictString('type'),
  9255. optionString('text')
  9256. ]);
  9257. var createSeparatorMenuItem = function (spec) {
  9258. return asRaw('separatormenuitem', separatorMenuItemSchema, spec);
  9259. };
  9260. var autocompleterItemSchema = objOf([
  9261. state$1('type', function () {
  9262. return 'autocompleteitem';
  9263. }),
  9264. state$1('active', function () {
  9265. return false;
  9266. }),
  9267. state$1('disabled', function () {
  9268. return false;
  9269. }),
  9270. defaulted$1('meta', {}),
  9271. strictString('value'),
  9272. optionString('text'),
  9273. optionString('icon')
  9274. ]);
  9275. var autocompleterSchema = objOf([
  9276. strictString('type'),
  9277. strictString('ch'),
  9278. defaultedNumber('minChars', 1),
  9279. defaulted$1('columns', 1),
  9280. defaultedNumber('maxResults', 10),
  9281. optionFunction('matches'),
  9282. strictFunction('fetch'),
  9283. strictFunction('onAction')
  9284. ]);
  9285. var createSeparatorItem = function (spec) {
  9286. return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec);
  9287. };
  9288. var createAutocompleterItem = function (spec) {
  9289. return asRaw('Autocompleter.Item', autocompleterItemSchema, spec);
  9290. };
  9291. var createAutocompleter = function (spec) {
  9292. return asRaw('Autocompleter', autocompleterSchema, spec);
  9293. };
  9294. var stringArray = function (a) {
  9295. var all = {};
  9296. each(a, function (key) {
  9297. all[key] = {};
  9298. });
  9299. return keys(all);
  9300. };
  9301. var register = function (editor) {
  9302. var popups = editor.ui.registry.getAll().popups;
  9303. var dataset = map$1(popups, function (popup) {
  9304. return createAutocompleter(popup).fold(function (err) {
  9305. throw new Error(formatError(err));
  9306. }, function (x) {
  9307. return x;
  9308. });
  9309. });
  9310. var triggerChars = stringArray(mapToArray(dataset, function (v) {
  9311. return v.ch;
  9312. }));
  9313. var datasetValues = values(dataset);
  9314. var lookupByChar = function (ch) {
  9315. return filter(datasetValues, function (dv) {
  9316. return dv.ch === ch;
  9317. });
  9318. };
  9319. return {
  9320. dataset: dataset,
  9321. triggerChars: triggerChars,
  9322. lookupByChar: lookupByChar
  9323. };
  9324. };
  9325. var commonMenuItemFields = [
  9326. defaultedBoolean('disabled', false),
  9327. optionString('text'),
  9328. optionString('shortcut'),
  9329. field('value', 'value', defaultedThunk(function () {
  9330. return generate$1('menuitem-value');
  9331. }), anyValue$1()),
  9332. defaulted$1('meta', {})
  9333. ];
  9334. var menuItemSchema = objOf([
  9335. strictString('type'),
  9336. defaultedFunction('onSetup', function () {
  9337. return noop;
  9338. }),
  9339. defaultedFunction('onAction', noop),
  9340. optionString('icon')
  9341. ].concat(commonMenuItemFields));
  9342. var createMenuItem = function (spec) {
  9343. return asRaw('menuitem', menuItemSchema, spec);
  9344. };
  9345. var nestedMenuItemSchema = objOf([
  9346. strictString('type'),
  9347. strictFunction('getSubmenuItems'),
  9348. defaultedFunction('onSetup', function () {
  9349. return noop;
  9350. }),
  9351. optionString('icon')
  9352. ].concat(commonMenuItemFields));
  9353. var createNestedMenuItem = function (spec) {
  9354. return asRaw('nestedmenuitem', nestedMenuItemSchema, spec);
  9355. };
  9356. var toggleMenuItemSchema = objOf([
  9357. strictString('type'),
  9358. optionString('icon'),
  9359. defaultedBoolean('active', false),
  9360. defaultedFunction('onSetup', function () {
  9361. return noop;
  9362. }),
  9363. strictFunction('onAction')
  9364. ].concat(commonMenuItemFields));
  9365. var createToggleMenuItem = function (spec) {
  9366. return asRaw('togglemenuitem', toggleMenuItemSchema, spec);
  9367. };
  9368. var choiceMenuItemSchema = objOf([
  9369. strictString('type'),
  9370. defaultedBoolean('active', false),
  9371. optionString('icon')
  9372. ].concat(commonMenuItemFields));
  9373. var createChoiceMenuItem = function (spec) {
  9374. return asRaw('choicemenuitem', choiceMenuItemSchema, spec);
  9375. };
  9376. var fancyTypes = [
  9377. 'inserttable',
  9378. 'colorswatch'
  9379. ];
  9380. var fancyMenuItemSchema = objOf([
  9381. strictString('type'),
  9382. strictStringEnum('fancytype', fancyTypes),
  9383. defaultedFunction('onAction', noop)
  9384. ]);
  9385. var createFancyMenuItem = function (spec) {
  9386. return asRaw('fancymenuitem', fancyMenuItemSchema, spec);
  9387. };
  9388. var detectSize = function (comp, margin, selectorClass) {
  9389. var descendants$1 = descendants(comp.element(), '.' + selectorClass);
  9390. if (descendants$1.length > 0) {
  9391. var columnLength = findIndex(descendants$1, function (c) {
  9392. var thisTop = c.dom().getBoundingClientRect().top;
  9393. var cTop = descendants$1[0].dom().getBoundingClientRect().top;
  9394. return Math.abs(thisTop - cTop) > margin;
  9395. }).getOr(descendants$1.length);
  9396. return Option.some({
  9397. numColumns: columnLength,
  9398. numRows: Math.ceil(descendants$1.length / columnLength)
  9399. });
  9400. } else {
  9401. return Option.none();
  9402. }
  9403. };
  9404. var namedEvents = function (name, handlers) {
  9405. return derive$1([config(name, handlers)]);
  9406. };
  9407. var unnamedEvents = function (handlers) {
  9408. return namedEvents(generate$1('unnamed-events'), handlers);
  9409. };
  9410. var SimpleBehaviours = {
  9411. namedEvents: namedEvents,
  9412. unnamedEvents: unnamedEvents
  9413. };
  9414. var TooltippingSchema = [
  9415. strict$1('lazySink'),
  9416. strict$1('tooltipDom'),
  9417. defaulted$1('exclusive', true),
  9418. defaulted$1('tooltipComponents', []),
  9419. defaulted$1('delay', 300),
  9420. defaultedStringEnum('mode', 'normal', [
  9421. 'normal',
  9422. 'follow-highlight'
  9423. ]),
  9424. defaulted$1('anchor', function (comp) {
  9425. return {
  9426. anchor: 'hotspot',
  9427. hotspot: comp,
  9428. layouts: {
  9429. onLtr: constant([
  9430. south$1,
  9431. north$1,
  9432. southeast$1,
  9433. northeast$1,
  9434. southwest$1,
  9435. northwest$1
  9436. ]),
  9437. onRtl: constant([
  9438. south$1,
  9439. north$1,
  9440. southeast$1,
  9441. northeast$1,
  9442. southwest$1,
  9443. northwest$1
  9444. ])
  9445. }
  9446. };
  9447. }),
  9448. onHandler('onHide'),
  9449. onHandler('onShow')
  9450. ];
  9451. var init$4 = function () {
  9452. var timer = Cell(Option.none());
  9453. var popup = Cell(Option.none());
  9454. var getTooltip = function () {
  9455. return popup.get();
  9456. };
  9457. var setTooltip = function (comp) {
  9458. popup.set(Option.some(comp));
  9459. };
  9460. var clearTooltip = function () {
  9461. popup.set(Option.none());
  9462. };
  9463. var clearTimer = function () {
  9464. timer.get().each(function (t) {
  9465. domGlobals.clearTimeout(t);
  9466. });
  9467. };
  9468. var resetTimer = function (f, delay) {
  9469. clearTimer();
  9470. timer.set(Option.some(domGlobals.setTimeout(function () {
  9471. f();
  9472. }, delay)));
  9473. };
  9474. var isShowing = function () {
  9475. return popup.get().isSome();
  9476. };
  9477. var readState = constant('not-implemented');
  9478. return nu$5({
  9479. getTooltip: getTooltip,
  9480. isShowing: isShowing,
  9481. setTooltip: setTooltip,
  9482. clearTooltip: clearTooltip,
  9483. clearTimer: clearTimer,
  9484. resetTimer: resetTimer,
  9485. readState: readState
  9486. });
  9487. };
  9488. var TooltippingState = /*#__PURE__*/Object.freeze({
  9489. __proto__: null,
  9490. init: init$4
  9491. });
  9492. var ExclusivityChannel = generate$1('tooltip.exclusive');
  9493. var ShowTooltipEvent = generate$1('tooltip.show');
  9494. var HideTooltipEvent = generate$1('tooltip.hide');
  9495. var hideAllExclusive = function (component, _tConfig, _tState) {
  9496. component.getSystem().broadcastOn([ExclusivityChannel], {});
  9497. };
  9498. var setComponents = function (component, tConfig, tState, specs) {
  9499. tState.getTooltip().each(function (tooltip) {
  9500. if (tooltip.getSystem().isConnected()) {
  9501. Replacing.set(tooltip, specs);
  9502. }
  9503. });
  9504. };
  9505. var TooltippingApis = /*#__PURE__*/Object.freeze({
  9506. __proto__: null,
  9507. hideAllExclusive: hideAllExclusive,
  9508. setComponents: setComponents
  9509. });
  9510. var events$8 = function (tooltipConfig, state) {
  9511. var hide = function (comp) {
  9512. state.getTooltip().each(function (p) {
  9513. detach(p);
  9514. tooltipConfig.onHide(comp, p);
  9515. state.clearTooltip();
  9516. });
  9517. state.clearTimer();
  9518. };
  9519. var show = function (comp) {
  9520. if (!state.isShowing()) {
  9521. hideAllExclusive(comp);
  9522. var sink = tooltipConfig.lazySink(comp).getOrDie();
  9523. var popup = comp.getSystem().build({
  9524. dom: tooltipConfig.tooltipDom,
  9525. components: tooltipConfig.tooltipComponents,
  9526. events: derive(tooltipConfig.mode === 'normal' ? [
  9527. run(mouseover(), function (_) {
  9528. emit(comp, ShowTooltipEvent);
  9529. }),
  9530. run(mouseout(), function (_) {
  9531. emit(comp, HideTooltipEvent);
  9532. })
  9533. ] : []),
  9534. behaviours: derive$1([Replacing.config({})])
  9535. });
  9536. state.setTooltip(popup);
  9537. attach$1(sink, popup);
  9538. tooltipConfig.onShow(comp, popup);
  9539. Positioning.position(sink, tooltipConfig.anchor(comp), popup);
  9540. }
  9541. };
  9542. return derive(flatten([
  9543. [
  9544. run(ShowTooltipEvent, function (comp) {
  9545. state.resetTimer(function () {
  9546. show(comp);
  9547. }, tooltipConfig.delay);
  9548. }),
  9549. run(HideTooltipEvent, function (comp) {
  9550. state.resetTimer(function () {
  9551. hide(comp);
  9552. }, tooltipConfig.delay);
  9553. }),
  9554. run(receive(), function (comp, message) {
  9555. var receivingData = message;
  9556. if (contains(receivingData.channels(), ExclusivityChannel)) {
  9557. hide(comp);
  9558. }
  9559. }),
  9560. runOnDetached(function (comp) {
  9561. hide(comp);
  9562. })
  9563. ],
  9564. tooltipConfig.mode === 'normal' ? [
  9565. run(focusin(), function (comp) {
  9566. emit(comp, ShowTooltipEvent);
  9567. }),
  9568. run(postBlur(), function (comp) {
  9569. emit(comp, HideTooltipEvent);
  9570. }),
  9571. run(mouseover(), function (comp) {
  9572. emit(comp, ShowTooltipEvent);
  9573. }),
  9574. run(mouseout(), function (comp) {
  9575. emit(comp, HideTooltipEvent);
  9576. })
  9577. ] : [
  9578. run(highlight(), function (comp, _se) {
  9579. emit(comp, ShowTooltipEvent);
  9580. }),
  9581. run(dehighlight(), function (comp) {
  9582. emit(comp, HideTooltipEvent);
  9583. })
  9584. ]
  9585. ]));
  9586. };
  9587. var ActiveTooltipping = /*#__PURE__*/Object.freeze({
  9588. __proto__: null,
  9589. events: events$8
  9590. });
  9591. var Tooltipping = create$1({
  9592. fields: TooltippingSchema,
  9593. name: 'tooltipping',
  9594. active: ActiveTooltipping,
  9595. state: TooltippingState,
  9596. apis: TooltippingApis
  9597. });
  9598. var global$5 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  9599. var navClass = 'tox-menu-nav__js';
  9600. var selectableClass = 'tox-collection__item';
  9601. var colorClass = 'tox-swatch';
  9602. var presetClasses = {
  9603. normal: navClass,
  9604. color: colorClass
  9605. };
  9606. var tickedClass = 'tox-collection__item--enabled';
  9607. var groupHeadingClass = 'tox-collection__group-heading';
  9608. var iconClass = 'tox-collection__item-icon';
  9609. var textClass = 'tox-collection__item-label';
  9610. var accessoryClass = 'tox-collection__item-accessory';
  9611. var caretClass = 'tox-collection__item-caret';
  9612. var checkmarkClass = 'tox-collection__item-checkmark';
  9613. var activeClass = 'tox-collection__item--active';
  9614. var iconClassRtl = 'tox-collection__item-icon-rtl';
  9615. var classForPreset = function (presets) {
  9616. return get(presetClasses, presets).getOr(navClass);
  9617. };
  9618. var global$6 = tinymce.util.Tools.resolve('tinymce.Env');
  9619. var convertText = function (source) {
  9620. var mac = {
  9621. alt: '&#x2325;',
  9622. ctrl: '&#x2303;',
  9623. shift: '&#x21E7;',
  9624. meta: '&#x2318;',
  9625. access: '&#x2303;&#x2325;'
  9626. };
  9627. var other = {
  9628. meta: 'Ctrl',
  9629. access: 'Shift+Alt'
  9630. };
  9631. var replace = global$6.mac ? mac : other;
  9632. var shortcut = source.split('+');
  9633. var updated = map(shortcut, function (segment) {
  9634. var search = segment.toLowerCase().trim();
  9635. return has(replace, search) ? replace[search] : segment;
  9636. });
  9637. return global$6.mac ? updated.join('') : updated.join('+');
  9638. };
  9639. var renderIcon = function (iconHtml) {
  9640. return {
  9641. dom: {
  9642. tag: 'div',
  9643. classes: [iconClass],
  9644. innerHtml: iconHtml
  9645. }
  9646. };
  9647. };
  9648. var renderText = function (text$1) {
  9649. return {
  9650. dom: {
  9651. tag: 'div',
  9652. classes: [textClass]
  9653. },
  9654. components: [text(global$5.translate(text$1))]
  9655. };
  9656. };
  9657. var renderHtml = function (html) {
  9658. return {
  9659. dom: {
  9660. tag: 'div',
  9661. classes: [textClass],
  9662. innerHtml: html
  9663. }
  9664. };
  9665. };
  9666. var renderStyledText = function (style, text$1) {
  9667. return {
  9668. dom: {
  9669. tag: 'div',
  9670. classes: [textClass]
  9671. },
  9672. components: [{
  9673. dom: {
  9674. tag: style.tag,
  9675. styles: style.styles
  9676. },
  9677. components: [text(global$5.translate(text$1))]
  9678. }]
  9679. };
  9680. };
  9681. var renderShortcut = function (shortcut) {
  9682. return {
  9683. dom: {
  9684. tag: 'div',
  9685. classes: [accessoryClass],
  9686. innerHtml: convertText(shortcut)
  9687. }
  9688. };
  9689. };
  9690. var renderCheckmark = function (icons) {
  9691. return {
  9692. dom: {
  9693. tag: 'div',
  9694. classes: [checkmarkClass],
  9695. innerHtml: get$d('checkmark', icons)
  9696. }
  9697. };
  9698. };
  9699. var renderSubmenuCaret = function (icons) {
  9700. return {
  9701. dom: {
  9702. tag: 'div',
  9703. classes: [caretClass],
  9704. innerHtml: get$d('chevron-right', icons)
  9705. }
  9706. };
  9707. };
  9708. var renderDownwardsCaret = function (icons) {
  9709. return {
  9710. dom: {
  9711. tag: 'div',
  9712. classes: [caretClass],
  9713. innerHtml: get$d('chevron-down', icons)
  9714. }
  9715. };
  9716. };
  9717. var renderColorStructure = function (itemText, itemValue, iconSvg, providerBackstage) {
  9718. var colorPickerCommand = 'custom';
  9719. var removeColorCommand = 'remove';
  9720. var getDom = function () {
  9721. var common = colorClass;
  9722. var icon = iconSvg.getOr('');
  9723. var attributes = itemText.map(function (text) {
  9724. return { title: providerBackstage.translate(text) };
  9725. }).getOr({});
  9726. var baseDom = {
  9727. tag: 'div',
  9728. attributes: attributes,
  9729. classes: [common]
  9730. };
  9731. if (itemValue === colorPickerCommand) {
  9732. return __assign(__assign({}, baseDom), {
  9733. tag: 'button',
  9734. classes: __spreadArrays(baseDom.classes, ['tox-swatches__picker-btn']),
  9735. innerHtml: icon
  9736. });
  9737. } else if (itemValue === removeColorCommand) {
  9738. return __assign(__assign({}, baseDom), {
  9739. classes: __spreadArrays(baseDom.classes, ['tox-swatch--remove']),
  9740. innerHtml: icon
  9741. });
  9742. } else {
  9743. return __assign(__assign({}, baseDom), {
  9744. attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }),
  9745. styles: { 'background-color': itemValue }
  9746. });
  9747. }
  9748. };
  9749. return {
  9750. dom: getDom(),
  9751. optComponents: []
  9752. };
  9753. };
  9754. var renderNormalItemStructure = function (info, icon, renderIcons, textRender, rtlClass) {
  9755. var leftIcon = renderIcons ? icon.or(Option.some('')).map(renderIcon) : Option.none();
  9756. var checkmark = info.checkMark;
  9757. var domTitle = info.ariaLabel.map(function (label) {
  9758. return { attributes: { title: global$5.translate(label) } };
  9759. }).getOr({});
  9760. var dom = __assign({
  9761. tag: 'div',
  9762. classes: [
  9763. navClass,
  9764. selectableClass
  9765. ].concat(rtlClass ? [iconClassRtl] : [])
  9766. }, domTitle);
  9767. var content = info.htmlContent.fold(function () {
  9768. return info.textContent.map(textRender);
  9769. }, function (html) {
  9770. return Option.some(renderHtml(html));
  9771. });
  9772. var menuItem = {
  9773. dom: dom,
  9774. optComponents: [
  9775. leftIcon,
  9776. content,
  9777. info.shortcutContent.map(renderShortcut),
  9778. checkmark,
  9779. info.caret
  9780. ]
  9781. };
  9782. return menuItem;
  9783. };
  9784. var rtlIcon = [
  9785. 'list-num-default',
  9786. 'list-num-lower-alpha',
  9787. 'list-num-lower-greek',
  9788. 'list-num-lower-roman',
  9789. 'list-num-upper-alpha',
  9790. 'list-num-upper-roman'
  9791. ];
  9792. var rtlTransform = [
  9793. 'list-bull-circle',
  9794. 'list-bull-default',
  9795. 'list-bull-square'
  9796. ];
  9797. var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) {
  9798. if (fallbackIcon === void 0) {
  9799. fallbackIcon = Option.none();
  9800. }
  9801. var getIconName = function (iconName) {
  9802. return iconName.map(function (name) {
  9803. return global$5.isRtl() && contains(rtlIcon, name) ? name + '-rtl' : name;
  9804. });
  9805. };
  9806. var needRtlClass = global$5.isRtl() && info.iconContent.exists(function (name) {
  9807. return contains(rtlTransform, name);
  9808. });
  9809. var icon = getIconName(info.iconContent).map(function (iconName) {
  9810. return getOr(iconName, providersBackstage.icons, fallbackIcon);
  9811. });
  9812. var textRender = Option.from(info.meta).fold(function () {
  9813. return renderText;
  9814. }, function (meta) {
  9815. return has(meta, 'style') ? curry(renderStyledText, meta.style) : renderText;
  9816. });
  9817. if (info.presets === 'color') {
  9818. return renderColorStructure(info.ariaLabel, info.value, icon, providersBackstage);
  9819. } else {
  9820. return renderNormalItemStructure(info, icon, renderIcons, textRender, needRtlClass);
  9821. }
  9822. };
  9823. var nativeDisabled = [
  9824. 'input',
  9825. 'button',
  9826. 'textarea',
  9827. 'select'
  9828. ];
  9829. var onLoad$5 = function (component, disableConfig, disableState) {
  9830. var f = disableConfig.disabled() ? disable : enable;
  9831. f(component, disableConfig, disableState);
  9832. };
  9833. var hasNative = function (component, config) {
  9834. return config.useNative === true && contains(nativeDisabled, name(component.element()));
  9835. };
  9836. var nativeIsDisabled = function (component) {
  9837. return has$1(component.element(), 'disabled');
  9838. };
  9839. var nativeDisable = function (component) {
  9840. set$1(component.element(), 'disabled', 'disabled');
  9841. };
  9842. var nativeEnable = function (component) {
  9843. remove$1(component.element(), 'disabled');
  9844. };
  9845. var ariaIsDisabled = function (component) {
  9846. return get$2(component.element(), 'aria-disabled') === 'true';
  9847. };
  9848. var ariaDisable = function (component) {
  9849. set$1(component.element(), 'aria-disabled', 'true');
  9850. };
  9851. var ariaEnable = function (component) {
  9852. set$1(component.element(), 'aria-disabled', 'false');
  9853. };
  9854. var disable = function (component, disableConfig, _disableState) {
  9855. disableConfig.disableClass.each(function (disableClass) {
  9856. add$2(component.element(), disableClass);
  9857. });
  9858. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  9859. f(component);
  9860. disableConfig.onDisabled(component);
  9861. };
  9862. var enable = function (component, disableConfig, _disableState) {
  9863. disableConfig.disableClass.each(function (disableClass) {
  9864. remove$4(component.element(), disableClass);
  9865. });
  9866. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  9867. f(component);
  9868. disableConfig.onEnabled(component);
  9869. };
  9870. var isDisabled = function (component, disableConfig) {
  9871. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  9872. };
  9873. var set$7 = function (component, disableConfig, disableState, disabled) {
  9874. var f = disabled ? disable : enable;
  9875. f(component, disableConfig, disableState);
  9876. };
  9877. var DisableApis = /*#__PURE__*/Object.freeze({
  9878. __proto__: null,
  9879. enable: enable,
  9880. disable: disable,
  9881. isDisabled: isDisabled,
  9882. onLoad: onLoad$5,
  9883. set: set$7
  9884. });
  9885. var exhibit$3 = function (base, disableConfig) {
  9886. return nu$6({ classes: disableConfig.disabled ? disableConfig.disableClass.map(pure).getOr([]) : [] });
  9887. };
  9888. var events$9 = function (disableConfig, disableState) {
  9889. return derive([
  9890. abort(execute(), function (component, _simulatedEvent) {
  9891. return isDisabled(component, disableConfig);
  9892. }),
  9893. loadEvent(disableConfig, disableState, onLoad$5)
  9894. ]);
  9895. };
  9896. var ActiveDisable = /*#__PURE__*/Object.freeze({
  9897. __proto__: null,
  9898. exhibit: exhibit$3,
  9899. events: events$9
  9900. });
  9901. var DisableSchema = [
  9902. defaultedFunction('disabled', never),
  9903. defaulted$1('useNative', true),
  9904. option('disableClass'),
  9905. onHandler('onDisabled'),
  9906. onHandler('onEnabled')
  9907. ];
  9908. var Disabling = create$1({
  9909. fields: DisableSchema,
  9910. name: 'disabling',
  9911. active: ActiveDisable,
  9912. apis: DisableApis
  9913. });
  9914. var global$7 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  9915. var global$8 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  9916. var getSkinUrl = function (editor) {
  9917. var settings = editor.settings;
  9918. var skin = settings.skin;
  9919. var skinUrl = settings.skin_url;
  9920. if (skin !== false) {
  9921. var skinName = skin ? skin : 'oxide';
  9922. if (skinUrl) {
  9923. skinUrl = editor.documentBaseURI.toAbsolute(skinUrl);
  9924. } else {
  9925. skinUrl = global$8.baseURL + '/skins/ui/' + skinName;
  9926. }
  9927. }
  9928. return skinUrl;
  9929. };
  9930. var isReadOnly = function (editor) {
  9931. return editor.getParam('readonly', false, 'boolean');
  9932. };
  9933. var isSkinDisabled = function (editor) {
  9934. return editor.getParam('skin') === false;
  9935. };
  9936. var getHeightSetting = function (editor) {
  9937. return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200));
  9938. };
  9939. var getWidthSetting = function (editor) {
  9940. return editor.getParam('width', global$7.DOM.getStyle(editor.getElement(), 'width'));
  9941. };
  9942. var getMinWidthSetting = function (editor) {
  9943. return Option.from(editor.settings.min_width).filter(isNumber);
  9944. };
  9945. var getMinHeightSetting = function (editor) {
  9946. return Option.from(editor.settings.min_height).filter(isNumber);
  9947. };
  9948. var getMaxWidthSetting = function (editor) {
  9949. return Option.from(editor.getParam('max_width')).filter(isNumber);
  9950. };
  9951. var getMaxHeightSetting = function (editor) {
  9952. return Option.from(editor.getParam('max_height')).filter(isNumber);
  9953. };
  9954. var getUserStyleFormats = function (editor) {
  9955. return Option.from(editor.getParam('style_formats')).filter(isArray);
  9956. };
  9957. var isMergeStyleFormats = function (editor) {
  9958. return editor.getParam('style_formats_merge', false, 'boolean');
  9959. };
  9960. var getRemovedMenuItems = function (editor) {
  9961. return editor.getParam('removed_menuitems', '');
  9962. };
  9963. var isMenubarEnabled = function (editor) {
  9964. return editor.getParam('menubar', true, 'boolean') !== false;
  9965. };
  9966. var isToolbarEnabled = function (editor) {
  9967. var toolbar = editor.getParam('toolbar', true);
  9968. var isToolbarTrue = toolbar === true;
  9969. var isToolbarString = isString(toolbar);
  9970. var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0;
  9971. return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue);
  9972. };
  9973. var getMultipleToolbarsSetting = function (editor) {
  9974. var keys$1 = keys(editor.settings);
  9975. var toolbarKeys = filter(keys$1, function (key) {
  9976. return /^toolbar([1-9])$/.test(key);
  9977. });
  9978. var toolbars = map(toolbarKeys, function (key) {
  9979. return editor.getParam(key, false, 'string');
  9980. });
  9981. var toolbarArray = filter(toolbars, function (toolbar) {
  9982. return typeof toolbar === 'string';
  9983. });
  9984. return toolbarArray.length > 0 ? Option.some(toolbarArray) : Option.none();
  9985. };
  9986. var isMultipleToolbars = function (editor) {
  9987. return getMultipleToolbarsSetting(editor).fold(function () {
  9988. var toolbar = editor.getParam('toolbar', [], 'string[]');
  9989. return toolbar.length > 0;
  9990. }, function () {
  9991. return true;
  9992. });
  9993. };
  9994. var ToolbarMode;
  9995. (function (ToolbarMode) {
  9996. ToolbarMode['default'] = 'wrap';
  9997. ToolbarMode['floating'] = 'floating';
  9998. ToolbarMode['sliding'] = 'sliding';
  9999. ToolbarMode['scrolling'] = 'scrolling';
  10000. }(ToolbarMode || (ToolbarMode = {})));
  10001. var getToolbarMode = function (editor) {
  10002. return editor.getParam('toolbar_mode', '', 'string');
  10003. };
  10004. var ToolbarLocation;
  10005. (function (ToolbarLocation) {
  10006. ToolbarLocation['auto'] = 'auto';
  10007. ToolbarLocation['top'] = 'top';
  10008. ToolbarLocation['bottom'] = 'bottom';
  10009. }(ToolbarLocation || (ToolbarLocation = {})));
  10010. var getToolbarGroups = function (editor) {
  10011. return editor.getParam('toolbar_groups', {}, 'object');
  10012. };
  10013. var getToolbarLocation = function (editor) {
  10014. return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string');
  10015. };
  10016. var isToolbarLocationBottom = function (editor) {
  10017. return getToolbarLocation(editor) === ToolbarLocation.bottom;
  10018. };
  10019. var fixedContainerSelector = function (editor) {
  10020. return editor.getParam('fixed_toolbar_container', '', 'string');
  10021. };
  10022. var fixedContainerElement = function (editor) {
  10023. var selector = fixedContainerSelector(editor);
  10024. return selector.length > 0 && editor.inline ? descendant$1(body(), selector) : Option.none();
  10025. };
  10026. var useFixedContainer = function (editor) {
  10027. return editor.inline && fixedContainerElement(editor).isSome();
  10028. };
  10029. var getUiContainer = function (editor) {
  10030. var fixedContainer = fixedContainerElement(editor);
  10031. return fixedContainer.getOr(body());
  10032. };
  10033. var isDistractionFree = function (editor) {
  10034. return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor);
  10035. };
  10036. var isStickyToolbar = function (editor) {
  10037. var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean');
  10038. return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor);
  10039. };
  10040. var isDraggableModal = function (editor) {
  10041. return editor.getParam('draggable_modal', false, 'boolean');
  10042. };
  10043. var ReadOnlyChannel = 'silver.readonly';
  10044. var ReadOnlyDataSchema = objOf([strictBoolean('readonly')]);
  10045. var broadcastReadonly = function (uiComponents, readonly) {
  10046. var outerContainer = uiComponents.outerContainer;
  10047. var target = outerContainer.element();
  10048. if (readonly) {
  10049. uiComponents.mothership.broadcastOn([dismissPopups()], { target: target });
  10050. uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target });
  10051. }
  10052. uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10053. uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly });
  10054. };
  10055. var setupReadonlyModeSwitch = function (editor, uiComponents) {
  10056. editor.on('init', function () {
  10057. if (editor.mode.isReadOnly()) {
  10058. broadcastReadonly(uiComponents, true);
  10059. }
  10060. });
  10061. editor.on('SwitchMode', function () {
  10062. return broadcastReadonly(uiComponents, editor.mode.isReadOnly());
  10063. });
  10064. if (isReadOnly(editor)) {
  10065. editor.setMode('readonly');
  10066. }
  10067. };
  10068. var receivingConfig = function () {
  10069. var _a;
  10070. return Receiving.config({
  10071. channels: (_a = {}, _a[ReadOnlyChannel] = {
  10072. schema: ReadOnlyDataSchema,
  10073. onReceive: function (comp, data) {
  10074. Disabling.set(comp, data.readonly);
  10075. }
  10076. }, _a)
  10077. });
  10078. };
  10079. var item = function (disabled) {
  10080. return Disabling.config({
  10081. disabled: disabled,
  10082. disableClass: 'tox-collection__item--state-disabled'
  10083. });
  10084. };
  10085. var button = function (disabled) {
  10086. return Disabling.config({ disabled: disabled });
  10087. };
  10088. var splitButton = function (disabled) {
  10089. return Disabling.config({
  10090. disabled: disabled,
  10091. disableClass: 'tox-tbtn--disabled'
  10092. });
  10093. };
  10094. var toolbarButton = function (disabled) {
  10095. return Disabling.config({
  10096. disabled: disabled,
  10097. disableClass: 'tox-tbtn--disabled',
  10098. useNative: false
  10099. });
  10100. };
  10101. var DisablingConfigs = {
  10102. item: item,
  10103. button: button,
  10104. splitButton: splitButton,
  10105. toolbarButton: toolbarButton
  10106. };
  10107. var runWithApi = function (info, comp) {
  10108. var api = info.getApi(comp);
  10109. return function (f) {
  10110. f(api);
  10111. };
  10112. };
  10113. var onControlAttached = function (info, editorOffCell) {
  10114. return runOnAttached(function (comp) {
  10115. var run = runWithApi(info, comp);
  10116. run(function (api) {
  10117. var onDestroy = info.onSetup(api);
  10118. if (onDestroy !== null && onDestroy !== undefined) {
  10119. editorOffCell.set(onDestroy);
  10120. }
  10121. });
  10122. });
  10123. };
  10124. var onControlDetached = function (getApi, editorOffCell) {
  10125. return runOnDetached(function (comp) {
  10126. return runWithApi(getApi, comp)(editorOffCell.get());
  10127. });
  10128. };
  10129. var ItemResponse;
  10130. (function (ItemResponse) {
  10131. ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE';
  10132. ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX';
  10133. }(ItemResponse || (ItemResponse = {})));
  10134. var ItemResponse$1 = ItemResponse;
  10135. var onMenuItemExecute = function (info, itemResponse) {
  10136. return runOnExecute(function (comp, simulatedEvent) {
  10137. runWithApi(info, comp)(info.onAction);
  10138. if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) {
  10139. emit(comp, sandboxClose());
  10140. simulatedEvent.stop();
  10141. }
  10142. });
  10143. };
  10144. var menuItemEventOrder = {
  10145. 'alloy.execute': [
  10146. 'disabling',
  10147. 'alloy.base.behaviour',
  10148. 'toggling',
  10149. 'item-events'
  10150. ]
  10151. };
  10152. var componentRenderPipeline = function (xs) {
  10153. return bind(xs, function (o) {
  10154. return o.toArray();
  10155. });
  10156. };
  10157. var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) {
  10158. var editorOffCell = Cell(noop);
  10159. return {
  10160. type: 'item',
  10161. dom: structure.dom,
  10162. components: componentRenderPipeline(structure.optComponents),
  10163. data: spec.data,
  10164. eventOrder: menuItemEventOrder,
  10165. hasSubmenu: spec.triggersSubmenu,
  10166. itemBehaviours: derive$1([
  10167. config('item-events', [
  10168. onMenuItemExecute(spec, itemResponse),
  10169. onControlAttached(spec, editorOffCell),
  10170. onControlDetached(spec, editorOffCell)
  10171. ]),
  10172. DisablingConfigs.item(function () {
  10173. return spec.disabled || providersbackstage.isReadOnly();
  10174. }),
  10175. receivingConfig(),
  10176. Replacing.config({})
  10177. ].concat(spec.itemBehaviours))
  10178. };
  10179. };
  10180. var buildData = function (source) {
  10181. return {
  10182. value: source.value,
  10183. meta: __assign({ text: source.text.getOr('') }, source.meta)
  10184. };
  10185. };
  10186. var tooltipBehaviour = function (meta, sharedBackstage) {
  10187. return get(meta, 'tooltipWorker').map(function (tooltipWorker) {
  10188. return [Tooltipping.config({
  10189. lazySink: sharedBackstage.getSink,
  10190. tooltipDom: {
  10191. tag: 'div',
  10192. classes: ['tox-tooltip-worker-container']
  10193. },
  10194. tooltipComponents: [],
  10195. anchor: function (comp) {
  10196. return {
  10197. anchor: 'submenu',
  10198. item: comp,
  10199. overrides: { maxHeightFunction: expandable }
  10200. };
  10201. },
  10202. mode: 'follow-highlight',
  10203. onShow: function (component, _tooltip) {
  10204. tooltipWorker(function (elm) {
  10205. Tooltipping.setComponents(component, [external({ element: Element.fromDom(elm) })]);
  10206. });
  10207. }
  10208. })];
  10209. }).getOr([]);
  10210. };
  10211. var escapeRegExp = function (text) {
  10212. return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  10213. };
  10214. var encodeText = function (text) {
  10215. return global$7.DOM.encode(text);
  10216. };
  10217. var replaceText = function (text, matchText) {
  10218. var translated = global$5.translate(text);
  10219. var encoded = encodeText(translated);
  10220. if (matchText.length > 0) {
  10221. var escapedMatchRegex = new RegExp(escapeRegExp(matchText), 'gi');
  10222. return encoded.replace(escapedMatchRegex, function (match) {
  10223. return '<span class="tox-autocompleter-highlight">' + match + '</span>';
  10224. });
  10225. } else {
  10226. return encoded;
  10227. }
  10228. };
  10229. var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) {
  10230. if (renderIcons === void 0) {
  10231. renderIcons = true;
  10232. }
  10233. var structure = renderItemStructure({
  10234. presets: presets,
  10235. textContent: Option.none(),
  10236. htmlContent: useText ? spec.text.map(function (text) {
  10237. return replaceText(text, matchText);
  10238. }) : Option.none(),
  10239. ariaLabel: spec.text,
  10240. iconContent: spec.icon,
  10241. shortcutContent: Option.none(),
  10242. checkMark: Option.none(),
  10243. caret: Option.none(),
  10244. value: spec.value
  10245. }, sharedBackstage.providers, renderIcons, spec.icon);
  10246. return renderCommonItem({
  10247. data: buildData(spec),
  10248. disabled: spec.disabled,
  10249. getApi: function () {
  10250. return {};
  10251. },
  10252. onAction: function (_api) {
  10253. return onItemValueHandler(spec.value, spec.meta);
  10254. },
  10255. onSetup: function () {
  10256. return function () {
  10257. };
  10258. },
  10259. triggersSubmenu: false,
  10260. itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage)
  10261. }, structure, itemResponse, sharedBackstage.providers);
  10262. };
  10263. var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) {
  10264. if (renderIcons === void 0) {
  10265. renderIcons = true;
  10266. }
  10267. var getApi = function (component) {
  10268. return {
  10269. setActive: function (state) {
  10270. Toggling.set(component, state);
  10271. },
  10272. isActive: function () {
  10273. return Toggling.isOn(component);
  10274. },
  10275. isDisabled: function () {
  10276. return Disabling.isDisabled(component);
  10277. },
  10278. setDisabled: function (state) {
  10279. return Disabling.set(component, state);
  10280. }
  10281. };
  10282. };
  10283. var structure = renderItemStructure({
  10284. presets: presets,
  10285. textContent: useText ? spec.text : Option.none(),
  10286. htmlContent: Option.none(),
  10287. ariaLabel: spec.text,
  10288. iconContent: spec.icon,
  10289. shortcutContent: useText ? spec.shortcut : Option.none(),
  10290. checkMark: useText ? Option.some(renderCheckmark(providersBackstage.icons)) : Option.none(),
  10291. caret: Option.none(),
  10292. value: spec.value
  10293. }, providersBackstage, renderIcons);
  10294. return deepMerge(renderCommonItem({
  10295. data: buildData(spec),
  10296. disabled: spec.disabled,
  10297. getApi: getApi,
  10298. onAction: function (_api) {
  10299. return onItemValueHandler(spec.value);
  10300. },
  10301. onSetup: function (api) {
  10302. api.setActive(isSelected);
  10303. return function () {
  10304. };
  10305. },
  10306. triggersSubmenu: false,
  10307. itemBehaviours: []
  10308. }, structure, itemResponse, providersBackstage), {
  10309. toggling: {
  10310. toggleClass: tickedClass,
  10311. toggleOnExecute: false,
  10312. selected: spec.active
  10313. }
  10314. });
  10315. };
  10316. var parts$2 = constant(generate$4(owner$2(), parts()));
  10317. var cellOverEvent = generate$1('cell-over');
  10318. var cellExecuteEvent = generate$1('cell-execute');
  10319. var makeCell = function (row, col, labelId) {
  10320. var _a;
  10321. var emitCellOver = function (c) {
  10322. return emitWith(c, cellOverEvent, {
  10323. row: row,
  10324. col: col
  10325. });
  10326. };
  10327. var emitExecute = function (c) {
  10328. return emitWith(c, cellExecuteEvent, {
  10329. row: row,
  10330. col: col
  10331. });
  10332. };
  10333. var onClick = function (c, se) {
  10334. se.stop();
  10335. emitExecute(c);
  10336. };
  10337. return build$1({
  10338. dom: {
  10339. tag: 'div',
  10340. attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a)
  10341. },
  10342. behaviours: derive$1([
  10343. config('insert-table-picker-cell', [
  10344. run(mouseover(), Focusing.focus),
  10345. run(execute(), emitExecute),
  10346. run(click(), onClick),
  10347. run(tap(), onClick)
  10348. ]),
  10349. Toggling.config({
  10350. toggleClass: 'tox-insert-table-picker__selected',
  10351. toggleOnExecute: false
  10352. }),
  10353. Focusing.config({ onFocus: emitCellOver })
  10354. ])
  10355. });
  10356. };
  10357. var makeCells = function (labelId, numRows, numCols) {
  10358. var cells = [];
  10359. for (var i = 0; i < numRows; i++) {
  10360. var row = [];
  10361. for (var j = 0; j < numCols; j++) {
  10362. row.push(makeCell(i, j, labelId));
  10363. }
  10364. cells.push(row);
  10365. }
  10366. return cells;
  10367. };
  10368. var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) {
  10369. for (var i = 0; i < numRows; i++) {
  10370. for (var j = 0; j < numColumns; j++) {
  10371. Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn);
  10372. }
  10373. }
  10374. };
  10375. var makeComponents = function (cells) {
  10376. return bind(cells, function (cellRow) {
  10377. return map(cellRow, premade$1);
  10378. });
  10379. };
  10380. var makeLabelText = function (row, col) {
  10381. return text(col + 1 + 'x' + (row + 1));
  10382. };
  10383. var renderInsertTableMenuItem = function (spec) {
  10384. var numRows = 10;
  10385. var numColumns = 10;
  10386. var sizeLabelId = generate$1('size-label');
  10387. var cells = makeCells(sizeLabelId, numRows, numColumns);
  10388. var memLabel = record({
  10389. dom: {
  10390. tag: 'span',
  10391. classes: ['tox-insert-table-picker__label'],
  10392. attributes: { id: sizeLabelId }
  10393. },
  10394. components: [text('0x0')],
  10395. behaviours: derive$1([Replacing.config({})])
  10396. });
  10397. return {
  10398. type: 'widget',
  10399. data: { value: generate$1('widget-id') },
  10400. dom: {
  10401. tag: 'div',
  10402. classes: ['tox-fancymenuitem']
  10403. },
  10404. autofocus: true,
  10405. components: [parts$2().widget({
  10406. dom: {
  10407. tag: 'div',
  10408. classes: ['tox-insert-table-picker']
  10409. },
  10410. components: makeComponents(cells).concat(memLabel.asSpec()),
  10411. behaviours: derive$1([
  10412. config('insert-table-picker', [
  10413. runWithTarget(cellOverEvent, function (c, t, e) {
  10414. var row = e.event().row();
  10415. var col = e.event().col();
  10416. selectCells(cells, row, col, numRows, numColumns);
  10417. Replacing.set(memLabel.get(c), [makeLabelText(row, col)]);
  10418. }),
  10419. runWithTarget(cellExecuteEvent, function (c, _, e) {
  10420. spec.onAction({
  10421. numRows: e.event().row() + 1,
  10422. numColumns: e.event().col() + 1
  10423. });
  10424. emit(c, sandboxClose());
  10425. })
  10426. ]),
  10427. Keying.config({
  10428. initSize: {
  10429. numRows: numRows,
  10430. numColumns: numColumns
  10431. },
  10432. mode: 'flatgrid',
  10433. selector: '[role="button"]'
  10434. })
  10435. ])
  10436. })]
  10437. };
  10438. };
  10439. var hexColour = function (value) {
  10440. return { value: value };
  10441. };
  10442. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  10443. var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
  10444. var isHexString = function (hex) {
  10445. return shorthandRegex.test(hex) || longformRegex.test(hex);
  10446. };
  10447. var getLongForm = function (hex) {
  10448. var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) {
  10449. return r + r + g + g + b + b;
  10450. });
  10451. return { value: hexString };
  10452. };
  10453. var extractValues = function (hex) {
  10454. var longForm = getLongForm(hex);
  10455. var splitForm = longformRegex.exec(longForm.value);
  10456. return splitForm === null ? [
  10457. 'FFFFFF',
  10458. 'FF',
  10459. 'FF',
  10460. 'FF'
  10461. ] : splitForm;
  10462. };
  10463. var toHex = function (component) {
  10464. var hex = component.toString(16);
  10465. return hex.length === 1 ? '0' + hex : hex;
  10466. };
  10467. var fromRgba = function (rgbaColour) {
  10468. var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue);
  10469. return hexColour(value);
  10470. };
  10471. var min = Math.min;
  10472. var max = Math.max;
  10473. var round = Math.round;
  10474. var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/;
  10475. var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/;
  10476. var rgbaColour = function (red, green, blue, alpha) {
  10477. return {
  10478. red: red,
  10479. green: green,
  10480. blue: blue,
  10481. alpha: alpha
  10482. };
  10483. };
  10484. var isRgbaComponent = function (value) {
  10485. var num = parseInt(value, 10);
  10486. return num.toString() === value && num >= 0 && num <= 255;
  10487. };
  10488. var fromHsv = function (hsv) {
  10489. var r;
  10490. var g;
  10491. var b;
  10492. var hue = (hsv.hue || 0) % 360;
  10493. var saturation = hsv.saturation / 100;
  10494. var brightness = hsv.value / 100;
  10495. saturation = max(0, min(saturation, 1));
  10496. brightness = max(0, min(brightness, 1));
  10497. if (saturation === 0) {
  10498. r = g = b = round(255 * brightness);
  10499. return rgbaColour(r, g, b, 1);
  10500. }
  10501. var side = hue / 60;
  10502. var chroma = brightness * saturation;
  10503. var x = chroma * (1 - Math.abs(side % 2 - 1));
  10504. var match = brightness - chroma;
  10505. switch (Math.floor(side)) {
  10506. case 0:
  10507. r = chroma;
  10508. g = x;
  10509. b = 0;
  10510. break;
  10511. case 1:
  10512. r = x;
  10513. g = chroma;
  10514. b = 0;
  10515. break;
  10516. case 2:
  10517. r = 0;
  10518. g = chroma;
  10519. b = x;
  10520. break;
  10521. case 3:
  10522. r = 0;
  10523. g = x;
  10524. b = chroma;
  10525. break;
  10526. case 4:
  10527. r = x;
  10528. g = 0;
  10529. b = chroma;
  10530. break;
  10531. case 5:
  10532. r = chroma;
  10533. g = 0;
  10534. b = x;
  10535. break;
  10536. default:
  10537. r = g = b = 0;
  10538. }
  10539. r = round(255 * (r + match));
  10540. g = round(255 * (g + match));
  10541. b = round(255 * (b + match));
  10542. return rgbaColour(r, g, b, 1);
  10543. };
  10544. var fromHex = function (hexColour) {
  10545. var result = extractValues(hexColour);
  10546. var red = parseInt(result[1], 16);
  10547. var green = parseInt(result[2], 16);
  10548. var blue = parseInt(result[3], 16);
  10549. return rgbaColour(red, green, blue, 1);
  10550. };
  10551. var fromStringValues = function (red, green, blue, alpha) {
  10552. var r = parseInt(red, 10);
  10553. var g = parseInt(green, 10);
  10554. var b = parseInt(blue, 10);
  10555. var a = parseFloat(alpha);
  10556. return rgbaColour(r, g, b, a);
  10557. };
  10558. var fromString = function (rgbaString) {
  10559. if (rgbaString === 'transparent') {
  10560. return Option.some(rgbaColour(0, 0, 0, 0));
  10561. }
  10562. var rgbMatch = rgbRegex.exec(rgbaString);
  10563. if (rgbMatch !== null) {
  10564. return Option.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1'));
  10565. }
  10566. var rgbaMatch = rgbaRegex.exec(rgbaString);
  10567. if (rgbaMatch !== null) {
  10568. return Option.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4]));
  10569. }
  10570. return Option.none();
  10571. };
  10572. var toString = function (rgba) {
  10573. return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')';
  10574. };
  10575. var red = rgbaColour(255, 0, 0, 1);
  10576. var global$9 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage');
  10577. var storageName = 'tinymce-custom-colors';
  10578. function ColorCache (max) {
  10579. if (max === void 0) {
  10580. max = 10;
  10581. }
  10582. var storageString = global$9.getItem(storageName);
  10583. var localstorage = isString(storageString) ? JSON.parse(storageString) : [];
  10584. var prune = function (list) {
  10585. var diff = max - list.length;
  10586. return diff < 0 ? list.slice(0, max) : list;
  10587. };
  10588. var cache = prune(localstorage);
  10589. var add = function (key) {
  10590. indexOf(cache, key).each(remove);
  10591. cache.unshift(key);
  10592. if (cache.length > max) {
  10593. cache.pop();
  10594. }
  10595. global$9.setItem(storageName, JSON.stringify(cache));
  10596. };
  10597. var remove = function (idx) {
  10598. cache.splice(idx, 1);
  10599. };
  10600. var state = function () {
  10601. return cache.slice(0);
  10602. };
  10603. return {
  10604. add: add,
  10605. state: state
  10606. };
  10607. }
  10608. var choiceItem = 'choiceitem';
  10609. var defaultColors = [
  10610. {
  10611. type: choiceItem,
  10612. text: 'Light Green',
  10613. value: '#BFEDD2'
  10614. },
  10615. {
  10616. type: choiceItem,
  10617. text: 'Light Yellow',
  10618. value: '#FBEEB8'
  10619. },
  10620. {
  10621. type: choiceItem,
  10622. text: 'Light Red',
  10623. value: '#F8CAC6'
  10624. },
  10625. {
  10626. type: choiceItem,
  10627. text: 'Light Purple',
  10628. value: '#ECCAFA'
  10629. },
  10630. {
  10631. type: choiceItem,
  10632. text: 'Light Blue',
  10633. value: '#C2E0F4'
  10634. },
  10635. {
  10636. type: choiceItem,
  10637. text: 'Green',
  10638. value: '#2DC26B'
  10639. },
  10640. {
  10641. type: choiceItem,
  10642. text: 'Yellow',
  10643. value: '#F1C40F'
  10644. },
  10645. {
  10646. type: choiceItem,
  10647. text: 'Red',
  10648. value: '#E03E2D'
  10649. },
  10650. {
  10651. type: choiceItem,
  10652. text: 'Purple',
  10653. value: '#B96AD9'
  10654. },
  10655. {
  10656. type: choiceItem,
  10657. text: 'Blue',
  10658. value: '#3598DB'
  10659. },
  10660. {
  10661. type: choiceItem,
  10662. text: 'Dark Turquoise',
  10663. value: '#169179'
  10664. },
  10665. {
  10666. type: choiceItem,
  10667. text: 'Orange',
  10668. value: '#E67E23'
  10669. },
  10670. {
  10671. type: choiceItem,
  10672. text: 'Dark Red',
  10673. value: '#BA372A'
  10674. },
  10675. {
  10676. type: choiceItem,
  10677. text: 'Dark Purple',
  10678. value: '#843FA1'
  10679. },
  10680. {
  10681. type: choiceItem,
  10682. text: 'Dark Blue',
  10683. value: '#236FA1'
  10684. },
  10685. {
  10686. type: choiceItem,
  10687. text: 'Light Gray',
  10688. value: '#ECF0F1'
  10689. },
  10690. {
  10691. type: choiceItem,
  10692. text: 'Medium Gray',
  10693. value: '#CED4D9'
  10694. },
  10695. {
  10696. type: choiceItem,
  10697. text: 'Gray',
  10698. value: '#95A5A6'
  10699. },
  10700. {
  10701. type: choiceItem,
  10702. text: 'Dark Gray',
  10703. value: '#7E8C8D'
  10704. },
  10705. {
  10706. type: choiceItem,
  10707. text: 'Navy Blue',
  10708. value: '#34495E'
  10709. },
  10710. {
  10711. type: choiceItem,
  10712. text: 'Black',
  10713. value: '#000000'
  10714. },
  10715. {
  10716. type: choiceItem,
  10717. text: 'White',
  10718. value: '#ffffff'
  10719. }
  10720. ];
  10721. var colorCache = ColorCache(10);
  10722. var mapColors = function (colorMap) {
  10723. var colors = [];
  10724. var canvas = domGlobals.document.createElement('canvas');
  10725. canvas.height = 1;
  10726. canvas.width = 1;
  10727. var ctx = canvas.getContext('2d');
  10728. var byteAsHex = function (colorByte, alphaByte) {
  10729. var bg = 255;
  10730. var alpha = alphaByte / 255;
  10731. var colorByteWithWhiteBg = Math.round(colorByte * alpha + bg * (1 - alpha));
  10732. return ('0' + colorByteWithWhiteBg.toString(16)).slice(-2).toUpperCase();
  10733. };
  10734. var asHexColor = function (color) {
  10735. if (/^[0-9A-Fa-f]{6}$/.test(color)) {
  10736. return '#' + color.toUpperCase();
  10737. }
  10738. ctx.clearRect(0, 0, canvas.width, canvas.height);
  10739. ctx.fillStyle = '#FFFFFF';
  10740. ctx.fillStyle = color;
  10741. ctx.fillRect(0, 0, 1, 1);
  10742. var rgba = ctx.getImageData(0, 0, 1, 1).data;
  10743. var r = rgba[0], g = rgba[1], b = rgba[2], a = rgba[3];
  10744. return '#' + byteAsHex(r, a) + byteAsHex(g, a) + byteAsHex(b, a);
  10745. };
  10746. for (var i = 0; i < colorMap.length; i += 2) {
  10747. colors.push({
  10748. text: colorMap[i + 1],
  10749. value: asHexColor(colorMap[i]),
  10750. type: 'choiceitem'
  10751. });
  10752. }
  10753. return colors;
  10754. };
  10755. var getColorCols = function (editor, defaultCols) {
  10756. return editor.getParam('color_cols', defaultCols, 'number');
  10757. };
  10758. var hasCustomColors = function (editor) {
  10759. return editor.getParam('custom_colors') !== false;
  10760. };
  10761. var getColorMap = function (editor) {
  10762. return editor.getParam('color_map');
  10763. };
  10764. var getColors = function (editor) {
  10765. var unmapped = getColorMap(editor);
  10766. return unmapped !== undefined ? mapColors(unmapped) : defaultColors;
  10767. };
  10768. var getCurrentColors = function () {
  10769. return map(colorCache.state(), function (color) {
  10770. return {
  10771. type: choiceItem,
  10772. text: color,
  10773. value: color
  10774. };
  10775. });
  10776. };
  10777. var addColor = function (color) {
  10778. colorCache.add(color);
  10779. };
  10780. var fireSkinLoaded = function (editor) {
  10781. return editor.fire('SkinLoaded');
  10782. };
  10783. var fireSkinLoadError = function (editor, error) {
  10784. return editor.fire('SkinLoadError', error);
  10785. };
  10786. var fireResizeEditor = function (editor) {
  10787. return editor.fire('ResizeEditor');
  10788. };
  10789. var fireResizeContent = function (editor, e) {
  10790. return editor.fire('ResizeContent', e);
  10791. };
  10792. var fireScrollContent = function (editor, e) {
  10793. return editor.fire('ScrollContent', e);
  10794. };
  10795. var fireTextColorChange = function (editor, data) {
  10796. return editor.fire('TextColorChange', data);
  10797. };
  10798. var getCurrentColor = function (editor, format) {
  10799. var color;
  10800. editor.dom.getParents(editor.selection.getStart(), function (elm) {
  10801. var value;
  10802. if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) {
  10803. color = color ? color : value;
  10804. }
  10805. });
  10806. return color;
  10807. };
  10808. var applyFormat = function (editor, format, value) {
  10809. editor.undoManager.transact(function () {
  10810. editor.focus();
  10811. editor.formatter.apply(format, { value: value });
  10812. editor.nodeChanged();
  10813. });
  10814. };
  10815. var removeFormat = function (editor, format) {
  10816. editor.undoManager.transact(function () {
  10817. editor.focus();
  10818. editor.formatter.remove(format, { value: null }, null, true);
  10819. editor.nodeChanged();
  10820. });
  10821. };
  10822. var registerCommands = function (editor) {
  10823. editor.addCommand('mceApplyTextcolor', function (format, value) {
  10824. applyFormat(editor, format, value);
  10825. });
  10826. editor.addCommand('mceRemoveTextcolor', function (format) {
  10827. removeFormat(editor, format);
  10828. });
  10829. };
  10830. var calcCols = function (colors) {
  10831. return Math.max(5, Math.ceil(Math.sqrt(colors)));
  10832. };
  10833. var getColorCols$1 = function (editor) {
  10834. var colors = getColors(editor);
  10835. var defaultCols = calcCols(colors.length);
  10836. return getColorCols(editor, defaultCols);
  10837. };
  10838. var getAdditionalColors = function (hasCustom) {
  10839. var type = 'choiceitem';
  10840. var remove = {
  10841. type: type,
  10842. text: 'Remove color',
  10843. icon: 'color-swatch-remove-color',
  10844. value: 'remove'
  10845. };
  10846. var custom = {
  10847. type: type,
  10848. text: 'Custom color',
  10849. icon: 'color-picker',
  10850. value: 'custom'
  10851. };
  10852. return hasCustom ? [
  10853. remove,
  10854. custom
  10855. ] : [remove];
  10856. };
  10857. var applyColor = function (editor, format, value, onChoice) {
  10858. if (value === 'custom') {
  10859. var dialog = colorPickerDialog(editor);
  10860. dialog(function (colorOpt) {
  10861. colorOpt.each(function (color) {
  10862. addColor(color);
  10863. editor.execCommand('mceApplyTextcolor', format, color);
  10864. onChoice(color);
  10865. });
  10866. }, '#000000');
  10867. } else if (value === 'remove') {
  10868. onChoice('');
  10869. editor.execCommand('mceRemoveTextcolor', format);
  10870. } else {
  10871. onChoice(value);
  10872. editor.execCommand('mceApplyTextcolor', format, value);
  10873. }
  10874. };
  10875. var getColors$1 = function (colors, hasCustom) {
  10876. return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom)));
  10877. };
  10878. var getFetch = function (colors, hasCustom) {
  10879. return function (callback) {
  10880. callback(getColors$1(colors, hasCustom));
  10881. };
  10882. };
  10883. var setIconColor = function (splitButtonApi, name, newColor) {
  10884. var setIconFillAndStroke = function (pathId, color) {
  10885. splitButtonApi.setIconFill(pathId, color);
  10886. splitButtonApi.setIconStroke(pathId, color);
  10887. };
  10888. var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color';
  10889. setIconFillAndStroke(id, newColor);
  10890. };
  10891. var registerTextColorButton = function (editor, name, format, tooltip, lastColor) {
  10892. editor.ui.registry.addSplitButton(name, {
  10893. tooltip: tooltip,
  10894. presets: 'color',
  10895. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10896. select: function (value) {
  10897. var optCurrentRgb = Option.from(getCurrentColor(editor, format));
  10898. return optCurrentRgb.bind(function (currentRgb) {
  10899. return fromString(currentRgb).map(function (rgba) {
  10900. var currentHex = fromRgba(rgba).value;
  10901. return contains$1(value.toLowerCase(), currentHex);
  10902. });
  10903. }).getOr(false);
  10904. },
  10905. columns: getColorCols$1(editor),
  10906. fetch: getFetch(getColors(editor), hasCustomColors(editor)),
  10907. onAction: function (_splitButtonApi) {
  10908. if (lastColor.get() !== null) {
  10909. applyColor(editor, format, lastColor.get(), function () {
  10910. });
  10911. }
  10912. },
  10913. onItemAction: function (_splitButtonApi, value) {
  10914. applyColor(editor, format, value, function (newColor) {
  10915. lastColor.set(newColor);
  10916. fireTextColorChange(editor, {
  10917. name: name,
  10918. color: newColor
  10919. });
  10920. });
  10921. },
  10922. onSetup: function (splitButtonApi) {
  10923. if (lastColor.get() !== null) {
  10924. setIconColor(splitButtonApi, name, lastColor.get());
  10925. }
  10926. var handler = function (e) {
  10927. if (e.name === name) {
  10928. setIconColor(splitButtonApi, e.name, e.color);
  10929. }
  10930. };
  10931. editor.on('TextColorChange', handler);
  10932. return function () {
  10933. editor.off('TextColorChange', handler);
  10934. };
  10935. }
  10936. });
  10937. };
  10938. var registerTextColorMenuItem = function (editor, name, format, text) {
  10939. editor.ui.registry.addNestedMenuItem(name, {
  10940. text: text,
  10941. icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color',
  10942. getSubmenuItems: function () {
  10943. return [{
  10944. type: 'fancymenuitem',
  10945. fancytype: 'colorswatch',
  10946. onAction: function (data) {
  10947. applyColor(editor, format, data.value, noop);
  10948. }
  10949. }];
  10950. }
  10951. });
  10952. };
  10953. var colorPickerDialog = function (editor) {
  10954. return function (callback, value) {
  10955. var getOnSubmit = function (callback) {
  10956. return function (api) {
  10957. var data = api.getData();
  10958. callback(Option.from(data.colorpicker));
  10959. api.close();
  10960. };
  10961. };
  10962. var onAction = function (api, details) {
  10963. if (details.name === 'hex-valid') {
  10964. if (details.value) {
  10965. api.enable('ok');
  10966. } else {
  10967. api.disable('ok');
  10968. }
  10969. }
  10970. };
  10971. var initialData = { colorpicker: value };
  10972. var submit = getOnSubmit(callback);
  10973. editor.windowManager.open({
  10974. title: 'Color Picker',
  10975. size: 'normal',
  10976. body: {
  10977. type: 'panel',
  10978. items: [{
  10979. type: 'colorpicker',
  10980. name: 'colorpicker',
  10981. label: 'Color'
  10982. }]
  10983. },
  10984. buttons: [
  10985. {
  10986. type: 'cancel',
  10987. name: 'cancel',
  10988. text: 'Cancel'
  10989. },
  10990. {
  10991. type: 'submit',
  10992. name: 'save',
  10993. text: 'Save',
  10994. primary: true
  10995. }
  10996. ],
  10997. initialData: initialData,
  10998. onAction: onAction,
  10999. onSubmit: submit,
  11000. onClose: function () {
  11001. },
  11002. onCancel: function () {
  11003. callback(Option.none());
  11004. }
  11005. });
  11006. };
  11007. };
  11008. var register$1 = function (editor) {
  11009. registerCommands(editor);
  11010. var lastForeColor = Cell(null);
  11011. var lastBackColor = Cell(null);
  11012. registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor);
  11013. registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor);
  11014. registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color');
  11015. registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color');
  11016. };
  11017. var forMenu = function (presets) {
  11018. if (presets === 'color') {
  11019. return 'tox-swatches';
  11020. } else {
  11021. return 'tox-menu';
  11022. }
  11023. };
  11024. var classes = function (presets) {
  11025. return {
  11026. backgroundMenu: 'tox-background-menu',
  11027. selectedMenu: 'tox-selected-menu',
  11028. selectedItem: 'tox-collection__item--active',
  11029. hasIcons: 'tox-menu--has-icons',
  11030. menu: forMenu(presets),
  11031. tieredMenu: 'tox-tiered-menu'
  11032. };
  11033. };
  11034. var markers$1 = function (presets) {
  11035. var menuClasses = classes(presets);
  11036. return {
  11037. backgroundMenu: menuClasses.backgroundMenu,
  11038. selectedMenu: menuClasses.selectedMenu,
  11039. menu: menuClasses.menu,
  11040. selectedItem: menuClasses.selectedItem,
  11041. item: classForPreset(presets)
  11042. };
  11043. };
  11044. var dom$1 = function (hasIcons, columns, presets) {
  11045. var menuClasses = classes(presets);
  11046. return {
  11047. tag: 'div',
  11048. classes: flatten([
  11049. [
  11050. menuClasses.menu,
  11051. 'tox-menu-' + columns + '-column'
  11052. ],
  11053. hasIcons ? [menuClasses.hasIcons] : []
  11054. ])
  11055. };
  11056. };
  11057. var components$1 = [Menu.parts().items({})];
  11058. var part = function (hasIcons, columns, presets) {
  11059. var menuClasses = classes(presets);
  11060. var d = {
  11061. tag: 'div',
  11062. classes: flatten([[menuClasses.tieredMenu]])
  11063. };
  11064. return {
  11065. dom: d,
  11066. markers: markers$1(presets)
  11067. };
  11068. };
  11069. var chunk$1 = function (rowDom, numColumns) {
  11070. return function (items) {
  11071. var chunks = chunk(items, numColumns);
  11072. return map(chunks, function (c) {
  11073. return {
  11074. dom: rowDom,
  11075. components: c
  11076. };
  11077. });
  11078. };
  11079. };
  11080. var forSwatch = function (columns) {
  11081. return {
  11082. dom: {
  11083. tag: 'div',
  11084. classes: [
  11085. 'tox-menu',
  11086. 'tox-swatches-menu'
  11087. ]
  11088. },
  11089. components: [{
  11090. dom: {
  11091. tag: 'div',
  11092. classes: ['tox-swatches']
  11093. },
  11094. components: [Menu.parts().items({
  11095. preprocess: columns !== 'auto' ? chunk$1({
  11096. tag: 'div',
  11097. classes: ['tox-swatches__row']
  11098. }, columns) : identity
  11099. })]
  11100. }]
  11101. };
  11102. };
  11103. var forToolbar = function (columns) {
  11104. return {
  11105. dom: {
  11106. tag: 'div',
  11107. classes: [
  11108. 'tox-menu',
  11109. 'tox-collection',
  11110. 'tox-collection--toolbar',
  11111. 'tox-collection--toolbar-lg'
  11112. ]
  11113. },
  11114. components: [Menu.parts().items({
  11115. preprocess: chunk$1({
  11116. tag: 'div',
  11117. classes: ['tox-collection__group']
  11118. }, columns)
  11119. })]
  11120. };
  11121. };
  11122. var preprocessCollection = function (items, isSeparator) {
  11123. var allSplits = [];
  11124. var currentSplit = [];
  11125. each(items, function (item, i) {
  11126. if (isSeparator(item, i)) {
  11127. if (currentSplit.length > 0) {
  11128. allSplits.push(currentSplit);
  11129. }
  11130. currentSplit = [];
  11131. if (has(item.dom, 'innerHtml')) {
  11132. currentSplit.push(item);
  11133. }
  11134. } else {
  11135. currentSplit.push(item);
  11136. }
  11137. });
  11138. if (currentSplit.length > 0) {
  11139. allSplits.push(currentSplit);
  11140. }
  11141. return map(allSplits, function (s) {
  11142. return {
  11143. dom: {
  11144. tag: 'div',
  11145. classes: ['tox-collection__group']
  11146. },
  11147. components: s
  11148. };
  11149. });
  11150. };
  11151. var forCollection = function (columns, initItems, _hasIcons) {
  11152. return {
  11153. dom: {
  11154. tag: 'div',
  11155. classes: [
  11156. 'tox-menu',
  11157. 'tox-collection'
  11158. ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid'])
  11159. },
  11160. components: [Menu.parts().items({
  11161. preprocess: function (items) {
  11162. if (columns !== 'auto' && columns > 1) {
  11163. return chunk$1({
  11164. tag: 'div',
  11165. classes: ['tox-collection__group']
  11166. }, columns)(items);
  11167. } else {
  11168. return preprocessCollection(items, function (_item, i) {
  11169. return initItems[i].type === 'separator';
  11170. });
  11171. }
  11172. }
  11173. })]
  11174. };
  11175. };
  11176. var forHorizontalCollection = function (initItems, _hasIcons) {
  11177. return {
  11178. dom: {
  11179. tag: 'div',
  11180. classes: [
  11181. 'tox-collection',
  11182. 'tox-collection--horizontal'
  11183. ]
  11184. },
  11185. components: [Menu.parts().items({
  11186. preprocess: function (items) {
  11187. return preprocessCollection(items, function (_item, i) {
  11188. return initItems[i].type === 'separator';
  11189. });
  11190. }
  11191. })]
  11192. };
  11193. };
  11194. var menuHasIcons = function (xs) {
  11195. return exists(xs, function (item) {
  11196. return 'icon' in item && item.icon !== undefined;
  11197. });
  11198. };
  11199. var handleError = function (error) {
  11200. domGlobals.console.error(formatError(error));
  11201. domGlobals.console.log(error);
  11202. return Option.none();
  11203. };
  11204. var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) {
  11205. var structure = forHorizontalCollection(items);
  11206. return {
  11207. value: value,
  11208. dom: structure.dom,
  11209. components: structure.components,
  11210. items: items
  11211. };
  11212. };
  11213. var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) {
  11214. if (presets === 'color') {
  11215. var structure = forSwatch(columns);
  11216. return {
  11217. value: value,
  11218. dom: structure.dom,
  11219. components: structure.components,
  11220. items: items
  11221. };
  11222. }
  11223. if (presets === 'normal' && columns === 'auto') {
  11224. var structure = forCollection(columns, items);
  11225. return {
  11226. value: value,
  11227. dom: structure.dom,
  11228. components: structure.components,
  11229. items: items
  11230. };
  11231. }
  11232. if (presets === 'normal' && columns === 1) {
  11233. var structure = forCollection(1, items);
  11234. return {
  11235. value: value,
  11236. dom: structure.dom,
  11237. components: structure.components,
  11238. items: items
  11239. };
  11240. }
  11241. if (presets === 'normal') {
  11242. var structure = forCollection(columns, items);
  11243. return {
  11244. value: value,
  11245. dom: structure.dom,
  11246. components: structure.components,
  11247. items: items
  11248. };
  11249. }
  11250. if (presets === 'listpreview' && columns !== 'auto') {
  11251. var structure = forToolbar(columns);
  11252. return {
  11253. value: value,
  11254. dom: structure.dom,
  11255. components: structure.components,
  11256. items: items
  11257. };
  11258. }
  11259. return {
  11260. value: value,
  11261. dom: dom$1(hasIcons, columns, presets),
  11262. components: components$1,
  11263. items: items
  11264. };
  11265. };
  11266. var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) {
  11267. var hasIcons = menuHasIcons(items);
  11268. var presetItemTypes = presets !== 'color' ? 'normal' : 'color';
  11269. var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage);
  11270. return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets);
  11271. };
  11272. var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) {
  11273. return cat(map(items, function (item) {
  11274. if (item.type === 'choiceitem') {
  11275. return createChoiceMenuItem(item).fold(handleError, function (d) {
  11276. return Option.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items)));
  11277. });
  11278. } else {
  11279. return Option.none();
  11280. }
  11281. }));
  11282. };
  11283. var deriveMenuMovement = function (columns, presets) {
  11284. var menuMarkers = markers$1(presets);
  11285. if (columns === 1) {
  11286. return {
  11287. mode: 'menu',
  11288. moveOnTab: true
  11289. };
  11290. } else if (columns === 'auto') {
  11291. return {
  11292. mode: 'grid',
  11293. selector: '.' + menuMarkers.item,
  11294. initSize: {
  11295. numColumns: 1,
  11296. numRows: 1
  11297. }
  11298. };
  11299. } else {
  11300. var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group';
  11301. return {
  11302. mode: 'matrix',
  11303. rowSelector: '.' + rowClass
  11304. };
  11305. }
  11306. };
  11307. var deriveCollectionMovement = function (columns, presets) {
  11308. if (columns === 1) {
  11309. return {
  11310. mode: 'menu',
  11311. moveOnTab: false,
  11312. selector: '.tox-collection__item'
  11313. };
  11314. } else if (columns === 'auto') {
  11315. return {
  11316. mode: 'flatgrid',
  11317. selector: '.' + 'tox-collection__item',
  11318. initSize: {
  11319. numColumns: 1,
  11320. numRows: 1
  11321. }
  11322. };
  11323. } else {
  11324. return {
  11325. mode: 'matrix',
  11326. selectors: {
  11327. row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group',
  11328. cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass
  11329. }
  11330. };
  11331. }
  11332. };
  11333. function renderColorSwatchItem(spec, backstage) {
  11334. var items = getColors$1(backstage.colorinput.getColors(), backstage.colorinput.hasCustomColors());
  11335. var columns = backstage.colorinput.getColorCols();
  11336. var presets = 'color';
  11337. var menuSpec = createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  11338. spec.onAction({ value: value });
  11339. }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  11340. return false;
  11341. }, backstage.shared.providers);
  11342. var widgetSpec = __assign(__assign({}, menuSpec), {
  11343. markers: markers$1(presets),
  11344. movement: deriveMenuMovement(columns, presets)
  11345. });
  11346. return {
  11347. type: 'widget',
  11348. data: { value: generate$1('widget-id') },
  11349. dom: {
  11350. tag: 'div',
  11351. classes: ['tox-fancymenuitem']
  11352. },
  11353. autofocus: true,
  11354. components: [parts$2().widget(Menu.sketch(widgetSpec))]
  11355. };
  11356. }
  11357. var fancyMenuItems = {
  11358. inserttable: renderInsertTableMenuItem,
  11359. colorswatch: renderColorSwatchItem
  11360. };
  11361. var valueOpt = function (obj, key) {
  11362. return Object.prototype.hasOwnProperty.call(obj, key) ? Option.some(obj[key]) : Option.none();
  11363. };
  11364. var renderFancyMenuItem = function (spec, backstage) {
  11365. return valueOpt(fancyMenuItems, spec.fancytype).map(function (render) {
  11366. return render(spec, backstage);
  11367. });
  11368. };
  11369. var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11370. if (renderIcons === void 0) {
  11371. renderIcons = true;
  11372. }
  11373. var getApi = function (component) {
  11374. return {
  11375. isDisabled: function () {
  11376. return Disabling.isDisabled(component);
  11377. },
  11378. setDisabled: function (state) {
  11379. return Disabling.set(component, state);
  11380. }
  11381. };
  11382. };
  11383. var structure = renderItemStructure({
  11384. presets: 'normal',
  11385. iconContent: spec.icon,
  11386. textContent: spec.text,
  11387. htmlContent: Option.none(),
  11388. ariaLabel: spec.text,
  11389. caret: Option.none(),
  11390. checkMark: Option.none(),
  11391. shortcutContent: spec.shortcut
  11392. }, providersBackstage, renderIcons);
  11393. return renderCommonItem({
  11394. data: buildData(spec),
  11395. getApi: getApi,
  11396. disabled: spec.disabled,
  11397. onAction: spec.onAction,
  11398. onSetup: spec.onSetup,
  11399. triggersSubmenu: false,
  11400. itemBehaviours: []
  11401. }, structure, itemResponse, providersBackstage);
  11402. };
  11403. var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) {
  11404. if (renderIcons === void 0) {
  11405. renderIcons = true;
  11406. }
  11407. if (downwardsCaret === void 0) {
  11408. downwardsCaret = false;
  11409. }
  11410. var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons);
  11411. var getApi = function (component) {
  11412. return {
  11413. isDisabled: function () {
  11414. return Disabling.isDisabled(component);
  11415. },
  11416. setDisabled: function (state) {
  11417. return Disabling.set(component, state);
  11418. }
  11419. };
  11420. };
  11421. var structure = renderItemStructure({
  11422. presets: 'normal',
  11423. iconContent: spec.icon,
  11424. textContent: spec.text,
  11425. htmlContent: Option.none(),
  11426. ariaLabel: spec.text,
  11427. caret: Option.some(caret),
  11428. checkMark: Option.none(),
  11429. shortcutContent: spec.shortcut
  11430. }, providersBackstage, renderIcons);
  11431. return renderCommonItem({
  11432. data: buildData(spec),
  11433. getApi: getApi,
  11434. disabled: spec.disabled,
  11435. onAction: noop,
  11436. onSetup: spec.onSetup,
  11437. triggersSubmenu: true,
  11438. itemBehaviours: []
  11439. }, structure, itemResponse, providersBackstage);
  11440. };
  11441. var renderSeparatorItem = function (spec) {
  11442. var innerHtml = spec.text.fold(function () {
  11443. return {};
  11444. }, function (text) {
  11445. return { innerHtml: text };
  11446. });
  11447. return {
  11448. type: 'separator',
  11449. dom: __assign({
  11450. tag: 'div',
  11451. classes: [
  11452. selectableClass,
  11453. groupHeadingClass
  11454. ]
  11455. }, innerHtml),
  11456. components: []
  11457. };
  11458. };
  11459. var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) {
  11460. if (renderIcons === void 0) {
  11461. renderIcons = true;
  11462. }
  11463. var getApi = function (component) {
  11464. return {
  11465. setActive: function (state) {
  11466. Toggling.set(component, state);
  11467. },
  11468. isActive: function () {
  11469. return Toggling.isOn(component);
  11470. },
  11471. isDisabled: function () {
  11472. return Disabling.isDisabled(component);
  11473. },
  11474. setDisabled: function (state) {
  11475. return Disabling.set(component, state);
  11476. }
  11477. };
  11478. };
  11479. var structure = renderItemStructure({
  11480. iconContent: spec.icon,
  11481. textContent: spec.text,
  11482. htmlContent: Option.none(),
  11483. ariaLabel: spec.text,
  11484. checkMark: Option.some(renderCheckmark(providersBackstage.icons)),
  11485. caret: Option.none(),
  11486. shortcutContent: spec.shortcut,
  11487. presets: 'normal',
  11488. meta: spec.meta
  11489. }, providersBackstage, renderIcons);
  11490. return deepMerge(renderCommonItem({
  11491. data: buildData(spec),
  11492. disabled: spec.disabled,
  11493. getApi: getApi,
  11494. onAction: spec.onAction,
  11495. onSetup: spec.onSetup,
  11496. triggersSubmenu: false,
  11497. itemBehaviours: []
  11498. }, structure, itemResponse, providersBackstage), {
  11499. toggling: {
  11500. toggleClass: tickedClass,
  11501. toggleOnExecute: false,
  11502. selected: spec.active
  11503. }
  11504. });
  11505. };
  11506. var autocomplete = renderAutocompleteItem;
  11507. var separator = renderSeparatorItem;
  11508. var normal = renderNormalItem;
  11509. var nested = renderNestedItem;
  11510. var toggle$1 = renderToggleMenuItem;
  11511. var fancy = renderFancyMenuItem;
  11512. var FocusMode;
  11513. (function (FocusMode) {
  11514. FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus';
  11515. FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus';
  11516. }(FocusMode || (FocusMode = {})));
  11517. var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) {
  11518. var providersBackstage = backstage.shared.providers;
  11519. var parseForHorizontalMenu = function (menuitem) {
  11520. return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), {
  11521. shortcut: Option.none(),
  11522. icon: menuitem.text.isSome() ? Option.none() : menuitem.icon
  11523. });
  11524. };
  11525. switch (item.type) {
  11526. case 'menuitem':
  11527. return createMenuItem(item).fold(handleError, function (d) {
  11528. return Option.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11529. });
  11530. case 'nestedmenuitem':
  11531. return createNestedMenuItem(item).fold(handleError, function (d) {
  11532. return Option.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu));
  11533. });
  11534. case 'togglemenuitem':
  11535. return createToggleMenuItem(item).fold(handleError, function (d) {
  11536. return Option.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons));
  11537. });
  11538. case 'separator':
  11539. return createSeparatorMenuItem(item).fold(handleError, function (d) {
  11540. return Option.some(separator(d));
  11541. });
  11542. case 'fancymenuitem':
  11543. return createFancyMenuItem(item).fold(handleError, function (d) {
  11544. return fancy(parseForHorizontalMenu(d), backstage);
  11545. });
  11546. default: {
  11547. domGlobals.console.error('Unknown item in general menu', item);
  11548. return Option.none();
  11549. }
  11550. }
  11551. };
  11552. var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage) {
  11553. var renderText = columns === 1;
  11554. var renderIcons = !renderText || menuHasIcons(items);
  11555. return cat(map(items, function (item) {
  11556. if (item.type === 'separator') {
  11557. return createSeparatorItem(item).fold(handleError, function (d) {
  11558. return Option.some(separator(d));
  11559. });
  11560. } else {
  11561. return createAutocompleterItem(item).fold(handleError, function (d) {
  11562. return Option.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons));
  11563. });
  11564. }
  11565. }));
  11566. };
  11567. var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) {
  11568. var hasIcons = menuHasIcons(items);
  11569. var alloyItems = cat(map(items, function (item) {
  11570. var itemHasIcon = function (i) {
  11571. return isHorizontalMenu ? !i.hasOwnProperty('text') : hasIcons;
  11572. };
  11573. var createItem = function (i) {
  11574. return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu);
  11575. };
  11576. if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) {
  11577. return createItem(__assign(__assign({}, item), { disabled: true }));
  11578. } else {
  11579. return createItem(item);
  11580. }
  11581. }));
  11582. var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems;
  11583. return createPartial(value, hasIcons, alloyItems, 1, 'normal');
  11584. };
  11585. var createTieredDataFrom = function (partialMenu) {
  11586. return tieredMenu.singleData(partialMenu.value, partialMenu);
  11587. };
  11588. var createMenuFrom = function (partialMenu, columns, focusMode, presets) {
  11589. var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom();
  11590. var movement = deriveMenuMovement(columns, presets);
  11591. var menuMarkers = markers$1(presets);
  11592. return {
  11593. dom: partialMenu.dom,
  11594. components: partialMenu.components,
  11595. items: partialMenu.items,
  11596. value: partialMenu.value,
  11597. markers: {
  11598. selectedItem: menuMarkers.selectedItem,
  11599. item: menuMarkers.item
  11600. },
  11601. movement: movement,
  11602. fakeFocus: focusMode === FocusMode.ContentFocus,
  11603. focusManager: focusManager,
  11604. menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  11605. detectSize(comp, 4, menuMarkers.item).each(function (_a) {
  11606. var numColumns = _a.numColumns, numRows = _a.numRows;
  11607. Keying.setGridSize(comp, numRows, numColumns);
  11608. });
  11609. })])
  11610. };
  11611. };
  11612. var register$2 = function (editor, sharedBackstage) {
  11613. var activeAutocompleter = Cell(Option.none());
  11614. var processingAction = Cell(false);
  11615. var autocompleter = build$1(InlineView.sketch({
  11616. dom: {
  11617. tag: 'div',
  11618. classes: ['tox-autocompleter']
  11619. },
  11620. components: [],
  11621. fireDismissalEventInstead: {},
  11622. inlineBehaviours: derive$1([config('dismissAutocompleter', [run(dismissRequested(), function () {
  11623. return cancelIfNecessary();
  11624. })])]),
  11625. lazySink: sharedBackstage.getSink
  11626. }));
  11627. var isMenuOpen = function () {
  11628. return InlineView.isOpen(autocompleter);
  11629. };
  11630. var isActive = function () {
  11631. return activeAutocompleter.get().isSome();
  11632. };
  11633. var hideIfNecessary = function () {
  11634. if (isActive()) {
  11635. InlineView.hide(autocompleter);
  11636. }
  11637. };
  11638. var cancelIfNecessary = function () {
  11639. if (isActive()) {
  11640. var lastElement = activeAutocompleter.get().map(function (ac) {
  11641. return ac.element;
  11642. });
  11643. detect$4(lastElement.getOr(Element.fromDom(editor.selection.getNode()))).each(unwrap);
  11644. hideIfNecessary();
  11645. activeAutocompleter.set(Option.none());
  11646. processingAction.set(false);
  11647. }
  11648. };
  11649. var getAutocompleters = cached(function () {
  11650. return register(editor);
  11651. });
  11652. var getCombinedItems = function (triggerChar, matches) {
  11653. var columns = findMap(matches, function (m) {
  11654. return Option.from(m.columns);
  11655. }).getOr(1);
  11656. return bind(matches, function (match) {
  11657. var choices = match.items;
  11658. return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) {
  11659. var nr = editor.selection.getRng();
  11660. getContext(editor.dom, nr, triggerChar).fold(function () {
  11661. return domGlobals.console.error('Lost context. Cursor probably moved');
  11662. }, function (_a) {
  11663. var range = _a.range;
  11664. var autocompleterApi = {
  11665. hide: function () {
  11666. cancelIfNecessary();
  11667. },
  11668. reload: function (fetchOptions) {
  11669. hideIfNecessary();
  11670. load(fetchOptions);
  11671. }
  11672. };
  11673. processingAction.set(true);
  11674. match.onAction(autocompleterApi, range, itemValue, itemMeta);
  11675. processingAction.set(false);
  11676. });
  11677. }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage);
  11678. });
  11679. };
  11680. var commenceIfNecessary = function (context) {
  11681. if (!isActive()) {
  11682. var wrapper = create$4(editor, context.range);
  11683. activeAutocompleter.set(Option.some({
  11684. triggerChar: context.triggerChar,
  11685. element: wrapper,
  11686. matchLength: context.text.length
  11687. }));
  11688. processingAction.set(false);
  11689. }
  11690. };
  11691. var display = function (ac, context, lookupData, items) {
  11692. ac.matchLength = context.text.length;
  11693. var columns = findMap(lookupData, function (ld) {
  11694. return Option.from(ld.columns);
  11695. }).getOr(1);
  11696. InlineView.showAt(autocompleter, {
  11697. anchor: 'node',
  11698. root: Element.fromDom(editor.getBody()),
  11699. node: Option.from(ac.element)
  11700. }, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')));
  11701. InlineView.getContent(autocompleter).each(Highlighting.highlightFirst);
  11702. };
  11703. var doLookup = function (fetchOptions) {
  11704. return activeAutocompleter.get().map(function (ac) {
  11705. return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) {
  11706. return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions);
  11707. });
  11708. }).getOrThunk(function () {
  11709. return lookup(editor, getAutocompleters);
  11710. });
  11711. };
  11712. var load = function (fetchOptions) {
  11713. doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) {
  11714. commenceIfNecessary(lookupInfo.context);
  11715. lookupInfo.lookupData.then(function (lookupData) {
  11716. activeAutocompleter.get().map(function (ac) {
  11717. var context = lookupInfo.context;
  11718. if (ac.triggerChar === context.triggerChar) {
  11719. var combinedItems = getCombinedItems(context.triggerChar, lookupData);
  11720. if (combinedItems.length > 0) {
  11721. display(ac, context, lookupData, combinedItems);
  11722. } else if (context.text.length - ac.matchLength >= 10) {
  11723. cancelIfNecessary();
  11724. } else {
  11725. hideIfNecessary();
  11726. }
  11727. }
  11728. });
  11729. });
  11730. });
  11731. };
  11732. var onKeypress = last$2(function (e) {
  11733. if (e.which === 27) {
  11734. return;
  11735. }
  11736. load();
  11737. }, 50);
  11738. var autocompleterUiApi = {
  11739. onKeypress: onKeypress,
  11740. cancelIfNecessary: cancelIfNecessary,
  11741. isMenuOpen: isMenuOpen,
  11742. isActive: isActive,
  11743. isProcessingAction: processingAction.get,
  11744. getView: function () {
  11745. return InlineView.getContent(autocompleter);
  11746. }
  11747. };
  11748. AutocompleterEditorEvents.setup(autocompleterUiApi, editor);
  11749. };
  11750. var Autocompleter = { register: register$2 };
  11751. var filter$2 = constant(true);
  11752. var bind$3 = function (element, event, handler) {
  11753. return bind$2(element, event, filter$2, handler);
  11754. };
  11755. var capture$1 = function (element, event, handler) {
  11756. return capture(element, event, filter$2, handler);
  11757. };
  11758. var fromRawEvent$1 = fromRawEvent;
  11759. var closest$4 = function (scope, selector, isRoot) {
  11760. return closest$3(scope, selector, isRoot).isSome();
  11761. };
  11762. function DelayedFunction (fun, delay) {
  11763. var ref = null;
  11764. var schedule = function () {
  11765. var args = [];
  11766. for (var _i = 0; _i < arguments.length; _i++) {
  11767. args[_i] = arguments[_i];
  11768. }
  11769. ref = domGlobals.setTimeout(function () {
  11770. fun.apply(null, args);
  11771. ref = null;
  11772. }, delay);
  11773. };
  11774. var cancel = function () {
  11775. if (ref !== null) {
  11776. domGlobals.clearTimeout(ref);
  11777. ref = null;
  11778. }
  11779. };
  11780. return {
  11781. cancel: cancel,
  11782. schedule: schedule
  11783. };
  11784. }
  11785. var SIGNIFICANT_MOVE = 5;
  11786. var LONGPRESS_DELAY = 400;
  11787. var getTouch = function (event) {
  11788. var raw = event.raw();
  11789. if (raw.touches === undefined || raw.touches.length !== 1) {
  11790. return Option.none();
  11791. }
  11792. return Option.some(raw.touches[0]);
  11793. };
  11794. var isFarEnough = function (touch, data) {
  11795. var distX = Math.abs(touch.clientX - data.x);
  11796. var distY = Math.abs(touch.clientY - data.y);
  11797. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  11798. };
  11799. var monitor = function (settings) {
  11800. var startData = Cell(Option.none());
  11801. var longpressFired = Cell(false);
  11802. var longpress$1 = DelayedFunction(function (event) {
  11803. settings.triggerEvent(longpress(), event);
  11804. longpressFired.set(true);
  11805. }, LONGPRESS_DELAY);
  11806. var handleTouchstart = function (event) {
  11807. getTouch(event).each(function (touch) {
  11808. longpress$1.cancel();
  11809. var data = {
  11810. x: touch.clientX,
  11811. y: touch.clientY,
  11812. target: event.target()
  11813. };
  11814. longpress$1.schedule(event);
  11815. longpressFired.set(false);
  11816. startData.set(Option.some(data));
  11817. });
  11818. return Option.none();
  11819. };
  11820. var handleTouchmove = function (event) {
  11821. longpress$1.cancel();
  11822. getTouch(event).each(function (touch) {
  11823. startData.get().each(function (data) {
  11824. if (isFarEnough(touch, data)) {
  11825. startData.set(Option.none());
  11826. }
  11827. });
  11828. });
  11829. return Option.none();
  11830. };
  11831. var handleTouchend = function (event) {
  11832. longpress$1.cancel();
  11833. var isSame = function (data) {
  11834. return eq$1(data.target, event.target());
  11835. };
  11836. return startData.get().filter(isSame).map(function (_data) {
  11837. if (longpressFired.get()) {
  11838. event.prevent();
  11839. return false;
  11840. } else {
  11841. return settings.triggerEvent(tap(), event);
  11842. }
  11843. });
  11844. };
  11845. var handlers = wrapAll$1([
  11846. {
  11847. key: touchstart(),
  11848. value: handleTouchstart
  11849. },
  11850. {
  11851. key: touchmove(),
  11852. value: handleTouchmove
  11853. },
  11854. {
  11855. key: touchend(),
  11856. value: handleTouchend
  11857. }
  11858. ]);
  11859. var fireIfReady = function (event, type) {
  11860. return get(handlers, type).bind(function (handler) {
  11861. return handler(event);
  11862. });
  11863. };
  11864. return { fireIfReady: fireIfReady };
  11865. };
  11866. var isDangerous = function (event) {
  11867. var keyEv = event.raw();
  11868. return keyEv.which === BACKSPACE()[0] && !contains([
  11869. 'input',
  11870. 'textarea'
  11871. ], name(event.target())) && !closest$4(event.target(), '[contenteditable="true"]');
  11872. };
  11873. var isFirefox = function () {
  11874. return detect$3().browser.isFirefox();
  11875. };
  11876. var settingsSchema = objOfOnly([
  11877. strictFunction('triggerEvent'),
  11878. defaulted$1('stopBackspace', true)
  11879. ]);
  11880. var bindFocus = function (container, handler) {
  11881. if (isFirefox()) {
  11882. return capture$1(container, 'focus', handler);
  11883. } else {
  11884. return bind$3(container, 'focusin', handler);
  11885. }
  11886. };
  11887. var bindBlur = function (container, handler) {
  11888. if (isFirefox()) {
  11889. return capture$1(container, 'blur', handler);
  11890. } else {
  11891. return bind$3(container, 'focusout', handler);
  11892. }
  11893. };
  11894. var setup$1 = function (container, rawSettings) {
  11895. var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
  11896. var pointerEvents = [
  11897. 'touchstart',
  11898. 'touchmove',
  11899. 'touchend',
  11900. 'touchcancel',
  11901. 'gesturestart',
  11902. 'mousedown',
  11903. 'mouseup',
  11904. 'mouseover',
  11905. 'mousemove',
  11906. 'mouseout',
  11907. 'click'
  11908. ];
  11909. var tapEvent = monitor(settings);
  11910. var simpleEvents = map(pointerEvents.concat([
  11911. 'selectstart',
  11912. 'input',
  11913. 'contextmenu',
  11914. 'change',
  11915. 'transitionend',
  11916. 'drag',
  11917. 'dragstart',
  11918. 'dragend',
  11919. 'dragenter',
  11920. 'dragleave',
  11921. 'dragover',
  11922. 'drop',
  11923. 'keyup'
  11924. ]), function (type) {
  11925. return bind$3(container, type, function (event) {
  11926. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  11927. if (tapStopped) {
  11928. event.kill();
  11929. }
  11930. });
  11931. var stopped = settings.triggerEvent(type, event);
  11932. if (stopped) {
  11933. event.kill();
  11934. }
  11935. });
  11936. });
  11937. var pasteTimeout = Cell(Option.none());
  11938. var onPaste = bind$3(container, 'paste', function (event) {
  11939. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11940. if (tapStopped) {
  11941. event.kill();
  11942. }
  11943. });
  11944. var stopped = settings.triggerEvent('paste', event);
  11945. if (stopped) {
  11946. event.kill();
  11947. }
  11948. pasteTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11949. settings.triggerEvent(postPaste(), event);
  11950. }, 0)));
  11951. });
  11952. var onKeydown = bind$3(container, 'keydown', function (event) {
  11953. var stopped = settings.triggerEvent('keydown', event);
  11954. if (stopped) {
  11955. event.kill();
  11956. } else if (settings.stopBackspace === true && isDangerous(event)) {
  11957. event.prevent();
  11958. }
  11959. });
  11960. var onFocusIn = bindFocus(container, function (event) {
  11961. var stopped = settings.triggerEvent('focusin', event);
  11962. if (stopped) {
  11963. event.kill();
  11964. }
  11965. });
  11966. var focusoutTimeout = Cell(Option.none());
  11967. var onFocusOut = bindBlur(container, function (event) {
  11968. var stopped = settings.triggerEvent('focusout', event);
  11969. if (stopped) {
  11970. event.kill();
  11971. }
  11972. focusoutTimeout.set(Option.some(domGlobals.setTimeout(function () {
  11973. settings.triggerEvent(postBlur(), event);
  11974. }, 0)));
  11975. });
  11976. var unbind = function () {
  11977. each(simpleEvents, function (e) {
  11978. e.unbind();
  11979. });
  11980. onKeydown.unbind();
  11981. onFocusIn.unbind();
  11982. onFocusOut.unbind();
  11983. onPaste.unbind();
  11984. pasteTimeout.get().each(domGlobals.clearTimeout);
  11985. focusoutTimeout.get().each(domGlobals.clearTimeout);
  11986. };
  11987. return { unbind: unbind };
  11988. };
  11989. var derive$2 = function (rawEvent, rawTarget) {
  11990. var source = get(rawEvent, 'target').map(function (getTarget) {
  11991. return getTarget();
  11992. }).getOr(rawTarget);
  11993. return Cell(source);
  11994. };
  11995. var fromSource = function (event, source) {
  11996. var stopper = Cell(false);
  11997. var cutter = Cell(false);
  11998. var stop = function () {
  11999. stopper.set(true);
  12000. };
  12001. var cut = function () {
  12002. cutter.set(true);
  12003. };
  12004. return {
  12005. stop: stop,
  12006. cut: cut,
  12007. isStopped: stopper.get,
  12008. isCut: cutter.get,
  12009. event: constant(event),
  12010. setSource: source.set,
  12011. getSource: source.get
  12012. };
  12013. };
  12014. var fromExternal = function (event) {
  12015. var stopper = Cell(false);
  12016. var stop = function () {
  12017. stopper.set(true);
  12018. };
  12019. return {
  12020. stop: stop,
  12021. cut: noop,
  12022. isStopped: stopper.get,
  12023. isCut: constant(false),
  12024. event: constant(event),
  12025. setSource: die('Cannot set source of a broadcasted event'),
  12026. getSource: die('Cannot get source of a broadcasted event')
  12027. };
  12028. };
  12029. var adt$b = Adt.generate([
  12030. { stopped: [] },
  12031. { resume: ['element'] },
  12032. { complete: [] }
  12033. ]);
  12034. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  12035. var handler = lookup(eventType, target);
  12036. var simulatedEvent = fromSource(rawEvent, source);
  12037. return handler.fold(function () {
  12038. logger.logEventNoHandlers(eventType, target);
  12039. return adt$b.complete();
  12040. }, function (handlerInfo) {
  12041. var descHandler = handlerInfo.descHandler;
  12042. var eventHandler = getCurried(descHandler);
  12043. eventHandler(simulatedEvent);
  12044. if (simulatedEvent.isStopped()) {
  12045. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose());
  12046. return adt$b.stopped();
  12047. } else if (simulatedEvent.isCut()) {
  12048. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose());
  12049. return adt$b.complete();
  12050. } else {
  12051. return parent(handlerInfo.element).fold(function () {
  12052. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose());
  12053. return adt$b.complete();
  12054. }, function (parent) {
  12055. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose());
  12056. return adt$b.resume(parent);
  12057. });
  12058. }
  12059. });
  12060. };
  12061. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  12062. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
  12063. return true;
  12064. }, function (parent) {
  12065. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  12066. }, function () {
  12067. return false;
  12068. });
  12069. };
  12070. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  12071. var source = derive$2(rawEvent, target);
  12072. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  12073. };
  12074. var broadcast = function (listeners, rawEvent, _logger) {
  12075. var simulatedEvent = fromExternal(rawEvent);
  12076. each(listeners, function (listener) {
  12077. var descHandler = listener.descHandler();
  12078. var handler = getCurried(descHandler);
  12079. handler(simulatedEvent);
  12080. });
  12081. return simulatedEvent.isStopped();
  12082. };
  12083. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  12084. var rawTarget = rawEvent.target();
  12085. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
  12086. };
  12087. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  12088. var source = derive$2(rawEvent, rawTarget);
  12089. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  12090. };
  12091. var eventHandler = function (element, descHandler) {
  12092. return {
  12093. element: element,
  12094. descHandler: descHandler
  12095. };
  12096. };
  12097. var broadcastHandler = function (id, handler) {
  12098. return {
  12099. id: constant(id),
  12100. descHandler: constant(handler)
  12101. };
  12102. };
  12103. function EventRegistry () {
  12104. var registry = {};
  12105. var registerId = function (extraArgs, id, events) {
  12106. each$1(events, function (v, k) {
  12107. var handlers = registry[k] !== undefined ? registry[k] : {};
  12108. handlers[id] = curryArgs(v, extraArgs);
  12109. registry[k] = handlers;
  12110. });
  12111. };
  12112. var findHandler = function (handlers, elem) {
  12113. return read$1(elem).fold(function () {
  12114. return Option.none();
  12115. }, function (id) {
  12116. return handlers.bind(function (h) {
  12117. return get(h, id);
  12118. }).map(function (descHandler) {
  12119. return eventHandler(elem, descHandler);
  12120. });
  12121. });
  12122. };
  12123. var filterByType = function (type) {
  12124. return get(registry, type).map(function (handlers) {
  12125. return mapToArray(handlers, function (f, id) {
  12126. return broadcastHandler(id, f);
  12127. });
  12128. }).getOr([]);
  12129. };
  12130. var find = function (isAboveRoot, type, target) {
  12131. var handlers = get(registry, type);
  12132. return closest(target, function (elem) {
  12133. return findHandler(handlers, elem);
  12134. }, isAboveRoot);
  12135. };
  12136. var unregisterId = function (id) {
  12137. each$1(registry, function (handlersById, _eventName) {
  12138. if (handlersById.hasOwnProperty(id)) {
  12139. delete handlersById[id];
  12140. }
  12141. });
  12142. };
  12143. return {
  12144. registerId: registerId,
  12145. unregisterId: unregisterId,
  12146. filterByType: filterByType,
  12147. find: find
  12148. };
  12149. }
  12150. function Registry () {
  12151. var events = EventRegistry();
  12152. var components = {};
  12153. var readOrTag = function (component) {
  12154. var elem = component.element();
  12155. return read$1(elem).fold(function () {
  12156. return write('uid-', component.element());
  12157. }, function (uid) {
  12158. return uid;
  12159. });
  12160. };
  12161. var failOnDuplicate = function (component, tagId) {
  12162. var conflict = components[tagId];
  12163. if (conflict === component) {
  12164. unregister(component);
  12165. } else {
  12166. 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');
  12167. }
  12168. };
  12169. var register = function (component) {
  12170. var tagId = readOrTag(component);
  12171. if (hasNonNullableKey(components, tagId)) {
  12172. failOnDuplicate(component, tagId);
  12173. }
  12174. var extraArgs = [component];
  12175. events.registerId(extraArgs, tagId, component.events());
  12176. components[tagId] = component;
  12177. };
  12178. var unregister = function (component) {
  12179. read$1(component.element()).each(function (tagId) {
  12180. delete components[tagId];
  12181. events.unregisterId(tagId);
  12182. });
  12183. };
  12184. var filter = function (type) {
  12185. return events.filterByType(type);
  12186. };
  12187. var find = function (isAboveRoot, type, target) {
  12188. return events.find(isAboveRoot, type, target);
  12189. };
  12190. var getById = function (id) {
  12191. return get(components, id);
  12192. };
  12193. return {
  12194. find: find,
  12195. filter: filter,
  12196. register: register,
  12197. unregister: unregister,
  12198. getById: getById
  12199. };
  12200. }
  12201. var factory$3 = function (detail) {
  12202. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  12203. return {
  12204. uid: detail.uid,
  12205. dom: __assign({
  12206. tag: 'div',
  12207. attributes: __assign({ role: 'presentation' }, attributes)
  12208. }, domWithoutAttributes),
  12209. components: detail.components,
  12210. behaviours: get$c(detail.containerBehaviours),
  12211. events: detail.events,
  12212. domModification: detail.domModification,
  12213. eventOrder: detail.eventOrder
  12214. };
  12215. };
  12216. var Container = single$2({
  12217. name: 'Container',
  12218. factory: factory$3,
  12219. configFields: [
  12220. defaulted$1('components', []),
  12221. field$1('containerBehaviours', []),
  12222. defaulted$1('events', {}),
  12223. defaulted$1('domModification', {}),
  12224. defaulted$1('eventOrder', {})
  12225. ]
  12226. });
  12227. var takeover = function (root) {
  12228. var isAboveRoot = function (el) {
  12229. return parent(root.element()).fold(function () {
  12230. return true;
  12231. }, function (parent) {
  12232. return eq$1(el, parent);
  12233. });
  12234. };
  12235. var registry = Registry();
  12236. var lookup = function (eventName, target) {
  12237. return registry.find(isAboveRoot, eventName, target);
  12238. };
  12239. var domEvents = setup$1(root.element(), {
  12240. triggerEvent: function (eventName, event) {
  12241. return monitorEvent(eventName, event.target(), function (logger) {
  12242. return triggerUntilStopped(lookup, eventName, event, logger);
  12243. });
  12244. }
  12245. });
  12246. var systemApi = {
  12247. debugInfo: constant('real'),
  12248. triggerEvent: function (eventName, target, data) {
  12249. monitorEvent(eventName, target, function (logger) {
  12250. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  12251. });
  12252. },
  12253. triggerFocus: function (target, originator) {
  12254. read$1(target).fold(function () {
  12255. focus$1(target);
  12256. }, function (_alloyId) {
  12257. monitorEvent(focus(), target, function (logger) {
  12258. triggerHandler(lookup, focus(), {
  12259. originator: constant(originator),
  12260. kill: noop,
  12261. prevent: noop,
  12262. target: constant(target)
  12263. }, target, logger);
  12264. return false;
  12265. });
  12266. });
  12267. },
  12268. triggerEscape: function (comp, simulatedEvent) {
  12269. systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
  12270. },
  12271. getByUid: function (uid) {
  12272. return getByUid(uid);
  12273. },
  12274. getByDom: function (elem) {
  12275. return getByDom(elem);
  12276. },
  12277. build: build$1,
  12278. addToGui: function (c) {
  12279. add(c);
  12280. },
  12281. removeFromGui: function (c) {
  12282. remove$1(c);
  12283. },
  12284. addToWorld: function (c) {
  12285. addToWorld(c);
  12286. },
  12287. removeFromWorld: function (c) {
  12288. removeFromWorld(c);
  12289. },
  12290. broadcast: function (message) {
  12291. broadcast$1(message);
  12292. },
  12293. broadcastOn: function (channels, message) {
  12294. broadcastOn(channels, message);
  12295. },
  12296. broadcastEvent: function (eventName, event) {
  12297. broadcastEvent(eventName, event);
  12298. },
  12299. isConnected: constant(true)
  12300. };
  12301. var addToWorld = function (component) {
  12302. component.connect(systemApi);
  12303. if (!isText(component.element())) {
  12304. registry.register(component);
  12305. each(component.components(), addToWorld);
  12306. systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
  12307. }
  12308. };
  12309. var removeFromWorld = function (component) {
  12310. if (!isText(component.element())) {
  12311. each(component.components(), removeFromWorld);
  12312. registry.unregister(component);
  12313. }
  12314. component.disconnect();
  12315. };
  12316. var add = function (component) {
  12317. attach$1(root, component);
  12318. };
  12319. var remove$1 = function (component) {
  12320. detach(component);
  12321. };
  12322. var destroy = function () {
  12323. domEvents.unbind();
  12324. remove(root.element());
  12325. };
  12326. var broadcastData = function (data) {
  12327. var receivers = registry.filter(receive());
  12328. each(receivers, function (receiver) {
  12329. var descHandler = receiver.descHandler();
  12330. var handler = getCurried(descHandler);
  12331. handler(data);
  12332. });
  12333. };
  12334. var broadcast$1 = function (message) {
  12335. broadcastData({
  12336. universal: constant(true),
  12337. data: constant(message)
  12338. });
  12339. };
  12340. var broadcastOn = function (channels, message) {
  12341. broadcastData({
  12342. universal: constant(false),
  12343. channels: constant(channels),
  12344. data: constant(message)
  12345. });
  12346. };
  12347. var broadcastEvent = function (eventName, event) {
  12348. var listeners = registry.filter(eventName);
  12349. return broadcast(listeners, event);
  12350. };
  12351. var getByUid = function (uid) {
  12352. return registry.getById(uid).fold(function () {
  12353. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  12354. }, Result.value);
  12355. };
  12356. var getByDom = function (elem) {
  12357. var uid = read$1(elem).getOr('not found');
  12358. return getByUid(uid);
  12359. };
  12360. addToWorld(root);
  12361. return {
  12362. root: constant(root),
  12363. element: root.element,
  12364. destroy: destroy,
  12365. add: add,
  12366. remove: remove$1,
  12367. getByUid: getByUid,
  12368. getByDom: getByDom,
  12369. addToWorld: addToWorld,
  12370. removeFromWorld: removeFromWorld,
  12371. broadcast: broadcast$1,
  12372. broadcastOn: broadcastOn,
  12373. broadcastEvent: broadcastEvent
  12374. };
  12375. };
  12376. var formChangeEvent = generate$1('form-component-change');
  12377. var formCloseEvent = generate$1('form-close');
  12378. var formCancelEvent = generate$1('form-cancel');
  12379. var formActionEvent = generate$1('form-action');
  12380. var formSubmitEvent = generate$1('form-submit');
  12381. var formBlockEvent = generate$1('form-block');
  12382. var formUnblockEvent = generate$1('form-unblock');
  12383. var formTabChangeEvent = generate$1('form-tabchange');
  12384. var formResizeEvent = generate$1('form-resize');
  12385. var renderAlertBanner = function (spec, providersBackstage) {
  12386. return Container.sketch({
  12387. dom: {
  12388. tag: 'div',
  12389. attributes: { role: 'alert' },
  12390. classes: [
  12391. 'tox-notification',
  12392. 'tox-notification--in',
  12393. 'tox-notification--' + spec.level
  12394. ]
  12395. },
  12396. components: [
  12397. {
  12398. dom: {
  12399. tag: 'div',
  12400. classes: ['tox-notification__icon']
  12401. },
  12402. components: [Button.sketch({
  12403. dom: {
  12404. tag: 'button',
  12405. classes: [
  12406. 'tox-button',
  12407. 'tox-button--naked',
  12408. 'tox-button--icon'
  12409. ],
  12410. innerHtml: get$d(spec.icon, providersBackstage.icons),
  12411. attributes: { title: providersBackstage.translate(spec.iconTooltip) }
  12412. },
  12413. action: function (comp) {
  12414. emitWith(comp, formActionEvent, {
  12415. name: 'alert-banner',
  12416. value: spec.url
  12417. });
  12418. }
  12419. })]
  12420. },
  12421. {
  12422. dom: {
  12423. tag: 'div',
  12424. classes: ['tox-notification__body'],
  12425. innerHtml: providersBackstage.translate(spec.text)
  12426. }
  12427. }
  12428. ]
  12429. });
  12430. };
  12431. var renderBar = function (spec, backstage) {
  12432. return {
  12433. dom: {
  12434. tag: 'div',
  12435. classes: [
  12436. 'tox-bar',
  12437. 'tox-form__controls-h-stack'
  12438. ]
  12439. },
  12440. components: map(spec.items, backstage.interpreter)
  12441. };
  12442. };
  12443. var schema$e = constant([
  12444. defaulted$1('prefix', 'form-field'),
  12445. field$1('fieldBehaviours', [
  12446. Composing,
  12447. Representing
  12448. ])
  12449. ]);
  12450. var parts$3 = constant([
  12451. optional({
  12452. schema: [strict$1('dom')],
  12453. name: 'label'
  12454. }),
  12455. optional({
  12456. factory: {
  12457. sketch: function (spec) {
  12458. return {
  12459. uid: spec.uid,
  12460. dom: {
  12461. tag: 'span',
  12462. styles: { display: 'none' },
  12463. attributes: { 'aria-hidden': 'true' },
  12464. innerHtml: spec.text
  12465. }
  12466. };
  12467. }
  12468. },
  12469. schema: [strict$1('text')],
  12470. name: 'aria-descriptor'
  12471. }),
  12472. required({
  12473. factory: {
  12474. sketch: function (spec) {
  12475. var excludeFactory = exclude$1(spec, ['factory']);
  12476. return spec.factory.sketch(excludeFactory);
  12477. }
  12478. },
  12479. schema: [strict$1('factory')],
  12480. name: 'field'
  12481. })
  12482. ]);
  12483. var factory$4 = function (detail, components, _spec, _externals) {
  12484. var behaviours = augment(detail.fieldBehaviours, [
  12485. Composing.config({
  12486. find: function (container) {
  12487. return getPart(container, detail, 'field');
  12488. }
  12489. }),
  12490. Representing.config({
  12491. store: {
  12492. mode: 'manual',
  12493. getValue: function (field) {
  12494. return Composing.getCurrent(field).bind(Representing.getValue);
  12495. },
  12496. setValue: function (field, value) {
  12497. Composing.getCurrent(field).each(function (current) {
  12498. Representing.setValue(current, value);
  12499. });
  12500. }
  12501. }
  12502. })
  12503. ]);
  12504. var events = derive([runOnAttached(function (component, _simulatedEvent) {
  12505. var ps = getParts(component, detail, [
  12506. 'label',
  12507. 'field',
  12508. 'aria-descriptor'
  12509. ]);
  12510. ps.field().each(function (field) {
  12511. var id = generate$1(detail.prefix);
  12512. ps.label().each(function (label) {
  12513. set$1(label.element(), 'for', id);
  12514. set$1(field.element(), 'id', id);
  12515. });
  12516. ps['aria-descriptor']().each(function (descriptor) {
  12517. var descriptorId = generate$1(detail.prefix);
  12518. set$1(descriptor.element(), 'id', descriptorId);
  12519. set$1(field.element(), 'aria-describedby', descriptorId);
  12520. });
  12521. });
  12522. })]);
  12523. var apis = {
  12524. getField: function (container) {
  12525. return getPart(container, detail, 'field');
  12526. },
  12527. getLabel: function (container) {
  12528. return getPart(container, detail, 'label');
  12529. }
  12530. };
  12531. return {
  12532. uid: detail.uid,
  12533. dom: detail.dom,
  12534. components: components,
  12535. behaviours: behaviours,
  12536. events: events,
  12537. apis: apis
  12538. };
  12539. };
  12540. var FormField = composite$1({
  12541. name: 'FormField',
  12542. configFields: schema$e(),
  12543. partFields: parts$3(),
  12544. factory: factory$4,
  12545. apis: {
  12546. getField: function (apis, comp) {
  12547. return apis.getField(comp);
  12548. },
  12549. getLabel: function (apis, comp) {
  12550. return apis.getLabel(comp);
  12551. }
  12552. }
  12553. });
  12554. var schema$f = constant([
  12555. option('data'),
  12556. defaulted$1('inputAttributes', {}),
  12557. defaulted$1('inputStyles', {}),
  12558. defaulted$1('tag', 'input'),
  12559. defaulted$1('inputClasses', []),
  12560. onHandler('onSetValue'),
  12561. defaulted$1('styles', {}),
  12562. defaulted$1('eventOrder', {}),
  12563. field$1('inputBehaviours', [
  12564. Representing,
  12565. Focusing
  12566. ]),
  12567. defaulted$1('selectOnFocus', true)
  12568. ]);
  12569. var focusBehaviours = function (detail) {
  12570. return derive$1([Focusing.config({
  12571. onFocus: !detail.selectOnFocus ? noop : function (component) {
  12572. var input = component.element();
  12573. var value = get$5(input);
  12574. input.dom().setSelectionRange(0, value.length);
  12575. }
  12576. })]);
  12577. };
  12578. var behaviours = function (detail) {
  12579. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  12580. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  12581. return { initialValue: data };
  12582. }).getOr({})), {
  12583. getValue: function (input) {
  12584. return get$5(input.element());
  12585. },
  12586. setValue: function (input, data) {
  12587. var current = get$5(input.element());
  12588. if (current !== data) {
  12589. set$3(input.element(), data);
  12590. }
  12591. }
  12592. }),
  12593. onSetValue: detail.onSetValue
  12594. })]));
  12595. };
  12596. var dom$2 = function (detail) {
  12597. return {
  12598. tag: detail.tag,
  12599. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  12600. styles: detail.inputStyles,
  12601. classes: detail.inputClasses
  12602. };
  12603. };
  12604. var factory$5 = function (detail, _spec) {
  12605. return {
  12606. uid: detail.uid,
  12607. dom: dom$2(detail),
  12608. components: [],
  12609. behaviours: behaviours(detail),
  12610. eventOrder: detail.eventOrder
  12611. };
  12612. };
  12613. var Input = single$2({
  12614. name: 'Input',
  12615. configFields: schema$f(),
  12616. factory: factory$5
  12617. });
  12618. var exports$1 = {}, module = { exports: exports$1 };
  12619. (function (define, exports, module, require) {
  12620. (function (f) {
  12621. if (typeof exports === 'object' && typeof module !== 'undefined') {
  12622. module.exports = f();
  12623. } else if (typeof define === 'function' && define.amd) {
  12624. define([], f);
  12625. } else {
  12626. var g;
  12627. if (typeof window !== 'undefined') {
  12628. g = window;
  12629. } else if (typeof global !== 'undefined') {
  12630. g = global;
  12631. } else if (typeof self !== 'undefined') {
  12632. g = self;
  12633. } else {
  12634. g = this;
  12635. }
  12636. g.EphoxContactWrapper = f();
  12637. }
  12638. }(function () {
  12639. return function () {
  12640. function r(e, n, t) {
  12641. function o(i, f) {
  12642. if (!n[i]) {
  12643. if (!e[i]) {
  12644. var c = 'function' == typeof require && require;
  12645. if (!f && c)
  12646. return c(i, !0);
  12647. if (u)
  12648. return u(i, !0);
  12649. var a = new Error('Cannot find module \'' + i + '\'');
  12650. throw a.code = 'MODULE_NOT_FOUND', a;
  12651. }
  12652. var p = n[i] = { exports: {} };
  12653. e[i][0].call(p.exports, function (r) {
  12654. var n = e[i][1][r];
  12655. return o(n || r);
  12656. }, p, p.exports, r, e, n, t);
  12657. }
  12658. return n[i].exports;
  12659. }
  12660. for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++)
  12661. o(t[i]);
  12662. return o;
  12663. }
  12664. return r;
  12665. }()({
  12666. 1: [
  12667. function (require, module, exports) {
  12668. var process = module.exports = {};
  12669. var cachedSetTimeout;
  12670. var cachedClearTimeout;
  12671. function defaultSetTimout() {
  12672. throw new Error('setTimeout has not been defined');
  12673. }
  12674. function defaultClearTimeout() {
  12675. throw new Error('clearTimeout has not been defined');
  12676. }
  12677. (function () {
  12678. try {
  12679. if (typeof setTimeout === 'function') {
  12680. cachedSetTimeout = setTimeout;
  12681. } else {
  12682. cachedSetTimeout = defaultSetTimout;
  12683. }
  12684. } catch (e) {
  12685. cachedSetTimeout = defaultSetTimout;
  12686. }
  12687. try {
  12688. if (typeof clearTimeout === 'function') {
  12689. cachedClearTimeout = clearTimeout;
  12690. } else {
  12691. cachedClearTimeout = defaultClearTimeout;
  12692. }
  12693. } catch (e) {
  12694. cachedClearTimeout = defaultClearTimeout;
  12695. }
  12696. }());
  12697. function runTimeout(fun) {
  12698. if (cachedSetTimeout === setTimeout) {
  12699. return setTimeout(fun, 0);
  12700. }
  12701. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12702. cachedSetTimeout = setTimeout;
  12703. return setTimeout(fun, 0);
  12704. }
  12705. try {
  12706. return cachedSetTimeout(fun, 0);
  12707. } catch (e) {
  12708. try {
  12709. return cachedSetTimeout.call(null, fun, 0);
  12710. } catch (e) {
  12711. return cachedSetTimeout.call(this, fun, 0);
  12712. }
  12713. }
  12714. }
  12715. function runClearTimeout(marker) {
  12716. if (cachedClearTimeout === clearTimeout) {
  12717. return clearTimeout(marker);
  12718. }
  12719. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12720. cachedClearTimeout = clearTimeout;
  12721. return clearTimeout(marker);
  12722. }
  12723. try {
  12724. return cachedClearTimeout(marker);
  12725. } catch (e) {
  12726. try {
  12727. return cachedClearTimeout.call(null, marker);
  12728. } catch (e) {
  12729. return cachedClearTimeout.call(this, marker);
  12730. }
  12731. }
  12732. }
  12733. var queue = [];
  12734. var draining = false;
  12735. var currentQueue;
  12736. var queueIndex = -1;
  12737. function cleanUpNextTick() {
  12738. if (!draining || !currentQueue) {
  12739. return;
  12740. }
  12741. draining = false;
  12742. if (currentQueue.length) {
  12743. queue = currentQueue.concat(queue);
  12744. } else {
  12745. queueIndex = -1;
  12746. }
  12747. if (queue.length) {
  12748. drainQueue();
  12749. }
  12750. }
  12751. function drainQueue() {
  12752. if (draining) {
  12753. return;
  12754. }
  12755. var timeout = runTimeout(cleanUpNextTick);
  12756. draining = true;
  12757. var len = queue.length;
  12758. while (len) {
  12759. currentQueue = queue;
  12760. queue = [];
  12761. while (++queueIndex < len) {
  12762. if (currentQueue) {
  12763. currentQueue[queueIndex].run();
  12764. }
  12765. }
  12766. queueIndex = -1;
  12767. len = queue.length;
  12768. }
  12769. currentQueue = null;
  12770. draining = false;
  12771. runClearTimeout(timeout);
  12772. }
  12773. process.nextTick = function (fun) {
  12774. var args = new Array(arguments.length - 1);
  12775. if (arguments.length > 1) {
  12776. for (var i = 1; i < arguments.length; i++) {
  12777. args[i - 1] = arguments[i];
  12778. }
  12779. }
  12780. queue.push(new Item(fun, args));
  12781. if (queue.length === 1 && !draining) {
  12782. runTimeout(drainQueue);
  12783. }
  12784. };
  12785. function Item(fun, array) {
  12786. this.fun = fun;
  12787. this.array = array;
  12788. }
  12789. Item.prototype.run = function () {
  12790. this.fun.apply(null, this.array);
  12791. };
  12792. process.title = 'browser';
  12793. process.browser = true;
  12794. process.env = {};
  12795. process.argv = [];
  12796. process.version = '';
  12797. process.versions = {};
  12798. function noop() {
  12799. }
  12800. process.on = noop;
  12801. process.addListener = noop;
  12802. process.once = noop;
  12803. process.off = noop;
  12804. process.removeListener = noop;
  12805. process.removeAllListeners = noop;
  12806. process.emit = noop;
  12807. process.prependListener = noop;
  12808. process.prependOnceListener = noop;
  12809. process.listeners = function (name) {
  12810. return [];
  12811. };
  12812. process.binding = function (name) {
  12813. throw new Error('process.binding is not supported');
  12814. };
  12815. process.cwd = function () {
  12816. return '/';
  12817. };
  12818. process.chdir = function (dir) {
  12819. throw new Error('process.chdir is not supported');
  12820. };
  12821. process.umask = function () {
  12822. return 0;
  12823. };
  12824. },
  12825. {}
  12826. ],
  12827. 2: [
  12828. function (require, module, exports) {
  12829. (function (setImmediate) {
  12830. (function (root) {
  12831. var setTimeoutFunc = setTimeout;
  12832. function noop() {
  12833. }
  12834. function bind(fn, thisArg) {
  12835. return function () {
  12836. fn.apply(thisArg, arguments);
  12837. };
  12838. }
  12839. function Promise(fn) {
  12840. if (typeof this !== 'object')
  12841. throw new TypeError('Promises must be constructed via new');
  12842. if (typeof fn !== 'function')
  12843. throw new TypeError('not a function');
  12844. this._state = 0;
  12845. this._handled = false;
  12846. this._value = undefined;
  12847. this._deferreds = [];
  12848. doResolve(fn, this);
  12849. }
  12850. function handle(self, deferred) {
  12851. while (self._state === 3) {
  12852. self = self._value;
  12853. }
  12854. if (self._state === 0) {
  12855. self._deferreds.push(deferred);
  12856. return;
  12857. }
  12858. self._handled = true;
  12859. Promise._immediateFn(function () {
  12860. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  12861. if (cb === null) {
  12862. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  12863. return;
  12864. }
  12865. var ret;
  12866. try {
  12867. ret = cb(self._value);
  12868. } catch (e) {
  12869. reject(deferred.promise, e);
  12870. return;
  12871. }
  12872. resolve(deferred.promise, ret);
  12873. });
  12874. }
  12875. function resolve(self, newValue) {
  12876. try {
  12877. if (newValue === self)
  12878. throw new TypeError('A promise cannot be resolved with itself.');
  12879. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  12880. var then = newValue.then;
  12881. if (newValue instanceof Promise) {
  12882. self._state = 3;
  12883. self._value = newValue;
  12884. finale(self);
  12885. return;
  12886. } else if (typeof then === 'function') {
  12887. doResolve(bind(then, newValue), self);
  12888. return;
  12889. }
  12890. }
  12891. self._state = 1;
  12892. self._value = newValue;
  12893. finale(self);
  12894. } catch (e) {
  12895. reject(self, e);
  12896. }
  12897. }
  12898. function reject(self, newValue) {
  12899. self._state = 2;
  12900. self._value = newValue;
  12901. finale(self);
  12902. }
  12903. function finale(self) {
  12904. if (self._state === 2 && self._deferreds.length === 0) {
  12905. Promise._immediateFn(function () {
  12906. if (!self._handled) {
  12907. Promise._unhandledRejectionFn(self._value);
  12908. }
  12909. });
  12910. }
  12911. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  12912. handle(self, self._deferreds[i]);
  12913. }
  12914. self._deferreds = null;
  12915. }
  12916. function Handler(onFulfilled, onRejected, promise) {
  12917. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  12918. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  12919. this.promise = promise;
  12920. }
  12921. function doResolve(fn, self) {
  12922. var done = false;
  12923. try {
  12924. fn(function (value) {
  12925. if (done)
  12926. return;
  12927. done = true;
  12928. resolve(self, value);
  12929. }, function (reason) {
  12930. if (done)
  12931. return;
  12932. done = true;
  12933. reject(self, reason);
  12934. });
  12935. } catch (ex) {
  12936. if (done)
  12937. return;
  12938. done = true;
  12939. reject(self, ex);
  12940. }
  12941. }
  12942. Promise.prototype['catch'] = function (onRejected) {
  12943. return this.then(null, onRejected);
  12944. };
  12945. Promise.prototype.then = function (onFulfilled, onRejected) {
  12946. var prom = new this.constructor(noop);
  12947. handle(this, new Handler(onFulfilled, onRejected, prom));
  12948. return prom;
  12949. };
  12950. Promise.all = function (arr) {
  12951. var args = Array.prototype.slice.call(arr);
  12952. return new Promise(function (resolve, reject) {
  12953. if (args.length === 0)
  12954. return resolve([]);
  12955. var remaining = args.length;
  12956. function res(i, val) {
  12957. try {
  12958. if (val && (typeof val === 'object' || typeof val === 'function')) {
  12959. var then = val.then;
  12960. if (typeof then === 'function') {
  12961. then.call(val, function (val) {
  12962. res(i, val);
  12963. }, reject);
  12964. return;
  12965. }
  12966. }
  12967. args[i] = val;
  12968. if (--remaining === 0) {
  12969. resolve(args);
  12970. }
  12971. } catch (ex) {
  12972. reject(ex);
  12973. }
  12974. }
  12975. for (var i = 0; i < args.length; i++) {
  12976. res(i, args[i]);
  12977. }
  12978. });
  12979. };
  12980. Promise.resolve = function (value) {
  12981. if (value && typeof value === 'object' && value.constructor === Promise) {
  12982. return value;
  12983. }
  12984. return new Promise(function (resolve) {
  12985. resolve(value);
  12986. });
  12987. };
  12988. Promise.reject = function (value) {
  12989. return new Promise(function (resolve, reject) {
  12990. reject(value);
  12991. });
  12992. };
  12993. Promise.race = function (values) {
  12994. return new Promise(function (resolve, reject) {
  12995. for (var i = 0, len = values.length; i < len; i++) {
  12996. values[i].then(resolve, reject);
  12997. }
  12998. });
  12999. };
  13000. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  13001. setImmediate(fn);
  13002. } : function (fn) {
  13003. setTimeoutFunc(fn, 0);
  13004. };
  13005. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  13006. if (typeof console !== 'undefined' && console) {
  13007. console.warn('Possible Unhandled Promise Rejection:', err);
  13008. }
  13009. };
  13010. Promise._setImmediateFn = function _setImmediateFn(fn) {
  13011. Promise._immediateFn = fn;
  13012. };
  13013. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  13014. Promise._unhandledRejectionFn = fn;
  13015. };
  13016. if (typeof module !== 'undefined' && module.exports) {
  13017. module.exports = Promise;
  13018. } else if (!root.Promise) {
  13019. root.Promise = Promise;
  13020. }
  13021. }(this));
  13022. }.call(this, require('timers').setImmediate));
  13023. },
  13024. { 'timers': 3 }
  13025. ],
  13026. 3: [
  13027. function (require, module, exports) {
  13028. (function (setImmediate, clearImmediate) {
  13029. var nextTick = require('process/browser.js').nextTick;
  13030. var apply = Function.prototype.apply;
  13031. var slice = Array.prototype.slice;
  13032. var immediateIds = {};
  13033. var nextImmediateId = 0;
  13034. exports.setTimeout = function () {
  13035. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  13036. };
  13037. exports.setInterval = function () {
  13038. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  13039. };
  13040. exports.clearTimeout = exports.clearInterval = function (timeout) {
  13041. timeout.close();
  13042. };
  13043. function Timeout(id, clearFn) {
  13044. this._id = id;
  13045. this._clearFn = clearFn;
  13046. }
  13047. Timeout.prototype.unref = Timeout.prototype.ref = function () {
  13048. };
  13049. Timeout.prototype.close = function () {
  13050. this._clearFn.call(window, this._id);
  13051. };
  13052. exports.enroll = function (item, msecs) {
  13053. clearTimeout(item._idleTimeoutId);
  13054. item._idleTimeout = msecs;
  13055. };
  13056. exports.unenroll = function (item) {
  13057. clearTimeout(item._idleTimeoutId);
  13058. item._idleTimeout = -1;
  13059. };
  13060. exports._unrefActive = exports.active = function (item) {
  13061. clearTimeout(item._idleTimeoutId);
  13062. var msecs = item._idleTimeout;
  13063. if (msecs >= 0) {
  13064. item._idleTimeoutId = setTimeout(function onTimeout() {
  13065. if (item._onTimeout)
  13066. item._onTimeout();
  13067. }, msecs);
  13068. }
  13069. };
  13070. exports.setImmediate = typeof setImmediate === 'function' ? setImmediate : function (fn) {
  13071. var id = nextImmediateId++;
  13072. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  13073. immediateIds[id] = true;
  13074. nextTick(function onNextTick() {
  13075. if (immediateIds[id]) {
  13076. if (args) {
  13077. fn.apply(null, args);
  13078. } else {
  13079. fn.call(null);
  13080. }
  13081. exports.clearImmediate(id);
  13082. }
  13083. });
  13084. return id;
  13085. };
  13086. exports.clearImmediate = typeof clearImmediate === 'function' ? clearImmediate : function (id) {
  13087. delete immediateIds[id];
  13088. };
  13089. }.call(this, require('timers').setImmediate, require('timers').clearImmediate));
  13090. },
  13091. {
  13092. 'process/browser.js': 1,
  13093. 'timers': 3
  13094. }
  13095. ],
  13096. 4: [
  13097. function (require, module, exports) {
  13098. var promisePolyfill = require('promise-polyfill');
  13099. var Global = function () {
  13100. if (typeof window !== 'undefined') {
  13101. return window;
  13102. } else {
  13103. return Function('return this;')();
  13104. }
  13105. }();
  13106. module.exports = { boltExport: Global.Promise || promisePolyfill };
  13107. },
  13108. { 'promise-polyfill': 2 }
  13109. ]
  13110. }, {}, [4])(4);
  13111. }));
  13112. }(undefined, exports$1, module, undefined));
  13113. var Promise = module.exports.boltExport;
  13114. var nu$a = function (baseFn) {
  13115. var data = Option.none();
  13116. var callbacks = [];
  13117. var map = function (f) {
  13118. return nu$a(function (nCallback) {
  13119. get(function (data) {
  13120. nCallback(f(data));
  13121. });
  13122. });
  13123. };
  13124. var get = function (nCallback) {
  13125. if (isReady()) {
  13126. call(nCallback);
  13127. } else {
  13128. callbacks.push(nCallback);
  13129. }
  13130. };
  13131. var set = function (x) {
  13132. data = Option.some(x);
  13133. run(callbacks);
  13134. callbacks = [];
  13135. };
  13136. var isReady = function () {
  13137. return data.isSome();
  13138. };
  13139. var run = function (cbs) {
  13140. each(cbs, call);
  13141. };
  13142. var call = function (cb) {
  13143. data.each(function (x) {
  13144. domGlobals.setTimeout(function () {
  13145. cb(x);
  13146. }, 0);
  13147. });
  13148. };
  13149. baseFn(set);
  13150. return {
  13151. get: get,
  13152. map: map,
  13153. isReady: isReady
  13154. };
  13155. };
  13156. var pure$1 = function (a) {
  13157. return nu$a(function (callback) {
  13158. callback(a);
  13159. });
  13160. };
  13161. var LazyValue = {
  13162. nu: nu$a,
  13163. pure: pure$1
  13164. };
  13165. var errorReporter = function (err) {
  13166. domGlobals.setTimeout(function () {
  13167. throw err;
  13168. }, 0);
  13169. };
  13170. var make$3 = function (run) {
  13171. var get = function (callback) {
  13172. run().then(callback, errorReporter);
  13173. };
  13174. var map = function (fab) {
  13175. return make$3(function () {
  13176. return run().then(fab);
  13177. });
  13178. };
  13179. var bind = function (aFutureB) {
  13180. return make$3(function () {
  13181. return run().then(function (v) {
  13182. return aFutureB(v).toPromise();
  13183. });
  13184. });
  13185. };
  13186. var anonBind = function (futureB) {
  13187. return make$3(function () {
  13188. return run().then(function () {
  13189. return futureB.toPromise();
  13190. });
  13191. });
  13192. };
  13193. var toLazy = function () {
  13194. return LazyValue.nu(get);
  13195. };
  13196. var toCached = function () {
  13197. var cache = null;
  13198. return make$3(function () {
  13199. if (cache === null) {
  13200. cache = run();
  13201. }
  13202. return cache;
  13203. });
  13204. };
  13205. var toPromise = run;
  13206. return {
  13207. map: map,
  13208. bind: bind,
  13209. anonBind: anonBind,
  13210. toLazy: toLazy,
  13211. toCached: toCached,
  13212. toPromise: toPromise,
  13213. get: get
  13214. };
  13215. };
  13216. var nu$b = function (baseFn) {
  13217. return make$3(function () {
  13218. return new Promise(baseFn);
  13219. });
  13220. };
  13221. var pure$2 = function (a) {
  13222. return make$3(function () {
  13223. return Promise.resolve(a);
  13224. });
  13225. };
  13226. var Future = {
  13227. nu: nu$b,
  13228. pure: pure$2
  13229. };
  13230. var ariaElements = [
  13231. 'input',
  13232. 'textarea'
  13233. ];
  13234. var isAriaElement = function (elem) {
  13235. var name$1 = name(elem);
  13236. return contains(ariaElements, name$1);
  13237. };
  13238. var markValid = function (component, invalidConfig) {
  13239. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13240. remove$4(elem, invalidConfig.invalidClass);
  13241. invalidConfig.notify.each(function (notifyInfo) {
  13242. if (isAriaElement(component.element())) {
  13243. set$1(component.element(), 'aria-invalid', false);
  13244. }
  13245. notifyInfo.getContainer(component).each(function (container) {
  13246. set(container, notifyInfo.validHtml);
  13247. });
  13248. notifyInfo.onValid(component);
  13249. });
  13250. };
  13251. var markInvalid = function (component, invalidConfig, invalidState, text) {
  13252. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13253. add$2(elem, invalidConfig.invalidClass);
  13254. invalidConfig.notify.each(function (notifyInfo) {
  13255. if (isAriaElement(component.element())) {
  13256. set$1(component.element(), 'aria-invalid', true);
  13257. }
  13258. notifyInfo.getContainer(component).each(function (container) {
  13259. set(container, text);
  13260. });
  13261. notifyInfo.onInvalid(component, text);
  13262. });
  13263. };
  13264. var query = function (component, invalidConfig, _invalidState) {
  13265. return invalidConfig.validator.fold(function () {
  13266. return Future.pure(Result.value(true));
  13267. }, function (validatorInfo) {
  13268. return validatorInfo.validate(component);
  13269. });
  13270. };
  13271. var run$1 = function (component, invalidConfig, invalidState) {
  13272. invalidConfig.notify.each(function (notifyInfo) {
  13273. notifyInfo.onValidate(component);
  13274. });
  13275. return query(component, invalidConfig).map(function (valid) {
  13276. if (component.getSystem().isConnected()) {
  13277. return valid.fold(function (err) {
  13278. markInvalid(component, invalidConfig, invalidState, err);
  13279. return Result.error(err);
  13280. }, function (v) {
  13281. markValid(component, invalidConfig);
  13282. return Result.value(v);
  13283. });
  13284. } else {
  13285. return Result.error('No longer in system');
  13286. }
  13287. });
  13288. };
  13289. var isInvalid = function (component, invalidConfig) {
  13290. var elem = invalidConfig.getRoot(component).getOr(component.element());
  13291. return has$2(elem, invalidConfig.invalidClass);
  13292. };
  13293. var InvalidateApis = /*#__PURE__*/Object.freeze({
  13294. __proto__: null,
  13295. markValid: markValid,
  13296. markInvalid: markInvalid,
  13297. query: query,
  13298. run: run$1,
  13299. isInvalid: isInvalid
  13300. });
  13301. var events$a = function (invalidConfig, invalidState) {
  13302. return invalidConfig.validator.map(function (validatorInfo) {
  13303. return derive([run(validatorInfo.onEvent, function (component) {
  13304. run$1(component, invalidConfig, invalidState).get(identity);
  13305. })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) {
  13306. run$1(component, invalidConfig, invalidState).get(noop);
  13307. })] : []));
  13308. }).getOr({});
  13309. };
  13310. var ActiveInvalidate = /*#__PURE__*/Object.freeze({
  13311. __proto__: null,
  13312. events: events$a
  13313. });
  13314. var InvalidateSchema = [
  13315. strict$1('invalidClass'),
  13316. defaulted$1('getRoot', Option.none),
  13317. optionObjOf('notify', [
  13318. defaulted$1('aria', 'alert'),
  13319. defaulted$1('getContainer', Option.none),
  13320. defaulted$1('validHtml', ''),
  13321. onHandler('onValid'),
  13322. onHandler('onInvalid'),
  13323. onHandler('onValidate')
  13324. ]),
  13325. optionObjOf('validator', [
  13326. strict$1('validate'),
  13327. defaulted$1('onEvent', 'input'),
  13328. defaulted$1('validateOnLoad', true)
  13329. ])
  13330. ];
  13331. var Invalidating = create$1({
  13332. fields: InvalidateSchema,
  13333. name: 'invalidating',
  13334. active: ActiveInvalidate,
  13335. apis: InvalidateApis,
  13336. extra: {
  13337. validation: function (validator) {
  13338. return function (component) {
  13339. var v = Representing.getValue(component);
  13340. return Future.pure(validator(v));
  13341. };
  13342. }
  13343. }
  13344. });
  13345. var exhibit$4 = function (base, tabConfig) {
  13346. return nu$6({
  13347. attributes: wrapAll$1([{
  13348. key: tabConfig.tabAttr,
  13349. value: 'true'
  13350. }])
  13351. });
  13352. };
  13353. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  13354. __proto__: null,
  13355. exhibit: exhibit$4
  13356. });
  13357. var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
  13358. var Tabstopping = create$1({
  13359. fields: TabstopSchema,
  13360. name: 'tabstopping',
  13361. active: ActiveTabstopping
  13362. });
  13363. var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13364. var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours);
  13365. return FormField.sketch(spec);
  13366. };
  13367. var renderFormField = function (pLabel, pField) {
  13368. return renderFormFieldWith(pLabel, pField, [], []);
  13369. };
  13370. var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) {
  13371. return {
  13372. dom: renderFormFieldDomWith(extraClasses),
  13373. components: pLabel.toArray().concat([pField]),
  13374. fieldBehaviours: derive$1(extraBehaviours)
  13375. };
  13376. };
  13377. var renderFormFieldDom = function () {
  13378. return renderFormFieldDomWith([]);
  13379. };
  13380. var renderFormFieldDomWith = function (extraClasses) {
  13381. return {
  13382. tag: 'div',
  13383. classes: ['tox-form__group'].concat(extraClasses)
  13384. };
  13385. };
  13386. var renderLabel = function (label, providersBackstage) {
  13387. return FormField.parts().label({
  13388. dom: {
  13389. tag: 'label',
  13390. classes: ['tox-label'],
  13391. innerHtml: providersBackstage.translate(label)
  13392. }
  13393. });
  13394. };
  13395. var getCoupled = function (component, coupleConfig, coupleState, name) {
  13396. return coupleState.getOrCreate(component, coupleConfig, name);
  13397. };
  13398. var CouplingApis = /*#__PURE__*/Object.freeze({
  13399. __proto__: null,
  13400. getCoupled: getCoupled
  13401. });
  13402. var CouplingSchema = [strictOf('others', setOf$1(Result.value, anyValue$1()))];
  13403. var init$5 = function () {
  13404. var coupled = {};
  13405. var getOrCreate = function (component, coupleConfig, name) {
  13406. var available = keys(coupleConfig.others);
  13407. if (!available) {
  13408. throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2));
  13409. } else {
  13410. return get(coupled, name).getOrThunk(function () {
  13411. var builder = get(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name);
  13412. var spec = builder(component);
  13413. var built = component.getSystem().build(spec);
  13414. coupled[name] = built;
  13415. return built;
  13416. });
  13417. }
  13418. };
  13419. var readState = constant({});
  13420. return nu$5({
  13421. readState: readState,
  13422. getOrCreate: getOrCreate
  13423. });
  13424. };
  13425. var CouplingState = /*#__PURE__*/Object.freeze({
  13426. __proto__: null,
  13427. init: init$5
  13428. });
  13429. var Coupling = create$1({
  13430. fields: CouplingSchema,
  13431. name: 'coupling',
  13432. apis: CouplingApis,
  13433. state: CouplingState
  13434. });
  13435. var suffix = constant('sink');
  13436. var partType = constant(optional({
  13437. name: suffix(),
  13438. overrides: constant({
  13439. dom: { tag: 'div' },
  13440. behaviours: derive$1([Positioning.config({ useFixed: always })]),
  13441. events: derive([
  13442. cutter(keydown()),
  13443. cutter(mousedown()),
  13444. cutter(click())
  13445. ])
  13446. })
  13447. }));
  13448. var HighlightOnOpen;
  13449. (function (HighlightOnOpen) {
  13450. HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst';
  13451. HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone';
  13452. }(HighlightOnOpen || (HighlightOnOpen = {})));
  13453. var getAnchor = function (detail, component) {
  13454. var hotspot = detail.getHotspot(component).getOr(component);
  13455. var anchor = 'hotspot';
  13456. var overrides = detail.getAnchorOverrides();
  13457. return detail.layouts.fold(function () {
  13458. return {
  13459. anchor: anchor,
  13460. hotspot: hotspot,
  13461. overrides: overrides
  13462. };
  13463. }, function (layouts) {
  13464. return {
  13465. anchor: anchor,
  13466. hotspot: hotspot,
  13467. overrides: overrides,
  13468. layouts: layouts
  13469. };
  13470. });
  13471. };
  13472. var fetch = function (detail, mapFetch, component) {
  13473. var fetcher = detail.fetch;
  13474. return fetcher(component).map(mapFetch);
  13475. };
  13476. var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) {
  13477. var futureData = fetch(detail, mapFetch, component);
  13478. var getLazySink = getSink(component, detail);
  13479. return futureData.map(function (tdata) {
  13480. return tdata.bind(function (data) {
  13481. return Option.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), {
  13482. uid: generate$2(''),
  13483. data: data,
  13484. highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst,
  13485. onOpenMenu: function (tmenu, menu) {
  13486. var sink = getLazySink().getOrDie();
  13487. Positioning.position(sink, anchor, menu);
  13488. Sandboxing.decloak(sandbox);
  13489. },
  13490. onOpenSubmenu: function (tmenu, item, submenu) {
  13491. var sink = getLazySink().getOrDie();
  13492. Positioning.position(sink, {
  13493. anchor: 'submenu',
  13494. item: item
  13495. }, submenu);
  13496. Sandboxing.decloak(sandbox);
  13497. },
  13498. onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) {
  13499. var sink = getLazySink().getOrDie();
  13500. Positioning.position(sink, anchor, primaryMenu);
  13501. each(submenuTriggers, function (st) {
  13502. Positioning.position(sink, {
  13503. anchor: 'submenu',
  13504. item: st.triggeringItem
  13505. }, st.triggeredMenu);
  13506. });
  13507. },
  13508. onEscape: function () {
  13509. Focusing.focus(component);
  13510. Sandboxing.close(sandbox);
  13511. return Option.some(true);
  13512. }
  13513. })));
  13514. });
  13515. });
  13516. };
  13517. var open$1 = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) {
  13518. var anchor = getAnchor(detail, hotspot);
  13519. var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen);
  13520. return processed.map(function (tdata) {
  13521. tdata.fold(function () {
  13522. if (Sandboxing.isOpen(sandbox)) {
  13523. Sandboxing.close(sandbox);
  13524. }
  13525. }, function (data) {
  13526. Sandboxing.cloak(sandbox);
  13527. Sandboxing.open(sandbox, data);
  13528. onOpenSync(sandbox);
  13529. });
  13530. return sandbox;
  13531. });
  13532. };
  13533. var close$1 = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) {
  13534. Sandboxing.close(sandbox);
  13535. return Future.pure(sandbox);
  13536. };
  13537. var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) {
  13538. var sandbox = Coupling.getCoupled(hotspot, 'sandbox');
  13539. var showing = Sandboxing.isOpen(sandbox);
  13540. var action = showing ? close$1 : open$1;
  13541. return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen);
  13542. };
  13543. var matchWidth = function (hotspot, container, useMinWidth) {
  13544. var menu = Composing.getCurrent(container).getOr(container);
  13545. var buttonWidth = get$7(hotspot.element());
  13546. if (useMinWidth) {
  13547. set$2(menu.element(), 'min-width', buttonWidth + 'px');
  13548. } else {
  13549. set$4(menu.element(), buttonWidth);
  13550. }
  13551. };
  13552. var getSink = function (anyInSystem, sinkDetail) {
  13553. return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) {
  13554. return function () {
  13555. return Result.value(internalSink);
  13556. };
  13557. }).getOrThunk(function () {
  13558. return sinkDetail.lazySink.fold(function () {
  13559. return function () {
  13560. return Result.error(new Error('No internal sink is specified, nor could an external sink be found'));
  13561. };
  13562. }, function (lazySinkFn) {
  13563. return function () {
  13564. return lazySinkFn(anyInSystem);
  13565. };
  13566. });
  13567. });
  13568. };
  13569. var doRepositionMenus = function (sandbox) {
  13570. Sandboxing.getState(sandbox).each(function (tmenu) {
  13571. tieredMenu.repositionMenus(tmenu);
  13572. });
  13573. };
  13574. var makeSandbox = function (detail, hotspot, extras) {
  13575. var ariaOwner = manager();
  13576. var onOpen = function (component, menu) {
  13577. var anchor = getAnchor(detail, hotspot);
  13578. ariaOwner.link(hotspot.element());
  13579. if (detail.matchWidth) {
  13580. matchWidth(anchor.hotspot, menu, detail.useMinWidth);
  13581. }
  13582. detail.onOpen(anchor, component, menu);
  13583. if (extras !== undefined && extras.onOpen !== undefined) {
  13584. extras.onOpen(component, menu);
  13585. }
  13586. };
  13587. var onClose = function (component, menu) {
  13588. ariaOwner.unlink(hotspot.element());
  13589. if (extras !== undefined && extras.onClose !== undefined) {
  13590. extras.onClose(component, menu);
  13591. }
  13592. };
  13593. var lazySink = getSink(hotspot, detail);
  13594. return {
  13595. dom: {
  13596. tag: 'div',
  13597. classes: detail.sandboxClasses,
  13598. attributes: {
  13599. id: ariaOwner.id,
  13600. role: 'listbox'
  13601. }
  13602. },
  13603. behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [
  13604. Representing.config({
  13605. store: {
  13606. mode: 'memory',
  13607. initialValue: hotspot
  13608. }
  13609. }),
  13610. Sandboxing.config({
  13611. onOpen: onOpen,
  13612. onClose: onClose,
  13613. isPartOf: function (container, data, queryElem) {
  13614. return isPartOf(data, queryElem) || isPartOf(hotspot, queryElem);
  13615. },
  13616. getAttachPoint: function () {
  13617. return lazySink().getOrDie();
  13618. }
  13619. }),
  13620. Composing.config({
  13621. find: function (sandbox) {
  13622. return Sandboxing.getState(sandbox).bind(function (menu) {
  13623. return Composing.getCurrent(menu);
  13624. });
  13625. }
  13626. }),
  13627. Receiving.config({ channels: __assign(__assign({}, receivingChannel({ isExtraPart: never })), receivingChannel$1({ doReposition: doRepositionMenus })) })
  13628. ])
  13629. };
  13630. };
  13631. var repositionMenus = function (comp) {
  13632. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13633. doRepositionMenus(sandbox);
  13634. };
  13635. var sandboxFields = function () {
  13636. return [
  13637. defaulted$1('sandboxClasses', []),
  13638. SketchBehaviours.field('sandboxBehaviours', [
  13639. Composing,
  13640. Receiving,
  13641. Sandboxing,
  13642. Representing
  13643. ])
  13644. ];
  13645. };
  13646. var schema$g = constant([
  13647. strict$1('dom'),
  13648. strict$1('fetch'),
  13649. onHandler('onOpen'),
  13650. onKeyboardHandler('onExecute'),
  13651. defaulted$1('getHotspot', Option.some),
  13652. defaulted$1('getAnchorOverrides', constant({})),
  13653. schema$1(),
  13654. field$1('dropdownBehaviours', [
  13655. Toggling,
  13656. Coupling,
  13657. Keying,
  13658. Focusing
  13659. ]),
  13660. strict$1('toggleClass'),
  13661. defaulted$1('eventOrder', {}),
  13662. option('lazySink'),
  13663. defaulted$1('matchWidth', false),
  13664. defaulted$1('useMinWidth', false),
  13665. option('role')
  13666. ].concat(sandboxFields()));
  13667. var parts$4 = constant([
  13668. external$1({
  13669. schema: [tieredMenuMarkers()],
  13670. name: 'menu',
  13671. defaults: function (detail) {
  13672. return { onExecute: detail.onExecute };
  13673. }
  13674. }),
  13675. partType()
  13676. ]);
  13677. var factory$6 = function (detail, components, _spec, externals) {
  13678. var _a;
  13679. var lookupAttr = function (attr) {
  13680. return get(detail.dom, 'attributes').bind(function (attrs) {
  13681. return get(attrs, attr);
  13682. });
  13683. };
  13684. var switchToMenu = function (sandbox) {
  13685. Sandboxing.getState(sandbox).each(function (tmenu) {
  13686. tieredMenu.highlightPrimary(tmenu);
  13687. });
  13688. };
  13689. var action = function (component) {
  13690. var onOpenSync = switchToMenu;
  13691. togglePopup(detail, function (x) {
  13692. return x;
  13693. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  13694. };
  13695. var apis = {
  13696. expand: function (comp) {
  13697. if (!Toggling.isOn(comp)) {
  13698. togglePopup(detail, function (x) {
  13699. return x;
  13700. }, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop);
  13701. }
  13702. },
  13703. open: function (comp) {
  13704. if (!Toggling.isOn(comp)) {
  13705. togglePopup(detail, function (x) {
  13706. return x;
  13707. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13708. }
  13709. },
  13710. isOpen: Toggling.isOn,
  13711. close: function (comp) {
  13712. if (Toggling.isOn(comp)) {
  13713. togglePopup(detail, function (x) {
  13714. return x;
  13715. }, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop);
  13716. }
  13717. },
  13718. repositionMenus: function (comp) {
  13719. if (Toggling.isOn(comp)) {
  13720. repositionMenus(comp);
  13721. }
  13722. }
  13723. };
  13724. var triggerExecute = function (comp, _se) {
  13725. emitExecute(comp);
  13726. return Option.some(true);
  13727. };
  13728. return {
  13729. uid: detail.uid,
  13730. dom: detail.dom,
  13731. components: components,
  13732. behaviours: augment(detail.dropdownBehaviours, [
  13733. Toggling.config({
  13734. toggleClass: detail.toggleClass,
  13735. aria: { mode: 'expanded' }
  13736. }),
  13737. Coupling.config({
  13738. others: {
  13739. sandbox: function (hotspot) {
  13740. return makeSandbox(detail, hotspot, {
  13741. onOpen: function () {
  13742. Toggling.on(hotspot);
  13743. },
  13744. onClose: function () {
  13745. Toggling.off(hotspot);
  13746. }
  13747. });
  13748. }
  13749. }
  13750. }),
  13751. Keying.config({
  13752. mode: 'special',
  13753. onSpace: triggerExecute,
  13754. onEnter: triggerExecute,
  13755. onDown: function (comp, _se) {
  13756. if (Dropdown.isOpen(comp)) {
  13757. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  13758. switchToMenu(sandbox);
  13759. } else {
  13760. Dropdown.open(comp);
  13761. }
  13762. return Option.some(true);
  13763. },
  13764. onEscape: function (comp, _se) {
  13765. if (Dropdown.isOpen(comp)) {
  13766. Dropdown.close(comp);
  13767. return Option.some(true);
  13768. } else {
  13769. return Option.none();
  13770. }
  13771. }
  13772. }),
  13773. Focusing.config({})
  13774. ]),
  13775. events: events$7(Option.some(action)),
  13776. eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute()] = [
  13777. 'disabling',
  13778. 'toggling',
  13779. 'alloy.base.behaviour'
  13780. ], _a)),
  13781. apis: apis,
  13782. domModification: {
  13783. attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () {
  13784. return {};
  13785. }, function (role) {
  13786. return { role: role };
  13787. })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {})
  13788. }
  13789. };
  13790. };
  13791. var Dropdown = composite$1({
  13792. name: 'Dropdown',
  13793. configFields: schema$g(),
  13794. partFields: parts$4(),
  13795. factory: factory$6,
  13796. apis: {
  13797. open: function (apis, comp) {
  13798. return apis.open(comp);
  13799. },
  13800. expand: function (apis, comp) {
  13801. return apis.expand(comp);
  13802. },
  13803. close: function (apis, comp) {
  13804. return apis.close(comp);
  13805. },
  13806. isOpen: function (apis, comp) {
  13807. return apis.isOpen(comp);
  13808. },
  13809. repositionMenus: function (apis, comp) {
  13810. return apis.repositionMenus(comp);
  13811. }
  13812. }
  13813. });
  13814. var exhibit$5 = function () {
  13815. return nu$6({
  13816. styles: {
  13817. '-webkit-user-select': 'none',
  13818. 'user-select': 'none',
  13819. '-ms-user-select': 'none',
  13820. '-moz-user-select': '-moz-none'
  13821. },
  13822. attributes: { unselectable: 'on' }
  13823. });
  13824. };
  13825. var events$b = function () {
  13826. return derive([abort(selectstart(), constant(true))]);
  13827. };
  13828. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  13829. __proto__: null,
  13830. events: events$b,
  13831. exhibit: exhibit$5
  13832. });
  13833. var Unselecting = create$1({
  13834. fields: [],
  13835. name: 'unselecting',
  13836. active: ActiveUnselecting
  13837. });
  13838. var renderPanelButton = function (spec, sharedBackstage) {
  13839. return Dropdown.sketch({
  13840. dom: spec.dom,
  13841. components: spec.components,
  13842. toggleClass: 'mce-active',
  13843. dropdownBehaviours: derive$1([
  13844. DisablingConfigs.button(sharedBackstage.providers.isReadOnly),
  13845. receivingConfig(),
  13846. Unselecting.config({}),
  13847. Tabstopping.config({})
  13848. ]),
  13849. layouts: spec.layouts,
  13850. sandboxClasses: ['tox-dialog__popups'],
  13851. lazySink: sharedBackstage.getSink,
  13852. fetch: function (comp) {
  13853. return Future.nu(function (callback) {
  13854. return spec.fetch(callback);
  13855. }).map(function (items) {
  13856. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  13857. spec.onItemAction(comp, value);
  13858. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, function () {
  13859. return false;
  13860. }, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) })));
  13861. });
  13862. },
  13863. parts: { menu: part(false, 1, spec.presets) }
  13864. });
  13865. };
  13866. var colorInputChangeEvent = generate$1('color-input-change');
  13867. var colorSwatchChangeEvent = generate$1('color-swatch-change');
  13868. var colorPickerCancelEvent = generate$1('color-picker-cancel');
  13869. var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) {
  13870. var pField = FormField.parts().field({
  13871. factory: Input,
  13872. inputClasses: ['tox-textfield'],
  13873. onSetValue: function (c) {
  13874. return Invalidating.run(c).get(function () {
  13875. });
  13876. },
  13877. inputBehaviours: derive$1([
  13878. Disabling.config({ disabled: sharedBackstage.providers.isReadOnly }),
  13879. receivingConfig(),
  13880. Tabstopping.config({}),
  13881. Invalidating.config({
  13882. invalidClass: 'tox-textbox-field-invalid',
  13883. getRoot: function (comp) {
  13884. return parent(comp.element());
  13885. },
  13886. notify: {
  13887. onValid: function (comp) {
  13888. var val = Representing.getValue(comp);
  13889. emitWith(comp, colorInputChangeEvent, { color: val });
  13890. }
  13891. },
  13892. validator: {
  13893. validateOnLoad: false,
  13894. validate: function (input) {
  13895. var inputValue = Representing.getValue(input);
  13896. if (inputValue.length === 0) {
  13897. return Future.pure(Result.value(true));
  13898. } else {
  13899. var span = Element.fromTag('span');
  13900. set$2(span, 'background-color', inputValue);
  13901. var res = getRaw(span, 'background-color').fold(function () {
  13902. return Result.error('blah');
  13903. }, function (_) {
  13904. return Result.value(inputValue);
  13905. });
  13906. return Future.pure(res);
  13907. }
  13908. }
  13909. }
  13910. })
  13911. ]),
  13912. selectOnFocus: false
  13913. });
  13914. var pLabel = spec.label.map(function (label) {
  13915. return renderLabel(label, sharedBackstage.providers);
  13916. });
  13917. var emitSwatchChange = function (colorBit, value) {
  13918. emitWith(colorBit, colorSwatchChangeEvent, { value: value });
  13919. };
  13920. var onItemAction = function (comp, value) {
  13921. memColorButton.getOpt(comp).each(function (colorBit) {
  13922. if (value === 'custom') {
  13923. colorInputBackstage.colorPicker(function (valueOpt) {
  13924. valueOpt.fold(function () {
  13925. return emit(colorBit, colorPickerCancelEvent);
  13926. }, function (value) {
  13927. emitSwatchChange(colorBit, value);
  13928. addColor(value);
  13929. });
  13930. }, '#ffffff');
  13931. } else if (value === 'remove') {
  13932. emitSwatchChange(colorBit, '');
  13933. } else {
  13934. emitSwatchChange(colorBit, value);
  13935. }
  13936. });
  13937. };
  13938. var memColorButton = record(renderPanelButton({
  13939. dom: {
  13940. tag: 'span',
  13941. attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') }
  13942. },
  13943. layouts: {
  13944. onRtl: function () {
  13945. return [
  13946. southwest$1,
  13947. southeast$1,
  13948. south$1
  13949. ];
  13950. },
  13951. onLtr: function () {
  13952. return [
  13953. southeast$1,
  13954. southwest$1,
  13955. south$1
  13956. ];
  13957. }
  13958. },
  13959. components: [],
  13960. fetch: getFetch(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()),
  13961. columns: colorInputBackstage.getColorCols(),
  13962. presets: 'color',
  13963. onItemAction: onItemAction
  13964. }, sharedBackstage));
  13965. return FormField.sketch({
  13966. dom: {
  13967. tag: 'div',
  13968. classes: ['tox-form__group']
  13969. },
  13970. components: pLabel.toArray().concat([{
  13971. dom: {
  13972. tag: 'div',
  13973. classes: ['tox-color-input']
  13974. },
  13975. components: [
  13976. pField,
  13977. memColorButton.asSpec()
  13978. ]
  13979. }]),
  13980. fieldBehaviours: derive$1([config('form-field-events', [
  13981. run(colorInputChangeEvent, function (comp, se) {
  13982. memColorButton.getOpt(comp).each(function (colorButton) {
  13983. set$2(colorButton.element(), 'background-color', se.event().color());
  13984. });
  13985. emitWith(comp, formChangeEvent, { name: spec.name });
  13986. }),
  13987. run(colorSwatchChangeEvent, function (comp, se) {
  13988. FormField.getField(comp).each(function (field) {
  13989. Representing.setValue(field, se.event().value());
  13990. Composing.getCurrent(comp).each(Focusing.focus);
  13991. });
  13992. }),
  13993. run(colorPickerCancelEvent, function (comp, _se) {
  13994. FormField.getField(comp).each(function (_field) {
  13995. Composing.getCurrent(comp).each(Focusing.focus);
  13996. });
  13997. })
  13998. ])])
  13999. });
  14000. };
  14001. var hsvColour = function (hue, saturation, value) {
  14002. return {
  14003. hue: hue,
  14004. saturation: saturation,
  14005. value: value
  14006. };
  14007. };
  14008. var fromRgb = function (rgbaColour) {
  14009. var h = 0;
  14010. var s = 0;
  14011. var v = 0;
  14012. var r = rgbaColour.red / 255;
  14013. var g = rgbaColour.green / 255;
  14014. var b = rgbaColour.blue / 255;
  14015. var minRGB = Math.min(r, Math.min(g, b));
  14016. var maxRGB = Math.max(r, Math.max(g, b));
  14017. if (minRGB === maxRGB) {
  14018. v = minRGB;
  14019. return hsvColour(0, 0, v * 100);
  14020. }
  14021. var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r;
  14022. h = r === minRGB ? 3 : b === minRGB ? 1 : 5;
  14023. h = 60 * (h - d / (maxRGB - minRGB));
  14024. s = (maxRGB - minRGB) / maxRGB;
  14025. v = maxRGB;
  14026. return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100));
  14027. };
  14028. var calcHex = function (value) {
  14029. var hue = (100 - value) / 100 * 360;
  14030. var hsv = hsvColour(hue, 100, 100);
  14031. var rgb = fromHsv(hsv);
  14032. return fromRgba(rgb);
  14033. };
  14034. var fieldsUpdate = generate$1('rgb-hex-update');
  14035. var sliderUpdate = generate$1('slider-update');
  14036. var paletteUpdate = generate$1('palette-update');
  14037. var labelPart = optional({
  14038. schema: [strict$1('dom')],
  14039. name: 'label'
  14040. });
  14041. var edgePart = function (name) {
  14042. return optional({
  14043. name: '' + name + '-edge',
  14044. overrides: function (detail) {
  14045. var action = detail.model.manager.edgeActions[name];
  14046. return action.fold(function () {
  14047. return {};
  14048. }, function (a) {
  14049. return {
  14050. events: derive([
  14051. runActionExtra(touchstart(), function (comp, se, d) {
  14052. return a(comp, d);
  14053. }, [detail]),
  14054. runActionExtra(mousedown(), function (comp, se, d) {
  14055. return a(comp, d);
  14056. }, [detail]),
  14057. runActionExtra(mousemove(), function (comp, se, det) {
  14058. if (det.mouseIsDown.get()) {
  14059. a(comp, det);
  14060. }
  14061. }, [detail])
  14062. ])
  14063. };
  14064. });
  14065. }
  14066. });
  14067. };
  14068. var tlEdgePart = edgePart('top-left');
  14069. var tedgePart = edgePart('top');
  14070. var trEdgePart = edgePart('top-right');
  14071. var redgePart = edgePart('right');
  14072. var brEdgePart = edgePart('bottom-right');
  14073. var bedgePart = edgePart('bottom');
  14074. var blEdgePart = edgePart('bottom-left');
  14075. var ledgePart = edgePart('left');
  14076. var thumbPart = required({
  14077. name: 'thumb',
  14078. defaults: constant({ dom: { styles: { position: 'absolute' } } }),
  14079. overrides: function (detail) {
  14080. return {
  14081. events: derive([
  14082. redirectToPart(touchstart(), detail, 'spectrum'),
  14083. redirectToPart(touchmove(), detail, 'spectrum'),
  14084. redirectToPart(touchend(), detail, 'spectrum'),
  14085. redirectToPart(mousedown(), detail, 'spectrum'),
  14086. redirectToPart(mousemove(), detail, 'spectrum'),
  14087. redirectToPart(mouseup(), detail, 'spectrum')
  14088. ])
  14089. };
  14090. }
  14091. });
  14092. var spectrumPart = required({
  14093. schema: [state$1('mouseIsDown', function () {
  14094. return Cell(false);
  14095. })],
  14096. name: 'spectrum',
  14097. overrides: function (detail) {
  14098. var modelDetail = detail.model;
  14099. var model = modelDetail.manager;
  14100. var setValueFrom = function (component, simulatedEvent) {
  14101. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  14102. return model.setValueFrom(component, detail, value);
  14103. });
  14104. };
  14105. return {
  14106. behaviours: derive$1([
  14107. Keying.config({
  14108. mode: 'special',
  14109. onLeft: function (spectrum) {
  14110. return model.onLeft(spectrum, detail);
  14111. },
  14112. onRight: function (spectrum) {
  14113. return model.onRight(spectrum, detail);
  14114. },
  14115. onUp: function (spectrum) {
  14116. return model.onUp(spectrum, detail);
  14117. },
  14118. onDown: function (spectrum) {
  14119. return model.onDown(spectrum, detail);
  14120. }
  14121. }),
  14122. Focusing.config({})
  14123. ]),
  14124. events: derive([
  14125. run(touchstart(), setValueFrom),
  14126. run(touchmove(), setValueFrom),
  14127. run(mousedown(), setValueFrom),
  14128. run(mousemove(), function (spectrum, se) {
  14129. if (detail.mouseIsDown.get()) {
  14130. setValueFrom(spectrum, se);
  14131. }
  14132. })
  14133. ])
  14134. };
  14135. }
  14136. });
  14137. var SliderParts = [
  14138. labelPart,
  14139. ledgePart,
  14140. redgePart,
  14141. tedgePart,
  14142. bedgePart,
  14143. tlEdgePart,
  14144. trEdgePart,
  14145. blEdgePart,
  14146. brEdgePart,
  14147. thumbPart,
  14148. spectrumPart
  14149. ];
  14150. var _sliderChangeEvent = 'slider.change.value';
  14151. var sliderChangeEvent = constant(_sliderChangeEvent);
  14152. var isTouchEvent = function (evt) {
  14153. return evt.type.indexOf('touch') !== -1;
  14154. };
  14155. var getEventSource = function (simulatedEvent) {
  14156. var evt = simulatedEvent.event().raw();
  14157. if (isTouchEvent(evt)) {
  14158. var touchEvent = evt;
  14159. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
  14160. return Position(t.clientX, t.clientY);
  14161. }) : Option.none();
  14162. } else {
  14163. var mouseEvent = evt;
  14164. return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
  14165. return Position(me.clientX, me.clientY);
  14166. }) : Option.none();
  14167. }
  14168. };
  14169. var t = 'top', r$1 = 'right', b = 'bottom', l = 'left';
  14170. var minX = function (detail) {
  14171. return detail.model.minX;
  14172. };
  14173. var minY = function (detail) {
  14174. return detail.model.minY;
  14175. };
  14176. var min1X = function (detail) {
  14177. return detail.model.minX - 1;
  14178. };
  14179. var min1Y = function (detail) {
  14180. return detail.model.minY - 1;
  14181. };
  14182. var maxX = function (detail) {
  14183. return detail.model.maxX;
  14184. };
  14185. var maxY = function (detail) {
  14186. return detail.model.maxY;
  14187. };
  14188. var max1X = function (detail) {
  14189. return detail.model.maxX + 1;
  14190. };
  14191. var max1Y = function (detail) {
  14192. return detail.model.maxY + 1;
  14193. };
  14194. var range$2 = function (detail, max, min) {
  14195. return max(detail) - min(detail);
  14196. };
  14197. var xRange = function (detail) {
  14198. return range$2(detail, maxX, minX);
  14199. };
  14200. var yRange = function (detail) {
  14201. return range$2(detail, maxY, minY);
  14202. };
  14203. var halfX = function (detail) {
  14204. return xRange(detail) / 2;
  14205. };
  14206. var halfY = function (detail) {
  14207. return yRange(detail) / 2;
  14208. };
  14209. var step = function (detail) {
  14210. return detail.stepSize;
  14211. };
  14212. var snap = function (detail) {
  14213. return detail.snapToGrid;
  14214. };
  14215. var snapStart = function (detail) {
  14216. return detail.snapStart;
  14217. };
  14218. var rounded = function (detail) {
  14219. return detail.rounded;
  14220. };
  14221. var hasEdge = function (detail, edgeName) {
  14222. return detail[edgeName + '-edge'] !== undefined;
  14223. };
  14224. var hasLEdge = function (detail) {
  14225. return hasEdge(detail, l);
  14226. };
  14227. var hasREdge = function (detail) {
  14228. return hasEdge(detail, r$1);
  14229. };
  14230. var hasTEdge = function (detail) {
  14231. return hasEdge(detail, t);
  14232. };
  14233. var hasBEdge = function (detail) {
  14234. return hasEdge(detail, b);
  14235. };
  14236. var currentValue = function (detail) {
  14237. return detail.model.value.get();
  14238. };
  14239. var xValue = function (x) {
  14240. return { x: constant(x) };
  14241. };
  14242. var yValue = function (y) {
  14243. return { y: constant(y) };
  14244. };
  14245. var xyValue = function (x, y) {
  14246. return {
  14247. x: constant(x),
  14248. y: constant(y)
  14249. };
  14250. };
  14251. var fireSliderChange = function (component, value) {
  14252. emitWith(component, sliderChangeEvent(), { value: value });
  14253. };
  14254. var setToTLEdgeXY = function (edge, detail) {
  14255. fireSliderChange(edge, xyValue(min1X(detail), min1Y(detail)));
  14256. };
  14257. var setToTEdge = function (edge, detail) {
  14258. fireSliderChange(edge, yValue(min1Y(detail)));
  14259. };
  14260. var setToTEdgeXY = function (edge, detail) {
  14261. fireSliderChange(edge, xyValue(halfX(detail), min1Y(detail)));
  14262. };
  14263. var setToTREdgeXY = function (edge, detail) {
  14264. fireSliderChange(edge, xyValue(max1X(detail), min1Y(detail)));
  14265. };
  14266. var setToREdge = function (edge, detail) {
  14267. fireSliderChange(edge, xValue(max1X(detail)));
  14268. };
  14269. var setToREdgeXY = function (edge, detail) {
  14270. fireSliderChange(edge, xyValue(max1X(detail), halfY(detail)));
  14271. };
  14272. var setToBREdgeXY = function (edge, detail) {
  14273. fireSliderChange(edge, xyValue(max1X(detail), max1Y(detail)));
  14274. };
  14275. var setToBEdge = function (edge, detail) {
  14276. fireSliderChange(edge, yValue(max1Y(detail)));
  14277. };
  14278. var setToBEdgeXY = function (edge, detail) {
  14279. fireSliderChange(edge, xyValue(halfX(detail), max1Y(detail)));
  14280. };
  14281. var setToBLEdgeXY = function (edge, detail) {
  14282. fireSliderChange(edge, xyValue(min1X(detail), max1Y(detail)));
  14283. };
  14284. var setToLEdge = function (edge, detail) {
  14285. fireSliderChange(edge, xValue(min1X(detail)));
  14286. };
  14287. var setToLEdgeXY = function (edge, detail) {
  14288. fireSliderChange(edge, xyValue(min1X(detail), halfY(detail)));
  14289. };
  14290. var reduceBy = function (value, min, max, step) {
  14291. if (value < min) {
  14292. return value;
  14293. } else if (value > max) {
  14294. return max;
  14295. } else if (value === min) {
  14296. return min - 1;
  14297. } else {
  14298. return Math.max(min, value - step);
  14299. }
  14300. };
  14301. var increaseBy = function (value, min, max, step) {
  14302. if (value > max) {
  14303. return value;
  14304. } else if (value < min) {
  14305. return min;
  14306. } else if (value === max) {
  14307. return max + 1;
  14308. } else {
  14309. return Math.min(max, value + step);
  14310. }
  14311. };
  14312. var capValue = function (value, min, max) {
  14313. return Math.max(min, Math.min(max, value));
  14314. };
  14315. var snapValueOf = function (value, min, max, step, snapStart) {
  14316. return snapStart.fold(function () {
  14317. var initValue = value - min;
  14318. var extraValue = Math.round(initValue / step) * step;
  14319. return capValue(min + extraValue, min - 1, max + 1);
  14320. }, function (start) {
  14321. var remainder = (value - start) % step;
  14322. var adjustment = Math.round(remainder / step);
  14323. var rawSteps = Math.floor((value - start) / step);
  14324. var maxSteps = Math.floor((max - start) / step);
  14325. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  14326. var r = start + numSteps * step;
  14327. return Math.max(start, r);
  14328. });
  14329. };
  14330. var findOffsetOf = function (value, min, max) {
  14331. return Math.min(max, Math.max(value, min)) - min;
  14332. };
  14333. var findValueOf = function (args) {
  14334. 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;
  14335. var capMin = hasMinEdge ? min - 1 : min;
  14336. var capMax = hasMaxEdge ? max + 1 : max;
  14337. if (value < minBound) {
  14338. return capMin;
  14339. } else if (value > maxBound) {
  14340. return capMax;
  14341. } else {
  14342. var offset = findOffsetOf(value, minBound, maxBound);
  14343. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  14344. if (snap && newValue >= min && newValue <= max) {
  14345. return snapValueOf(newValue, min, max, step, snapStart);
  14346. } else if (rounded) {
  14347. return Math.round(newValue);
  14348. } else {
  14349. return newValue;
  14350. }
  14351. }
  14352. };
  14353. var findOffsetOfValue = function (args) {
  14354. 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;
  14355. if (value < min) {
  14356. return hasMinEdge ? 0 : centerMinEdge;
  14357. } else if (value > max) {
  14358. return hasMaxEdge ? maxBound : centerMaxEdge;
  14359. } else {
  14360. return (value - min) / range * maxOffset;
  14361. }
  14362. };
  14363. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  14364. var getBounds$1 = function (component) {
  14365. return component.element().dom().getBoundingClientRect();
  14366. };
  14367. var getBoundsProperty = function (bounds, property) {
  14368. return bounds[property];
  14369. };
  14370. var getMinXBounds = function (component) {
  14371. var bounds = getBounds$1(component);
  14372. return getBoundsProperty(bounds, left);
  14373. };
  14374. var getMaxXBounds = function (component) {
  14375. var bounds = getBounds$1(component);
  14376. return getBoundsProperty(bounds, right);
  14377. };
  14378. var getMinYBounds = function (component) {
  14379. var bounds = getBounds$1(component);
  14380. return getBoundsProperty(bounds, top);
  14381. };
  14382. var getMaxYBounds = function (component) {
  14383. var bounds = getBounds$1(component);
  14384. return getBoundsProperty(bounds, bottom);
  14385. };
  14386. var getXScreenRange = function (component) {
  14387. var bounds = getBounds$1(component);
  14388. return getBoundsProperty(bounds, width);
  14389. };
  14390. var getYScreenRange = function (component) {
  14391. var bounds = getBounds$1(component);
  14392. return getBoundsProperty(bounds, height);
  14393. };
  14394. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  14395. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  14396. };
  14397. var getXCenterOffSetOf = function (component, spectrum) {
  14398. var componentBounds = getBounds$1(component);
  14399. var spectrumBounds = getBounds$1(spectrum);
  14400. var componentMinEdge = getBoundsProperty(componentBounds, left);
  14401. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  14402. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  14403. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14404. };
  14405. var getYCenterOffSetOf = function (component, spectrum) {
  14406. var componentBounds = getBounds$1(component);
  14407. var spectrumBounds = getBounds$1(spectrum);
  14408. var componentMinEdge = getBoundsProperty(componentBounds, top);
  14409. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  14410. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  14411. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  14412. };
  14413. var fireSliderChange$1 = function (spectrum, value) {
  14414. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14415. };
  14416. var sliderValue = function (x) {
  14417. return { x: constant(x) };
  14418. };
  14419. var findValueOfOffset = function (spectrum, detail, left) {
  14420. var args = {
  14421. min: minX(detail),
  14422. max: maxX(detail),
  14423. range: xRange(detail),
  14424. value: left,
  14425. step: step(detail),
  14426. snap: snap(detail),
  14427. snapStart: snapStart(detail),
  14428. rounded: rounded(detail),
  14429. hasMinEdge: hasLEdge(detail),
  14430. hasMaxEdge: hasREdge(detail),
  14431. minBound: getMinXBounds(spectrum),
  14432. maxBound: getMaxXBounds(spectrum),
  14433. screenRange: getXScreenRange(spectrum)
  14434. };
  14435. return findValueOf(args);
  14436. };
  14437. var setValueFrom = function (spectrum, detail, value) {
  14438. var xValue = findValueOfOffset(spectrum, detail, value);
  14439. var sliderVal = sliderValue(xValue);
  14440. fireSliderChange$1(spectrum, sliderVal);
  14441. return xValue;
  14442. };
  14443. var setToMin = function (spectrum, detail) {
  14444. var min = minX(detail);
  14445. fireSliderChange$1(spectrum, sliderValue(min));
  14446. };
  14447. var setToMax = function (spectrum, detail) {
  14448. var max = maxX(detail);
  14449. fireSliderChange$1(spectrum, sliderValue(max));
  14450. };
  14451. var moveBy = function (direction, spectrum, detail) {
  14452. var f = direction > 0 ? increaseBy : reduceBy;
  14453. var xValue = f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14454. fireSliderChange$1(spectrum, sliderValue(xValue));
  14455. return Option.some(xValue);
  14456. };
  14457. var handleMovement = function (direction) {
  14458. return function (spectrum, detail) {
  14459. return moveBy(direction, spectrum, detail).map(function () {
  14460. return true;
  14461. });
  14462. };
  14463. };
  14464. var getValueFromEvent = function (simulatedEvent) {
  14465. var pos = getEventSource(simulatedEvent);
  14466. return pos.map(function (p) {
  14467. return p.left();
  14468. });
  14469. };
  14470. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  14471. var minOffset = 0;
  14472. var maxOffset = getXScreenRange(spectrum);
  14473. var centerMinEdge = minEdge.bind(function (edge) {
  14474. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14475. }).getOr(minOffset);
  14476. var centerMaxEdge = maxEdge.bind(function (edge) {
  14477. return Option.some(getXCenterOffSetOf(edge, spectrum));
  14478. }).getOr(maxOffset);
  14479. var args = {
  14480. min: minX(detail),
  14481. max: maxX(detail),
  14482. range: xRange(detail),
  14483. value: value,
  14484. hasMinEdge: hasLEdge(detail),
  14485. hasMaxEdge: hasREdge(detail),
  14486. minBound: getMinXBounds(spectrum),
  14487. minOffset: minOffset,
  14488. maxBound: getMaxXBounds(spectrum),
  14489. maxOffset: maxOffset,
  14490. centerMinEdge: centerMinEdge,
  14491. centerMaxEdge: centerMaxEdge
  14492. };
  14493. return findOffsetOfValue(args);
  14494. };
  14495. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14496. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  14497. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  14498. };
  14499. var setPositionFromValue = function (slider, thumb, detail, edges) {
  14500. var value = currentValue(detail);
  14501. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14502. var thumbRadius = get$7(thumb.element()) / 2;
  14503. set$2(thumb.element(), 'left', pos - thumbRadius + 'px');
  14504. };
  14505. var onLeft = handleMovement(-1);
  14506. var onRight = handleMovement(1);
  14507. var onUp = Option.none;
  14508. var onDown = Option.none;
  14509. var edgeActions = {
  14510. 'top-left': Option.none(),
  14511. 'top': Option.none(),
  14512. 'top-right': Option.none(),
  14513. 'right': Option.some(setToREdge),
  14514. 'bottom-right': Option.none(),
  14515. 'bottom': Option.none(),
  14516. 'bottom-left': Option.none(),
  14517. 'left': Option.some(setToLEdge)
  14518. };
  14519. var HorizontalModel = /*#__PURE__*/Object.freeze({
  14520. __proto__: null,
  14521. setValueFrom: setValueFrom,
  14522. setToMin: setToMin,
  14523. setToMax: setToMax,
  14524. findValueOfOffset: findValueOfOffset,
  14525. getValueFromEvent: getValueFromEvent,
  14526. findPositionOfValue: findPositionOfValue,
  14527. setPositionFromValue: setPositionFromValue,
  14528. onLeft: onLeft,
  14529. onRight: onRight,
  14530. onUp: onUp,
  14531. onDown: onDown,
  14532. edgeActions: edgeActions
  14533. });
  14534. var fireSliderChange$2 = function (spectrum, value) {
  14535. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14536. };
  14537. var sliderValue$1 = function (y) {
  14538. return { y: constant(y) };
  14539. };
  14540. var findValueOfOffset$1 = function (spectrum, detail, top) {
  14541. var args = {
  14542. min: minY(detail),
  14543. max: maxY(detail),
  14544. range: yRange(detail),
  14545. value: top,
  14546. step: step(detail),
  14547. snap: snap(detail),
  14548. snapStart: snapStart(detail),
  14549. rounded: rounded(detail),
  14550. hasMinEdge: hasTEdge(detail),
  14551. hasMaxEdge: hasBEdge(detail),
  14552. minBound: getMinYBounds(spectrum),
  14553. maxBound: getMaxYBounds(spectrum),
  14554. screenRange: getYScreenRange(spectrum)
  14555. };
  14556. return findValueOf(args);
  14557. };
  14558. var setValueFrom$1 = function (spectrum, detail, value) {
  14559. var yValue = findValueOfOffset$1(spectrum, detail, value);
  14560. var sliderVal = sliderValue$1(yValue);
  14561. fireSliderChange$2(spectrum, sliderVal);
  14562. return yValue;
  14563. };
  14564. var setToMin$1 = function (spectrum, detail) {
  14565. var min = minY(detail);
  14566. fireSliderChange$2(spectrum, sliderValue$1(min));
  14567. };
  14568. var setToMax$1 = function (spectrum, detail) {
  14569. var max = maxY(detail);
  14570. fireSliderChange$2(spectrum, sliderValue$1(max));
  14571. };
  14572. var moveBy$1 = function (direction, spectrum, detail) {
  14573. var f = direction > 0 ? increaseBy : reduceBy;
  14574. var yValue = f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14575. fireSliderChange$2(spectrum, sliderValue$1(yValue));
  14576. return Option.some(yValue);
  14577. };
  14578. var handleMovement$1 = function (direction) {
  14579. return function (spectrum, detail) {
  14580. return moveBy$1(direction, spectrum, detail).map(function () {
  14581. return true;
  14582. });
  14583. };
  14584. };
  14585. var getValueFromEvent$1 = function (simulatedEvent) {
  14586. var pos = getEventSource(simulatedEvent);
  14587. return pos.map(function (p) {
  14588. return p.top();
  14589. });
  14590. };
  14591. var findOffsetOfValue$2 = function (spectrum, detail, value, minEdge, maxEdge) {
  14592. var minOffset = 0;
  14593. var maxOffset = getYScreenRange(spectrum);
  14594. var centerMinEdge = minEdge.bind(function (edge) {
  14595. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14596. }).getOr(minOffset);
  14597. var centerMaxEdge = maxEdge.bind(function (edge) {
  14598. return Option.some(getYCenterOffSetOf(edge, spectrum));
  14599. }).getOr(maxOffset);
  14600. var args = {
  14601. min: minY(detail),
  14602. max: maxY(detail),
  14603. range: yRange(detail),
  14604. value: value,
  14605. hasMinEdge: hasTEdge(detail),
  14606. hasMaxEdge: hasBEdge(detail),
  14607. minBound: getMinYBounds(spectrum),
  14608. minOffset: minOffset,
  14609. maxBound: getMaxYBounds(spectrum),
  14610. maxOffset: maxOffset,
  14611. centerMinEdge: centerMinEdge,
  14612. centerMaxEdge: centerMaxEdge
  14613. };
  14614. return findOffsetOfValue(args);
  14615. };
  14616. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  14617. var offset = findOffsetOfValue$2(spectrum, detail, value, minEdge, maxEdge);
  14618. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  14619. };
  14620. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  14621. var value = currentValue(detail);
  14622. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14623. var thumbRadius = get$6(thumb.element()) / 2;
  14624. set$2(thumb.element(), 'top', pos - thumbRadius + 'px');
  14625. };
  14626. var onLeft$1 = Option.none;
  14627. var onRight$1 = Option.none;
  14628. var onUp$1 = handleMovement$1(-1);
  14629. var onDown$1 = handleMovement$1(1);
  14630. var edgeActions$1 = {
  14631. 'top-left': Option.none(),
  14632. 'top': Option.some(setToTEdge),
  14633. 'top-right': Option.none(),
  14634. 'right': Option.none(),
  14635. 'bottom-right': Option.none(),
  14636. 'bottom': Option.some(setToBEdge),
  14637. 'bottom-left': Option.none(),
  14638. 'left': Option.none()
  14639. };
  14640. var VerticalModel = /*#__PURE__*/Object.freeze({
  14641. __proto__: null,
  14642. setValueFrom: setValueFrom$1,
  14643. setToMin: setToMin$1,
  14644. setToMax: setToMax$1,
  14645. findValueOfOffset: findValueOfOffset$1,
  14646. getValueFromEvent: getValueFromEvent$1,
  14647. findPositionOfValue: findPositionOfValue$1,
  14648. setPositionFromValue: setPositionFromValue$1,
  14649. onLeft: onLeft$1,
  14650. onRight: onRight$1,
  14651. onUp: onUp$1,
  14652. onDown: onDown$1,
  14653. edgeActions: edgeActions$1
  14654. });
  14655. var fireSliderChange$3 = function (spectrum, value) {
  14656. emitWith(spectrum, sliderChangeEvent(), { value: value });
  14657. };
  14658. var sliderValue$2 = function (x, y) {
  14659. return {
  14660. x: constant(x),
  14661. y: constant(y)
  14662. };
  14663. };
  14664. var setValueFrom$2 = function (spectrum, detail, value) {
  14665. var xValue = findValueOfOffset(spectrum, detail, value.left());
  14666. var yValue = findValueOfOffset$1(spectrum, detail, value.top());
  14667. var val = sliderValue$2(xValue, yValue);
  14668. fireSliderChange$3(spectrum, val);
  14669. return val;
  14670. };
  14671. var moveBy$2 = function (direction, isVerticalMovement, spectrum, detail) {
  14672. var f = direction > 0 ? increaseBy : reduceBy;
  14673. var xValue = isVerticalMovement ? currentValue(detail).x() : f(currentValue(detail).x(), minX(detail), maxX(detail), step(detail));
  14674. var yValue = !isVerticalMovement ? currentValue(detail).y() : f(currentValue(detail).y(), minY(detail), maxY(detail), step(detail));
  14675. fireSliderChange$3(spectrum, sliderValue$2(xValue, yValue));
  14676. return Option.some(xValue);
  14677. };
  14678. var handleMovement$2 = function (direction, isVerticalMovement) {
  14679. return function (spectrum, detail) {
  14680. return moveBy$2(direction, isVerticalMovement, spectrum, detail).map(function () {
  14681. return true;
  14682. });
  14683. };
  14684. };
  14685. var setToMin$2 = function (spectrum, detail) {
  14686. var mX = minX(detail);
  14687. var mY = minY(detail);
  14688. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14689. };
  14690. var setToMax$2 = function (spectrum, detail) {
  14691. var mX = maxX(detail);
  14692. var mY = maxY(detail);
  14693. fireSliderChange$3(spectrum, sliderValue$2(mX, mY));
  14694. };
  14695. var getValueFromEvent$2 = function (simulatedEvent) {
  14696. return getEventSource(simulatedEvent);
  14697. };
  14698. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  14699. var value = currentValue(detail);
  14700. var xPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.x(), edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  14701. var yPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.y(), edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  14702. var thumbXRadius = get$7(thumb.element()) / 2;
  14703. var thumbYRadius = get$6(thumb.element()) / 2;
  14704. set$2(thumb.element(), 'left', xPos - thumbXRadius + 'px');
  14705. set$2(thumb.element(), 'top', yPos - thumbYRadius + 'px');
  14706. };
  14707. var onLeft$2 = handleMovement$2(-1, false);
  14708. var onRight$2 = handleMovement$2(1, false);
  14709. var onUp$2 = handleMovement$2(-1, true);
  14710. var onDown$2 = handleMovement$2(1, true);
  14711. var edgeActions$2 = {
  14712. 'top-left': Option.some(setToTLEdgeXY),
  14713. 'top': Option.some(setToTEdgeXY),
  14714. 'top-right': Option.some(setToTREdgeXY),
  14715. 'right': Option.some(setToREdgeXY),
  14716. 'bottom-right': Option.some(setToBREdgeXY),
  14717. 'bottom': Option.some(setToBEdgeXY),
  14718. 'bottom-left': Option.some(setToBLEdgeXY),
  14719. 'left': Option.some(setToLEdgeXY)
  14720. };
  14721. var TwoDModel = /*#__PURE__*/Object.freeze({
  14722. __proto__: null,
  14723. setValueFrom: setValueFrom$2,
  14724. setToMin: setToMin$2,
  14725. setToMax: setToMax$2,
  14726. getValueFromEvent: getValueFromEvent$2,
  14727. setPositionFromValue: setPositionFromValue$2,
  14728. onLeft: onLeft$2,
  14729. onRight: onRight$2,
  14730. onUp: onUp$2,
  14731. onDown: onDown$2,
  14732. edgeActions: edgeActions$2
  14733. });
  14734. var SliderSchema = [
  14735. defaulted$1('stepSize', 1),
  14736. defaulted$1('onChange', noop),
  14737. defaulted$1('onChoose', noop),
  14738. defaulted$1('onInit', noop),
  14739. defaulted$1('onDragStart', noop),
  14740. defaulted$1('onDragEnd', noop),
  14741. defaulted$1('snapToGrid', false),
  14742. defaulted$1('rounded', true),
  14743. option('snapStart'),
  14744. strictOf('model', choose$1('mode', {
  14745. x: [
  14746. defaulted$1('minX', 0),
  14747. defaulted$1('maxX', 100),
  14748. state$1('value', function (spec) {
  14749. return Cell(spec.mode.minX);
  14750. }),
  14751. strict$1('getInitialValue'),
  14752. output('manager', HorizontalModel)
  14753. ],
  14754. y: [
  14755. defaulted$1('minY', 0),
  14756. defaulted$1('maxY', 100),
  14757. state$1('value', function (spec) {
  14758. return Cell(spec.mode.minY);
  14759. }),
  14760. strict$1('getInitialValue'),
  14761. output('manager', VerticalModel)
  14762. ],
  14763. xy: [
  14764. defaulted$1('minX', 0),
  14765. defaulted$1('maxX', 100),
  14766. defaulted$1('minY', 0),
  14767. defaulted$1('maxY', 100),
  14768. state$1('value', function (spec) {
  14769. return Cell({
  14770. x: constant(spec.mode.minX),
  14771. y: constant(spec.mode.minY)
  14772. });
  14773. }),
  14774. strict$1('getInitialValue'),
  14775. output('manager', TwoDModel)
  14776. ]
  14777. })),
  14778. field$1('sliderBehaviours', [
  14779. Keying,
  14780. Representing
  14781. ]),
  14782. state$1('mouseIsDown', function () {
  14783. return Cell(false);
  14784. })
  14785. ];
  14786. var sketch = function (detail, components, _spec, _externals) {
  14787. var _a;
  14788. var getThumb = function (component) {
  14789. return getPartOrDie(component, detail, 'thumb');
  14790. };
  14791. var getSpectrum = function (component) {
  14792. return getPartOrDie(component, detail, 'spectrum');
  14793. };
  14794. var getLeftEdge = function (component) {
  14795. return getPart(component, detail, 'left-edge');
  14796. };
  14797. var getRightEdge = function (component) {
  14798. return getPart(component, detail, 'right-edge');
  14799. };
  14800. var getTopEdge = function (component) {
  14801. return getPart(component, detail, 'top-edge');
  14802. };
  14803. var getBottomEdge = function (component) {
  14804. return getPart(component, detail, 'bottom-edge');
  14805. };
  14806. var modelDetail = detail.model;
  14807. var model = modelDetail.manager;
  14808. var refresh = function (slider, thumb) {
  14809. model.setPositionFromValue(slider, thumb, detail, {
  14810. getLeftEdge: getLeftEdge,
  14811. getRightEdge: getRightEdge,
  14812. getTopEdge: getTopEdge,
  14813. getBottomEdge: getBottomEdge,
  14814. getSpectrum: getSpectrum
  14815. });
  14816. };
  14817. var changeValue = function (slider, newValue) {
  14818. modelDetail.value.set(newValue);
  14819. var thumb = getThumb(slider);
  14820. refresh(slider, thumb);
  14821. detail.onChange(slider, thumb, newValue);
  14822. return Option.some(true);
  14823. };
  14824. var resetToMin = function (slider) {
  14825. model.setToMin(slider, detail);
  14826. };
  14827. var resetToMax = function (slider) {
  14828. model.setToMax(slider, detail);
  14829. };
  14830. var choose = function (slider) {
  14831. var fireOnChoose = function () {
  14832. getPart(slider, detail, 'thumb').each(function (thumb) {
  14833. var value = modelDetail.value.get();
  14834. detail.onChoose(slider, thumb, value);
  14835. });
  14836. };
  14837. var wasDown = detail.mouseIsDown.get();
  14838. detail.mouseIsDown.set(false);
  14839. if (wasDown) {
  14840. fireOnChoose();
  14841. }
  14842. };
  14843. var onDragStart = function (slider, simulatedEvent) {
  14844. simulatedEvent.stop();
  14845. detail.mouseIsDown.set(true);
  14846. detail.onDragStart(slider, getThumb(slider));
  14847. };
  14848. var onDragEnd = function (slider, simulatedEvent) {
  14849. simulatedEvent.stop();
  14850. detail.onDragEnd(slider, getThumb(slider));
  14851. choose(slider);
  14852. };
  14853. return {
  14854. uid: detail.uid,
  14855. dom: detail.dom,
  14856. components: components,
  14857. behaviours: augment(detail.sliderBehaviours, [
  14858. Keying.config({
  14859. mode: 'special',
  14860. focusIn: function (slider) {
  14861. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
  14862. }
  14863. }),
  14864. Representing.config({
  14865. store: {
  14866. mode: 'manual',
  14867. getValue: function (_) {
  14868. return modelDetail.value.get();
  14869. }
  14870. }
  14871. }),
  14872. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  14873. ]),
  14874. events: derive([
  14875. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  14876. changeValue(slider, simulatedEvent.event().value());
  14877. }),
  14878. runOnAttached(function (slider, _simulatedEvent) {
  14879. var getInitial = modelDetail.getInitialValue();
  14880. modelDetail.value.set(getInitial);
  14881. var thumb = getThumb(slider);
  14882. refresh(slider, thumb);
  14883. var spectrum = getSpectrum(slider);
  14884. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  14885. }),
  14886. run(touchstart(), onDragStart),
  14887. run(touchend(), onDragEnd),
  14888. run(mousedown(), onDragStart),
  14889. run(mouseup(), onDragEnd)
  14890. ]),
  14891. apis: {
  14892. resetToMin: resetToMin,
  14893. resetToMax: resetToMax,
  14894. changeValue: changeValue,
  14895. refresh: refresh
  14896. },
  14897. domModification: { styles: { position: 'relative' } }
  14898. };
  14899. };
  14900. var Slider = composite$1({
  14901. name: 'Slider',
  14902. configFields: SliderSchema,
  14903. partFields: SliderParts,
  14904. factory: sketch,
  14905. apis: {
  14906. resetToMin: function (apis, slider) {
  14907. apis.resetToMin(slider);
  14908. },
  14909. resetToMax: function (apis, slider) {
  14910. apis.resetToMax(slider);
  14911. },
  14912. refresh: function (apis, slider) {
  14913. apis.refresh(slider);
  14914. }
  14915. }
  14916. });
  14917. var sliderFactory = function (translate, getClass) {
  14918. var spectrum = Slider.parts().spectrum({
  14919. dom: {
  14920. tag: 'div',
  14921. classes: [getClass('hue-slider-spectrum')],
  14922. attributes: { role: 'presentation' }
  14923. }
  14924. });
  14925. var thumb = Slider.parts().thumb({
  14926. dom: {
  14927. tag: 'div',
  14928. classes: [getClass('hue-slider-thumb')],
  14929. attributes: { role: 'presentation' }
  14930. }
  14931. });
  14932. return Slider.sketch({
  14933. dom: {
  14934. tag: 'div',
  14935. classes: [getClass('hue-slider')],
  14936. attributes: { role: 'presentation' }
  14937. },
  14938. rounded: false,
  14939. model: {
  14940. mode: 'y',
  14941. getInitialValue: constant({ y: constant(0) })
  14942. },
  14943. components: [
  14944. spectrum,
  14945. thumb
  14946. ],
  14947. sliderBehaviours: derive$1([Focusing.config({})]),
  14948. onChange: function (slider, _thumb, value) {
  14949. emitWith(slider, sliderUpdate, { value: value });
  14950. }
  14951. });
  14952. };
  14953. var owner$3 = 'form';
  14954. var schema$h = [field$1('formBehaviours', [Representing])];
  14955. var getPartName = function (name) {
  14956. return '<alloy.field.' + name + '>';
  14957. };
  14958. var sketch$1 = function (fSpec) {
  14959. var parts = function () {
  14960. var record = [];
  14961. var field = function (name, config) {
  14962. record.push(name);
  14963. return generateOne(owner$3, getPartName(name), config);
  14964. };
  14965. return {
  14966. field: field,
  14967. record: function () {
  14968. return record;
  14969. }
  14970. };
  14971. }();
  14972. var spec = fSpec(parts);
  14973. var partNames = parts.record();
  14974. var fieldParts = map(partNames, function (n) {
  14975. return required({
  14976. name: n,
  14977. pname: getPartName(n)
  14978. });
  14979. });
  14980. return composite(owner$3, schema$h, fieldParts, make$4, spec);
  14981. };
  14982. var toResult$1 = function (o, e) {
  14983. return o.fold(function () {
  14984. return Result.error(e);
  14985. }, Result.value);
  14986. };
  14987. var make$4 = function (detail, components) {
  14988. return {
  14989. uid: detail.uid,
  14990. dom: detail.dom,
  14991. components: components,
  14992. behaviours: augment(detail.formBehaviours, [Representing.config({
  14993. store: {
  14994. mode: 'manual',
  14995. getValue: function (form) {
  14996. var resPs = getAllParts(form, detail);
  14997. return map$1(resPs, function (resPThunk, pName) {
  14998. return resPThunk().bind(function (v) {
  14999. var opt = Composing.getCurrent(v);
  15000. return toResult$1(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element())));
  15001. }).map(Representing.getValue);
  15002. });
  15003. },
  15004. setValue: function (form, values) {
  15005. each$1(values, function (newValue, key) {
  15006. getPart(form, detail, key).each(function (wrapper) {
  15007. Composing.getCurrent(wrapper).each(function (field) {
  15008. Representing.setValue(field, newValue);
  15009. });
  15010. });
  15011. });
  15012. }
  15013. }
  15014. })]),
  15015. apis: {
  15016. getField: function (form, key) {
  15017. return getPart(form, detail, key).bind(Composing.getCurrent);
  15018. }
  15019. }
  15020. };
  15021. };
  15022. var Form = {
  15023. getField: makeApi(function (apis, component, key) {
  15024. return apis.getField(component, key);
  15025. }),
  15026. sketch: sketch$1
  15027. };
  15028. var validInput = generate$1('valid-input');
  15029. var invalidInput = generate$1('invalid-input');
  15030. var validatingInput = generate$1('validating-input');
  15031. var translatePrefix = 'colorcustom.rgb.';
  15032. var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) {
  15033. var invalidation = function (label, isValid) {
  15034. return Invalidating.config({
  15035. invalidClass: getClass('invalid'),
  15036. notify: {
  15037. onValidate: function (comp) {
  15038. emitWith(comp, validatingInput, { type: label });
  15039. },
  15040. onValid: function (comp) {
  15041. emitWith(comp, validInput, {
  15042. type: label,
  15043. value: Representing.getValue(comp)
  15044. });
  15045. },
  15046. onInvalid: function (comp) {
  15047. emitWith(comp, invalidInput, {
  15048. type: label,
  15049. value: Representing.getValue(comp)
  15050. });
  15051. }
  15052. },
  15053. validator: {
  15054. validate: function (comp) {
  15055. var value = Representing.getValue(comp);
  15056. var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid'));
  15057. return Future.pure(res);
  15058. },
  15059. validateOnLoad: false
  15060. }
  15061. });
  15062. };
  15063. var renderTextField = function (isValid, name, label, description, data) {
  15064. var helptext = translate(translatePrefix + 'range');
  15065. var pLabel = FormField.parts().label({
  15066. dom: {
  15067. tag: 'label',
  15068. innerHtml: label,
  15069. attributes: { 'aria-label': description }
  15070. }
  15071. });
  15072. var pField = FormField.parts().field({
  15073. data: data,
  15074. factory: Input,
  15075. inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}),
  15076. inputClasses: [getClass('textfield')],
  15077. inputBehaviours: derive$1([
  15078. invalidation(name, isValid),
  15079. Tabstopping.config({})
  15080. ]),
  15081. onSetValue: function (input) {
  15082. if (Invalidating.isInvalid(input)) {
  15083. var run = Invalidating.run(input);
  15084. run.get(noop);
  15085. }
  15086. }
  15087. });
  15088. var comps = [
  15089. pLabel,
  15090. pField
  15091. ];
  15092. var concats = name !== 'hex' ? [FormField.parts()['aria-descriptor']({ text: helptext })] : [];
  15093. var components = comps.concat(concats);
  15094. return {
  15095. dom: {
  15096. tag: 'div',
  15097. attributes: { role: 'presentation' }
  15098. },
  15099. components: components
  15100. };
  15101. };
  15102. var copyRgbToHex = function (form, rgba) {
  15103. var hex = fromRgba(rgba);
  15104. Form.getField(form, 'hex').each(function (hexField) {
  15105. if (!Focusing.isFocused(hexField)) {
  15106. Representing.setValue(form, { hex: hex.value });
  15107. }
  15108. });
  15109. return hex;
  15110. };
  15111. var copyRgbToForm = function (form, rgb) {
  15112. var red = rgb.red;
  15113. var green = rgb.green;
  15114. var blue = rgb.blue;
  15115. Representing.setValue(form, {
  15116. red: red,
  15117. green: green,
  15118. blue: blue
  15119. });
  15120. };
  15121. var memPreview = record({
  15122. dom: {
  15123. tag: 'div',
  15124. classes: [getClass('rgba-preview')],
  15125. styles: { 'background-color': 'white' },
  15126. attributes: { role: 'presentation' }
  15127. }
  15128. });
  15129. var updatePreview = function (anyInSystem, hex) {
  15130. memPreview.getOpt(anyInSystem).each(function (preview) {
  15131. set$2(preview.element(), 'background-color', '#' + hex.value);
  15132. });
  15133. };
  15134. var factory = function () {
  15135. var state = {
  15136. red: Cell(Option.some(255)),
  15137. green: Cell(Option.some(255)),
  15138. blue: Cell(Option.some(255)),
  15139. hex: Cell(Option.some('ffffff'))
  15140. };
  15141. var copyHexToRgb = function (form, hex) {
  15142. var rgb = fromHex(hex);
  15143. copyRgbToForm(form, rgb);
  15144. setValueRgb(rgb);
  15145. };
  15146. var get = function (prop) {
  15147. return state[prop].get();
  15148. };
  15149. var set = function (prop, value) {
  15150. state[prop].set(value);
  15151. };
  15152. var getValueRgb = function () {
  15153. return get('red').bind(function (red) {
  15154. return get('green').bind(function (green) {
  15155. return get('blue').map(function (blue) {
  15156. return rgbaColour(red, green, blue, 1);
  15157. });
  15158. });
  15159. });
  15160. };
  15161. var setValueRgb = function (rgb) {
  15162. var red = rgb.red;
  15163. var green = rgb.green;
  15164. var blue = rgb.blue;
  15165. set('red', Option.some(red));
  15166. set('green', Option.some(green));
  15167. set('blue', Option.some(blue));
  15168. };
  15169. var onInvalidInput = function (form, simulatedEvent) {
  15170. var data = simulatedEvent.event();
  15171. if (data.type() !== 'hex') {
  15172. set(data.type(), Option.none());
  15173. } else {
  15174. onInvalidHexx(form);
  15175. }
  15176. };
  15177. var onValidHex = function (form, value) {
  15178. onValidHexx(form);
  15179. var hex = hexColour(value);
  15180. set('hex', Option.some(value));
  15181. var rgb = fromHex(hex);
  15182. copyRgbToForm(form, rgb);
  15183. setValueRgb(rgb);
  15184. emitWith(form, fieldsUpdate, { hex: hex });
  15185. updatePreview(form, hex);
  15186. };
  15187. var onValidRgb = function (form, prop, value) {
  15188. var val = parseInt(value, 10);
  15189. set(prop, Option.some(val));
  15190. getValueRgb().each(function (rgb) {
  15191. var hex = copyRgbToHex(form, rgb);
  15192. updatePreview(form, hex);
  15193. });
  15194. };
  15195. var isHexInputEvent = function (data) {
  15196. return data.type() === 'hex';
  15197. };
  15198. var onValidInput = function (form, simulatedEvent) {
  15199. var data = simulatedEvent.event();
  15200. if (isHexInputEvent(data)) {
  15201. onValidHex(form, data.value());
  15202. } else {
  15203. onValidRgb(form, data.type(), data.value());
  15204. }
  15205. };
  15206. var formPartStrings = function (key) {
  15207. return {
  15208. label: translate(translatePrefix + key + '.label'),
  15209. description: translate(translatePrefix + key + '.description')
  15210. };
  15211. };
  15212. var redStrings = formPartStrings('red');
  15213. var greenStrings = formPartStrings('green');
  15214. var blueStrings = formPartStrings('blue');
  15215. var hexStrings = formPartStrings('hex');
  15216. return deepMerge(Form.sketch(function (parts) {
  15217. return {
  15218. dom: {
  15219. tag: 'form',
  15220. classes: [getClass('rgb-form')],
  15221. attributes: { 'aria-label': translate('aria.color.picker') }
  15222. },
  15223. components: [
  15224. parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))),
  15225. parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))),
  15226. parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))),
  15227. parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))),
  15228. memPreview.asSpec()
  15229. ],
  15230. formBehaviours: derive$1([
  15231. Invalidating.config({ invalidClass: getClass('form-invalid') }),
  15232. config('rgb-form-events', [
  15233. run(validInput, onValidInput),
  15234. run(invalidInput, onInvalidInput),
  15235. run(validatingInput, onInvalidInput)
  15236. ])
  15237. ])
  15238. };
  15239. }), {
  15240. apis: {
  15241. updateHex: function (form, hex) {
  15242. Representing.setValue(form, { hex: hex.value });
  15243. copyHexToRgb(form, hex);
  15244. updatePreview(form, hex);
  15245. }
  15246. }
  15247. });
  15248. };
  15249. var rgbFormSketcher = single$2({
  15250. factory: factory,
  15251. name: 'RgbForm',
  15252. configFields: [],
  15253. apis: {
  15254. updateHex: function (apis, form, hex) {
  15255. apis.updateHex(form, hex);
  15256. }
  15257. },
  15258. extraApis: {}
  15259. });
  15260. return rgbFormSketcher;
  15261. };
  15262. var paletteFactory = function (_translate, getClass) {
  15263. var spectrumPart = Slider.parts().spectrum({
  15264. dom: {
  15265. tag: 'canvas',
  15266. attributes: { role: 'presentation' },
  15267. classes: [getClass('sv-palette-spectrum')]
  15268. }
  15269. });
  15270. var thumbPart = Slider.parts().thumb({
  15271. dom: {
  15272. tag: 'div',
  15273. attributes: { role: 'presentation' },
  15274. classes: [getClass('sv-palette-thumb')],
  15275. innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>'
  15276. }
  15277. });
  15278. var setColour = function (canvas, rgba) {
  15279. var width = canvas.width, height = canvas.height;
  15280. var ctx = canvas.getContext('2d');
  15281. if (ctx === null) {
  15282. return;
  15283. }
  15284. ctx.fillStyle = rgba;
  15285. ctx.fillRect(0, 0, width, height);
  15286. var grdWhite = ctx.createLinearGradient(0, 0, width, 0);
  15287. grdWhite.addColorStop(0, 'rgba(255,255,255,1)');
  15288. grdWhite.addColorStop(1, 'rgba(255,255,255,0)');
  15289. ctx.fillStyle = grdWhite;
  15290. ctx.fillRect(0, 0, width, height);
  15291. var grdBlack = ctx.createLinearGradient(0, 0, 0, height);
  15292. grdBlack.addColorStop(0, 'rgba(0,0,0,0)');
  15293. grdBlack.addColorStop(1, 'rgba(0,0,0,1)');
  15294. ctx.fillStyle = grdBlack;
  15295. ctx.fillRect(0, 0, width, height);
  15296. };
  15297. var setSliderColour = function (slider, rgba) {
  15298. var canvas = slider.components()[0].element().dom();
  15299. setColour(canvas, toString(rgba));
  15300. };
  15301. var factory = function (_detail) {
  15302. var getInitialValue = constant({
  15303. x: constant(0),
  15304. y: constant(0)
  15305. });
  15306. var onChange = function (slider, _thumb, value) {
  15307. emitWith(slider, paletteUpdate, { value: value });
  15308. };
  15309. var onInit = function (_slider, _thumb, spectrum, _value) {
  15310. setColour(spectrum.element().dom(), toString(red));
  15311. };
  15312. var sliderBehaviours = derive$1([
  15313. Composing.config({ find: Option.some }),
  15314. Focusing.config({})
  15315. ]);
  15316. return Slider.sketch({
  15317. dom: {
  15318. tag: 'div',
  15319. attributes: { role: 'presentation' },
  15320. classes: [getClass('sv-palette')]
  15321. },
  15322. model: {
  15323. mode: 'xy',
  15324. getInitialValue: getInitialValue
  15325. },
  15326. rounded: false,
  15327. components: [
  15328. spectrumPart,
  15329. thumbPart
  15330. ],
  15331. onChange: onChange,
  15332. onInit: onInit,
  15333. sliderBehaviours: sliderBehaviours
  15334. });
  15335. };
  15336. var saturationBrightnessPaletteSketcher = single$2({
  15337. factory: factory,
  15338. name: 'SaturationBrightnessPalette',
  15339. configFields: [],
  15340. apis: {
  15341. setRgba: function (_apis, slider, rgba) {
  15342. setSliderColour(slider, rgba);
  15343. }
  15344. },
  15345. extraApis: {}
  15346. });
  15347. return saturationBrightnessPaletteSketcher;
  15348. };
  15349. var makeFactory = function (translate, getClass) {
  15350. var factory = function (detail) {
  15351. var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex);
  15352. var sbPalette = paletteFactory(translate, getClass);
  15353. var state = { paletteRgba: Cell(red) };
  15354. var memPalette = record(sbPalette.sketch({}));
  15355. var memRgb = record(rgbForm.sketch({}));
  15356. var updatePalette = function (anyInSystem, hex) {
  15357. memPalette.getOpt(anyInSystem).each(function (palette) {
  15358. var rgba = fromHex(hex);
  15359. state.paletteRgba.set(rgba);
  15360. sbPalette.setRgba(palette, rgba);
  15361. });
  15362. };
  15363. var updateFields = function (anyInSystem, hex) {
  15364. memRgb.getOpt(anyInSystem).each(function (form) {
  15365. rgbForm.updateHex(form, hex);
  15366. });
  15367. };
  15368. var runUpdates = function (anyInSystem, hex, updates) {
  15369. each(updates, function (update) {
  15370. update(anyInSystem, hex);
  15371. });
  15372. };
  15373. var paletteUpdates = function () {
  15374. var updates = [updateFields];
  15375. return function (form, simulatedEvent) {
  15376. var value = simulatedEvent.event().value();
  15377. var oldRgb = state.paletteRgba.get();
  15378. var hsvColour$1 = fromRgb(oldRgb);
  15379. var newHsvColour = hsvColour(hsvColour$1.hue, value.x(), 100 - value.y());
  15380. var rgb = fromHsv(newHsvColour);
  15381. var nuHex = fromRgba(rgb);
  15382. runUpdates(form, nuHex, updates);
  15383. };
  15384. };
  15385. var sliderUpdates = function () {
  15386. var updates = [
  15387. updatePalette,
  15388. updateFields
  15389. ];
  15390. return function (form, simulatedEvent) {
  15391. var value = simulatedEvent.event().value();
  15392. var hex = calcHex(value.y());
  15393. runUpdates(form, hex, updates);
  15394. };
  15395. };
  15396. return {
  15397. uid: detail.uid,
  15398. dom: detail.dom,
  15399. components: [
  15400. memPalette.asSpec(),
  15401. sliderFactory(translate, getClass),
  15402. memRgb.asSpec()
  15403. ],
  15404. behaviours: derive$1([
  15405. config('colour-picker-events', [
  15406. run(paletteUpdate, paletteUpdates()),
  15407. run(sliderUpdate, sliderUpdates())
  15408. ]),
  15409. Composing.config({
  15410. find: function (comp) {
  15411. return memRgb.getOpt(comp);
  15412. }
  15413. }),
  15414. Keying.config({ mode: 'acyclic' })
  15415. ])
  15416. };
  15417. };
  15418. var colourPickerSketcher = single$2({
  15419. name: 'ColourPicker',
  15420. configFields: [
  15421. strict$1('dom'),
  15422. defaulted$1('onValidHex', noop),
  15423. defaulted$1('onInvalidHex', noop)
  15424. ],
  15425. factory: factory
  15426. });
  15427. return colourPickerSketcher;
  15428. };
  15429. var self$1 = function () {
  15430. return Composing.config({ find: Option.some });
  15431. };
  15432. var memento = function (mem) {
  15433. return Composing.config({ find: mem.getOpt });
  15434. };
  15435. var childAt = function (index) {
  15436. return Composing.config({
  15437. find: function (comp) {
  15438. return child(comp.element(), index).bind(function (element) {
  15439. return comp.getSystem().getByDom(element).toOption();
  15440. });
  15441. }
  15442. });
  15443. };
  15444. var ComposingConfigs = {
  15445. self: self$1,
  15446. memento: memento,
  15447. childAt: childAt
  15448. };
  15449. var english = {
  15450. 'colorcustom.rgb.red.label': 'R',
  15451. 'colorcustom.rgb.red.description': 'Red component',
  15452. 'colorcustom.rgb.green.label': 'G',
  15453. 'colorcustom.rgb.green.description': 'Green component',
  15454. 'colorcustom.rgb.blue.label': 'B',
  15455. 'colorcustom.rgb.blue.description': 'Blue component',
  15456. 'colorcustom.rgb.hex.label': '#',
  15457. 'colorcustom.rgb.hex.description': 'Hex color code',
  15458. 'colorcustom.rgb.range': 'Range 0 to 255',
  15459. 'colorcustom.sb.saturation': 'Saturation',
  15460. 'colorcustom.sb.brightness': 'Brightness',
  15461. 'colorcustom.sb.picker': 'Saturation and Brightness Picker',
  15462. 'colorcustom.sb.palette': 'Saturation and Brightness Palette',
  15463. 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes',
  15464. 'colorcustom.hue.hue': 'Hue',
  15465. 'colorcustom.hue.slider': 'Hue Slider',
  15466. 'colorcustom.hue.palette': 'Hue Palette',
  15467. 'colorcustom.hue.instructions': 'Use arrow keys to select a hue',
  15468. 'aria.color.picker': 'Color Picker',
  15469. 'aria.input.invalid': 'Invalid input'
  15470. };
  15471. var getEnglishText = function (key) {
  15472. return english[key];
  15473. };
  15474. var translate$1 = function (key) {
  15475. return getEnglishText(key);
  15476. };
  15477. var renderColorPicker = function (_spec) {
  15478. var getClass = function (key) {
  15479. return 'tox-' + key;
  15480. };
  15481. var colourPickerFactory = makeFactory(translate$1, getClass);
  15482. var onValidHex = function (form) {
  15483. emitWith(form, formActionEvent, {
  15484. name: 'hex-valid',
  15485. value: true
  15486. });
  15487. };
  15488. var onInvalidHex = function (form) {
  15489. emitWith(form, formActionEvent, {
  15490. name: 'hex-valid',
  15491. value: false
  15492. });
  15493. };
  15494. var memPicker = record(colourPickerFactory.sketch({
  15495. dom: {
  15496. tag: 'div',
  15497. classes: [getClass('color-picker-container')],
  15498. attributes: { role: 'presentation' }
  15499. },
  15500. onValidHex: onValidHex,
  15501. onInvalidHex: onInvalidHex
  15502. }));
  15503. return {
  15504. dom: { tag: 'div' },
  15505. components: [memPicker.asSpec()],
  15506. behaviours: derive$1([
  15507. Representing.config({
  15508. store: {
  15509. mode: 'manual',
  15510. getValue: function (comp) {
  15511. var picker = memPicker.get(comp);
  15512. var optRgbForm = Composing.getCurrent(picker);
  15513. var optHex = optRgbForm.bind(function (rgbForm) {
  15514. var formValues = Representing.getValue(rgbForm);
  15515. return formValues.hex;
  15516. });
  15517. return optHex.map(function (hex) {
  15518. return '#' + hex;
  15519. }).getOr('');
  15520. },
  15521. setValue: function (comp, newValue) {
  15522. var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/;
  15523. var m = pattern.exec(newValue);
  15524. var picker = memPicker.get(comp);
  15525. var optRgbForm = Composing.getCurrent(picker);
  15526. optRgbForm.fold(function () {
  15527. domGlobals.console.log('Can not find form');
  15528. }, function (rgbForm) {
  15529. Representing.setValue(rgbForm, { hex: Option.from(m[1]).getOr('') });
  15530. Form.getField(rgbForm, 'hex').each(function (hexField) {
  15531. emit(hexField, input());
  15532. });
  15533. });
  15534. }
  15535. }
  15536. }),
  15537. ComposingConfigs.self()
  15538. ])
  15539. };
  15540. };
  15541. var global$a = tinymce.util.Tools.resolve('tinymce.Resource');
  15542. var isOldCustomEditor = function (spec) {
  15543. return Object.prototype.hasOwnProperty.call(spec, 'init');
  15544. };
  15545. var renderCustomEditor = function (spec) {
  15546. var editorApi = Cell(Option.none());
  15547. var memReplaced = record({ dom: { tag: spec.tag } });
  15548. var initialValue = Cell(Option.none());
  15549. return {
  15550. dom: {
  15551. tag: 'div',
  15552. classes: ['tox-custom-editor']
  15553. },
  15554. behaviours: derive$1([
  15555. config('editor-foo-events', [runOnAttached(function (component) {
  15556. memReplaced.getOpt(component).each(function (ta) {
  15557. (isOldCustomEditor(spec) ? spec.init(ta.element().dom()) : global$a.load(spec.scriptId, spec.scriptUrl).then(function (init) {
  15558. return init(ta.element().dom(), spec.settings);
  15559. })).then(function (ea) {
  15560. initialValue.get().each(function (cvalue) {
  15561. ea.setValue(cvalue);
  15562. });
  15563. initialValue.set(Option.none());
  15564. editorApi.set(Option.some(ea));
  15565. });
  15566. });
  15567. })]),
  15568. Representing.config({
  15569. store: {
  15570. mode: 'manual',
  15571. getValue: function () {
  15572. return editorApi.get().fold(function () {
  15573. return initialValue.get().getOr('');
  15574. }, function (ed) {
  15575. return ed.getValue();
  15576. });
  15577. },
  15578. setValue: function (component, value) {
  15579. editorApi.get().fold(function () {
  15580. initialValue.set(Option.some(value));
  15581. }, function (ed) {
  15582. return ed.setValue(value);
  15583. });
  15584. }
  15585. }
  15586. }),
  15587. ComposingConfigs.self()
  15588. ]),
  15589. components: [memReplaced.asSpec()]
  15590. };
  15591. };
  15592. var processors = objOf([
  15593. defaulted$1('preprocess', identity),
  15594. defaulted$1('postprocess', identity)
  15595. ]);
  15596. var memento$1 = function (mem, rawProcessors) {
  15597. var ps = asRawOrDie('RepresentingConfigs.memento processors', processors, rawProcessors);
  15598. return Representing.config({
  15599. store: {
  15600. mode: 'manual',
  15601. getValue: function (comp) {
  15602. var other = mem.get(comp);
  15603. var rawValue = Representing.getValue(other);
  15604. return ps.postprocess(rawValue);
  15605. },
  15606. setValue: function (comp, rawValue) {
  15607. var newValue = ps.preprocess(rawValue);
  15608. var other = mem.get(comp);
  15609. Representing.setValue(other, newValue);
  15610. }
  15611. }
  15612. });
  15613. };
  15614. var withComp = function (optInitialValue, getter, setter) {
  15615. return Representing.config(deepMerge({
  15616. store: {
  15617. mode: 'manual',
  15618. getValue: getter,
  15619. setValue: setter
  15620. }
  15621. }, optInitialValue.map(function (initialValue) {
  15622. return { store: { initialValue: initialValue } };
  15623. }).getOr({})));
  15624. };
  15625. var withElement = function (initialValue, getter, setter) {
  15626. return withComp(initialValue, function (c) {
  15627. return getter(c.element());
  15628. }, function (c, v) {
  15629. return setter(c.element(), v);
  15630. });
  15631. };
  15632. var domValue = function (optInitialValue) {
  15633. return withElement(optInitialValue, get$5, set$3);
  15634. };
  15635. var domHtml = function (optInitialValue) {
  15636. return withElement(optInitialValue, get$1, set);
  15637. };
  15638. var memory$1 = function (initialValue) {
  15639. return Representing.config({
  15640. store: {
  15641. mode: 'memory',
  15642. initialValue: initialValue
  15643. }
  15644. });
  15645. };
  15646. var RepresentingConfigs = {
  15647. memento: memento$1,
  15648. withElement: withElement,
  15649. withComp: withComp,
  15650. domValue: domValue,
  15651. domHtml: domHtml,
  15652. memory: memory$1
  15653. };
  15654. var extensionsAccepted = '.jpg,.jpeg,.png,.gif';
  15655. var filterByExtension = function (files) {
  15656. var re = new RegExp('(' + extensionsAccepted.split(/\s*,\s*/).join('|') + ')$', 'i');
  15657. return filter(from$1(files), function (file) {
  15658. return re.test(file.name);
  15659. });
  15660. };
  15661. var renderDropZone = function (spec, providersBackstage) {
  15662. var stopper = function (_, se) {
  15663. se.stop();
  15664. };
  15665. var sequence = function (actions) {
  15666. return function (comp, se) {
  15667. each(actions, function (a) {
  15668. a(comp, se);
  15669. });
  15670. };
  15671. };
  15672. var onDrop = function (comp, se) {
  15673. if (!Disabling.isDisabled(comp)) {
  15674. var transferEvent = se.event().raw();
  15675. handleFiles(comp, transferEvent.dataTransfer.files);
  15676. }
  15677. };
  15678. var onSelect = function (component, simulatedEvent) {
  15679. var files = simulatedEvent.event().raw().target.files;
  15680. handleFiles(component, files);
  15681. };
  15682. var handleFiles = function (component, files) {
  15683. Representing.setValue(component, filterByExtension(files));
  15684. emitWith(component, formChangeEvent, { name: spec.name });
  15685. };
  15686. var memInput = record({
  15687. dom: {
  15688. tag: 'input',
  15689. attributes: {
  15690. type: 'file',
  15691. accept: 'image/*'
  15692. },
  15693. styles: { display: 'none' }
  15694. },
  15695. behaviours: derive$1([config('input-file-events', [
  15696. cutter(click()),
  15697. cutter(tap())
  15698. ])])
  15699. });
  15700. var renderField = function (s) {
  15701. return {
  15702. uid: s.uid,
  15703. dom: {
  15704. tag: 'div',
  15705. classes: ['tox-dropzone-container']
  15706. },
  15707. behaviours: derive$1([
  15708. RepresentingConfigs.memory([]),
  15709. ComposingConfigs.self(),
  15710. Disabling.config({}),
  15711. Toggling.config({
  15712. toggleClass: 'dragenter',
  15713. toggleOnExecute: false
  15714. }),
  15715. config('dropzone-events', [
  15716. run('dragenter', sequence([
  15717. stopper,
  15718. Toggling.toggle
  15719. ])),
  15720. run('dragleave', sequence([
  15721. stopper,
  15722. Toggling.toggle
  15723. ])),
  15724. run('dragover', stopper),
  15725. run('drop', sequence([
  15726. stopper,
  15727. onDrop
  15728. ])),
  15729. run(change(), onSelect)
  15730. ])
  15731. ]),
  15732. components: [{
  15733. dom: {
  15734. tag: 'div',
  15735. classes: ['tox-dropzone'],
  15736. styles: {}
  15737. },
  15738. components: [
  15739. {
  15740. dom: {
  15741. tag: 'p',
  15742. innerHtml: providersBackstage.translate('Drop an image here')
  15743. }
  15744. },
  15745. Button.sketch({
  15746. dom: {
  15747. tag: 'button',
  15748. innerHtml: providersBackstage.translate('Browse for an image'),
  15749. styles: { position: 'relative' },
  15750. classes: [
  15751. 'tox-button',
  15752. 'tox-button--secondary'
  15753. ]
  15754. },
  15755. components: [memInput.asSpec()],
  15756. action: function (comp) {
  15757. var inputComp = memInput.get(comp);
  15758. inputComp.element().dom().click();
  15759. },
  15760. buttonBehaviours: derive$1([
  15761. Tabstopping.config({}),
  15762. DisablingConfigs.button(providersBackstage.isReadOnly),
  15763. receivingConfig()
  15764. ])
  15765. })
  15766. ]
  15767. }]
  15768. };
  15769. };
  15770. var pLabel = spec.label.map(function (label) {
  15771. return renderLabel(label, providersBackstage);
  15772. });
  15773. var pField = FormField.parts().field({ factory: { sketch: renderField } });
  15774. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15775. };
  15776. var renderGrid = function (spec, backstage) {
  15777. return {
  15778. dom: {
  15779. tag: 'div',
  15780. classes: [
  15781. 'tox-form__grid',
  15782. 'tox-form__grid--' + spec.columns + 'col'
  15783. ]
  15784. },
  15785. components: map(spec.items, backstage.interpreter)
  15786. };
  15787. };
  15788. var beforeObject = generate$1('alloy-fake-before-tabstop');
  15789. var afterObject = generate$1('alloy-fake-after-tabstop');
  15790. var craftWithClasses = function (classes) {
  15791. return {
  15792. dom: {
  15793. tag: 'div',
  15794. styles: {
  15795. width: '1px',
  15796. height: '1px',
  15797. outline: 'none'
  15798. },
  15799. attributes: { tabindex: '0' },
  15800. classes: classes
  15801. },
  15802. behaviours: derive$1([
  15803. Focusing.config({ ignore: true }),
  15804. Tabstopping.config({})
  15805. ])
  15806. };
  15807. };
  15808. var craft = function (spec) {
  15809. return {
  15810. dom: {
  15811. tag: 'div',
  15812. classes: ['tox-navobj']
  15813. },
  15814. components: [
  15815. craftWithClasses([beforeObject]),
  15816. spec,
  15817. craftWithClasses([afterObject])
  15818. ],
  15819. behaviours: derive$1([ComposingConfigs.childAt(1)])
  15820. };
  15821. };
  15822. var triggerTab = function (placeholder, shiftKey) {
  15823. emitWith(placeholder, keydown(), {
  15824. raw: {
  15825. which: 9,
  15826. shiftKey: shiftKey
  15827. }
  15828. });
  15829. };
  15830. var onFocus$1 = function (container, targetComp) {
  15831. var target = targetComp.element();
  15832. if (has$2(target, beforeObject)) {
  15833. triggerTab(container, true);
  15834. } else if (has$2(target, afterObject)) {
  15835. triggerTab(container, false);
  15836. }
  15837. };
  15838. var isPseudoStop = function (element) {
  15839. return closest$4(element, [
  15840. '.' + beforeObject,
  15841. '.' + afterObject
  15842. ].join(','), constant(false));
  15843. };
  15844. var platformNeedsSandboxing = !(detect$3().browser.isIE() || detect$3().browser.isEdge());
  15845. var getDynamicSource = function (isSandbox) {
  15846. var cachedValue = Cell('');
  15847. return {
  15848. getValue: function (_frameComponent) {
  15849. return cachedValue.get();
  15850. },
  15851. setValue: function (frameComponent, html) {
  15852. if (!isSandbox) {
  15853. set$1(frameComponent.element(), 'src', 'javascript:\'\'');
  15854. var doc = frameComponent.element().dom().contentWindow.document;
  15855. doc.open();
  15856. doc.write(html);
  15857. doc.close();
  15858. } else {
  15859. set$1(frameComponent.element(), 'srcdoc', html);
  15860. }
  15861. cachedValue.set(html);
  15862. }
  15863. };
  15864. };
  15865. var renderIFrame = function (spec, providersBackstage) {
  15866. var isSandbox = platformNeedsSandboxing && spec.sandboxed;
  15867. var attributes = __assign(__assign({}, spec.label.map(function (title) {
  15868. return { title: title };
  15869. }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {});
  15870. var sourcing = getDynamicSource(isSandbox);
  15871. var pLabel = spec.label.map(function (label) {
  15872. return renderLabel(label, providersBackstage);
  15873. });
  15874. var factory = function (newSpec) {
  15875. return craft({
  15876. uid: newSpec.uid,
  15877. dom: {
  15878. tag: 'iframe',
  15879. attributes: attributes
  15880. },
  15881. behaviours: derive$1([
  15882. Tabstopping.config({}),
  15883. Focusing.config({}),
  15884. RepresentingConfigs.withComp(Option.none(), sourcing.getValue, sourcing.setValue)
  15885. ])
  15886. });
  15887. };
  15888. var pField = FormField.parts().field({ factory: { sketch: factory } });
  15889. return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []);
  15890. };
  15891. function create$5(width, height) {
  15892. return resize(domGlobals.document.createElement('canvas'), width, height);
  15893. }
  15894. function clone$1(canvas) {
  15895. var tCanvas = create$5(canvas.width, canvas.height);
  15896. var ctx = get2dContext(tCanvas);
  15897. ctx.drawImage(canvas, 0, 0);
  15898. return tCanvas;
  15899. }
  15900. function get2dContext(canvas) {
  15901. return canvas.getContext('2d');
  15902. }
  15903. function resize(canvas, width, height) {
  15904. canvas.width = width;
  15905. canvas.height = height;
  15906. return canvas;
  15907. }
  15908. function getWidth(image) {
  15909. return image.naturalWidth || image.width;
  15910. }
  15911. function getHeight(image) {
  15912. return image.naturalHeight || image.height;
  15913. }
  15914. var promise = function () {
  15915. var Promise = function (fn) {
  15916. if (typeof this !== 'object') {
  15917. throw new TypeError('Promises must be constructed via new');
  15918. }
  15919. if (typeof fn !== 'function') {
  15920. throw new TypeError('not a function');
  15921. }
  15922. this._state = null;
  15923. this._value = null;
  15924. this._deferreds = [];
  15925. doResolve(fn, bind(resolve, this), bind(reject, this));
  15926. };
  15927. var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
  15928. domGlobals.setTimeout(fn, 1);
  15929. };
  15930. function bind(fn, thisArg) {
  15931. return function () {
  15932. return fn.apply(thisArg, arguments);
  15933. };
  15934. }
  15935. var isArray = Array.isArray || function (value) {
  15936. return Object.prototype.toString.call(value) === '[object Array]';
  15937. };
  15938. function handle(deferred) {
  15939. var me = this;
  15940. if (this._state === null) {
  15941. this._deferreds.push(deferred);
  15942. return;
  15943. }
  15944. asap(function () {
  15945. var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
  15946. if (cb === null) {
  15947. (me._state ? deferred.resolve : deferred.reject)(me._value);
  15948. return;
  15949. }
  15950. var ret;
  15951. try {
  15952. ret = cb(me._value);
  15953. } catch (e) {
  15954. deferred.reject(e);
  15955. return;
  15956. }
  15957. deferred.resolve(ret);
  15958. });
  15959. }
  15960. function resolve(newValue) {
  15961. try {
  15962. if (newValue === this) {
  15963. throw new TypeError('A promise cannot be resolved with itself.');
  15964. }
  15965. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  15966. var then = newValue.then;
  15967. if (typeof then === 'function') {
  15968. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  15969. return;
  15970. }
  15971. }
  15972. this._state = true;
  15973. this._value = newValue;
  15974. finale.call(this);
  15975. } catch (e) {
  15976. reject.call(this, e);
  15977. }
  15978. }
  15979. function reject(newValue) {
  15980. this._state = false;
  15981. this._value = newValue;
  15982. finale.call(this);
  15983. }
  15984. function finale() {
  15985. for (var _i = 0, _a = this._deferreds; _i < _a.length; _i++) {
  15986. var deferred = _a[_i];
  15987. handle.call(this, deferred);
  15988. }
  15989. this._deferreds = [];
  15990. }
  15991. function Handler(onFulfilled, onRejected, resolve, reject) {
  15992. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  15993. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  15994. this.resolve = resolve;
  15995. this.reject = reject;
  15996. }
  15997. function doResolve(fn, onFulfilled, onRejected) {
  15998. var done = false;
  15999. try {
  16000. fn(function (value) {
  16001. if (done) {
  16002. return;
  16003. }
  16004. done = true;
  16005. onFulfilled(value);
  16006. }, function (reason) {
  16007. if (done) {
  16008. return;
  16009. }
  16010. done = true;
  16011. onRejected(reason);
  16012. });
  16013. } catch (ex) {
  16014. if (done) {
  16015. return;
  16016. }
  16017. done = true;
  16018. onRejected(ex);
  16019. }
  16020. }
  16021. Promise.prototype.catch = function (onRejected) {
  16022. return this.then(null, onRejected);
  16023. };
  16024. Promise.prototype.then = function (onFulfilled, onRejected) {
  16025. var me = this;
  16026. return new Promise(function (resolve, reject) {
  16027. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  16028. });
  16029. };
  16030. Promise.all = function () {
  16031. var values = [];
  16032. for (var _i = 0; _i < arguments.length; _i++) {
  16033. values[_i] = arguments[_i];
  16034. }
  16035. var args = Array.prototype.slice.call(values.length === 1 && isArray(values[0]) ? values[0] : values);
  16036. return new Promise(function (resolve, reject) {
  16037. if (args.length === 0) {
  16038. return resolve([]);
  16039. }
  16040. var remaining = args.length;
  16041. function res(i, val) {
  16042. try {
  16043. if (val && (typeof val === 'object' || typeof val === 'function')) {
  16044. var then = val.then;
  16045. if (typeof then === 'function') {
  16046. then.call(val, function (val) {
  16047. res(i, val);
  16048. }, reject);
  16049. return;
  16050. }
  16051. }
  16052. args[i] = val;
  16053. if (--remaining === 0) {
  16054. resolve(args);
  16055. }
  16056. } catch (ex) {
  16057. reject(ex);
  16058. }
  16059. }
  16060. for (var i = 0; i < args.length; i++) {
  16061. res(i, args[i]);
  16062. }
  16063. });
  16064. };
  16065. Promise.resolve = function (value) {
  16066. if (value && typeof value === 'object' && value.constructor === Promise) {
  16067. return value;
  16068. }
  16069. return new Promise(function (resolve) {
  16070. resolve(value);
  16071. });
  16072. };
  16073. Promise.reject = function (reason) {
  16074. return new Promise(function (resolve, reject) {
  16075. reject(reason);
  16076. });
  16077. };
  16078. Promise.race = function (values) {
  16079. return new Promise(function (resolve, reject) {
  16080. for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
  16081. var value = values_1[_i];
  16082. value.then(resolve, reject);
  16083. }
  16084. });
  16085. };
  16086. return Promise;
  16087. };
  16088. var Promise$1 = window.Promise ? window.Promise : promise();
  16089. function blobToImage(blob) {
  16090. return new Promise$1(function (resolve, reject) {
  16091. var blobUrl = domGlobals.URL.createObjectURL(blob);
  16092. var image = new domGlobals.Image();
  16093. var removeListeners = function () {
  16094. image.removeEventListener('load', loaded);
  16095. image.removeEventListener('error', error);
  16096. };
  16097. function loaded() {
  16098. removeListeners();
  16099. resolve(image);
  16100. }
  16101. function error() {
  16102. removeListeners();
  16103. reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
  16104. }
  16105. image.addEventListener('load', loaded);
  16106. image.addEventListener('error', error);
  16107. image.src = blobUrl;
  16108. if (image.complete) {
  16109. loaded();
  16110. }
  16111. });
  16112. }
  16113. function dataUriToBlobSync(uri) {
  16114. var data = uri.split(',');
  16115. var matches = /data:([^;]+)/.exec(data[0]);
  16116. if (!matches) {
  16117. return Option.none();
  16118. }
  16119. var mimetype = matches[1];
  16120. var base64 = data[1];
  16121. var sliceSize = 1024;
  16122. var byteCharacters = domGlobals.atob(base64);
  16123. var bytesLength = byteCharacters.length;
  16124. var slicesCount = Math.ceil(bytesLength / sliceSize);
  16125. var byteArrays = new Array(slicesCount);
  16126. for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
  16127. var begin = sliceIndex * sliceSize;
  16128. var end = Math.min(begin + sliceSize, bytesLength);
  16129. var bytes = new Array(end - begin);
  16130. for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
  16131. bytes[i] = byteCharacters[offset].charCodeAt(0);
  16132. }
  16133. byteArrays[sliceIndex] = new Uint8Array(bytes);
  16134. }
  16135. return Option.some(new domGlobals.Blob(byteArrays, { type: mimetype }));
  16136. }
  16137. function dataUriToBlob(uri) {
  16138. return new Promise$1(function (resolve, reject) {
  16139. dataUriToBlobSync(uri).fold(function () {
  16140. reject('uri is not base64: ' + uri);
  16141. }, resolve);
  16142. });
  16143. }
  16144. function canvasToBlob(canvas, type, quality) {
  16145. type = type || 'image/png';
  16146. if (domGlobals.HTMLCanvasElement.prototype.toBlob) {
  16147. return new Promise$1(function (resolve, reject) {
  16148. canvas.toBlob(function (blob) {
  16149. if (blob) {
  16150. resolve(blob);
  16151. } else {
  16152. reject();
  16153. }
  16154. }, type, quality);
  16155. });
  16156. } else {
  16157. return dataUriToBlob(canvas.toDataURL(type, quality));
  16158. }
  16159. }
  16160. function canvasToDataURL(canvas, type, quality) {
  16161. type = type || 'image/png';
  16162. return canvas.toDataURL(type, quality);
  16163. }
  16164. function blobToCanvas(blob) {
  16165. return blobToImage(blob).then(function (image) {
  16166. revokeImageUrl(image);
  16167. var canvas = create$5(getWidth(image), getHeight(image));
  16168. var context = get2dContext(canvas);
  16169. context.drawImage(image, 0, 0);
  16170. return canvas;
  16171. });
  16172. }
  16173. function blobToDataUri(blob) {
  16174. return new Promise$1(function (resolve) {
  16175. var reader = new domGlobals.FileReader();
  16176. reader.onloadend = function () {
  16177. resolve(reader.result);
  16178. };
  16179. reader.readAsDataURL(blob);
  16180. });
  16181. }
  16182. function revokeImageUrl(image) {
  16183. domGlobals.URL.revokeObjectURL(image.src);
  16184. }
  16185. function create$6(getCanvas, blob, uri) {
  16186. var initialType = blob.type;
  16187. var getType = constant(initialType);
  16188. function toBlob() {
  16189. return Promise$1.resolve(blob);
  16190. }
  16191. var toDataURL = constant(uri);
  16192. function toBase64() {
  16193. return uri.split(',')[1];
  16194. }
  16195. function toAdjustedBlob(type, quality) {
  16196. return getCanvas.then(function (canvas) {
  16197. return canvasToBlob(canvas, type, quality);
  16198. });
  16199. }
  16200. function toAdjustedDataURL(type, quality) {
  16201. return getCanvas.then(function (canvas) {
  16202. return canvasToDataURL(canvas, type, quality);
  16203. });
  16204. }
  16205. function toAdjustedBase64(type, quality) {
  16206. return toAdjustedDataURL(type, quality).then(function (dataurl) {
  16207. return dataurl.split(',')[1];
  16208. });
  16209. }
  16210. function toCanvas() {
  16211. return getCanvas.then(clone$1);
  16212. }
  16213. return {
  16214. getType: getType,
  16215. toBlob: toBlob,
  16216. toDataURL: toDataURL,
  16217. toBase64: toBase64,
  16218. toAdjustedBlob: toAdjustedBlob,
  16219. toAdjustedDataURL: toAdjustedDataURL,
  16220. toAdjustedBase64: toAdjustedBase64,
  16221. toCanvas: toCanvas
  16222. };
  16223. }
  16224. function fromBlob(blob) {
  16225. return blobToDataUri(blob).then(function (uri) {
  16226. return create$6(blobToCanvas(blob), blob, uri);
  16227. });
  16228. }
  16229. function fromCanvas(canvas, type) {
  16230. return canvasToBlob(canvas, type).then(function (blob) {
  16231. return create$6(Promise$1.resolve(canvas), blob, canvas.toDataURL());
  16232. });
  16233. }
  16234. var blobToImageResult = function (blob) {
  16235. return fromBlob(blob);
  16236. };
  16237. function clamp$1(value, min, max) {
  16238. var parsedValue = typeof value === 'string' ? parseFloat(value) : value;
  16239. if (parsedValue > max) {
  16240. parsedValue = max;
  16241. } else if (parsedValue < min) {
  16242. parsedValue = min;
  16243. }
  16244. return parsedValue;
  16245. }
  16246. function identity$1() {
  16247. return [
  16248. 1,
  16249. 0,
  16250. 0,
  16251. 0,
  16252. 0,
  16253. 0,
  16254. 1,
  16255. 0,
  16256. 0,
  16257. 0,
  16258. 0,
  16259. 0,
  16260. 1,
  16261. 0,
  16262. 0,
  16263. 0,
  16264. 0,
  16265. 0,
  16266. 1,
  16267. 0,
  16268. 0,
  16269. 0,
  16270. 0,
  16271. 0,
  16272. 1
  16273. ];
  16274. }
  16275. var DELTA_INDEX = [
  16276. 0,
  16277. 0.01,
  16278. 0.02,
  16279. 0.04,
  16280. 0.05,
  16281. 0.06,
  16282. 0.07,
  16283. 0.08,
  16284. 0.1,
  16285. 0.11,
  16286. 0.12,
  16287. 0.14,
  16288. 0.15,
  16289. 0.16,
  16290. 0.17,
  16291. 0.18,
  16292. 0.2,
  16293. 0.21,
  16294. 0.22,
  16295. 0.24,
  16296. 0.25,
  16297. 0.27,
  16298. 0.28,
  16299. 0.3,
  16300. 0.32,
  16301. 0.34,
  16302. 0.36,
  16303. 0.38,
  16304. 0.4,
  16305. 0.42,
  16306. 0.44,
  16307. 0.46,
  16308. 0.48,
  16309. 0.5,
  16310. 0.53,
  16311. 0.56,
  16312. 0.59,
  16313. 0.62,
  16314. 0.65,
  16315. 0.68,
  16316. 0.71,
  16317. 0.74,
  16318. 0.77,
  16319. 0.8,
  16320. 0.83,
  16321. 0.86,
  16322. 0.89,
  16323. 0.92,
  16324. 0.95,
  16325. 0.98,
  16326. 1,
  16327. 1.06,
  16328. 1.12,
  16329. 1.18,
  16330. 1.24,
  16331. 1.3,
  16332. 1.36,
  16333. 1.42,
  16334. 1.48,
  16335. 1.54,
  16336. 1.6,
  16337. 1.66,
  16338. 1.72,
  16339. 1.78,
  16340. 1.84,
  16341. 1.9,
  16342. 1.96,
  16343. 2,
  16344. 2.12,
  16345. 2.25,
  16346. 2.37,
  16347. 2.5,
  16348. 2.62,
  16349. 2.75,
  16350. 2.87,
  16351. 3,
  16352. 3.2,
  16353. 3.4,
  16354. 3.6,
  16355. 3.8,
  16356. 4,
  16357. 4.3,
  16358. 4.7,
  16359. 4.9,
  16360. 5,
  16361. 5.5,
  16362. 6,
  16363. 6.5,
  16364. 6.8,
  16365. 7,
  16366. 7.3,
  16367. 7.5,
  16368. 7.8,
  16369. 8,
  16370. 8.4,
  16371. 8.7,
  16372. 9,
  16373. 9.4,
  16374. 9.6,
  16375. 9.8,
  16376. 10
  16377. ];
  16378. function multiply(matrix1, matrix2) {
  16379. var col = [];
  16380. var out = new Array(25);
  16381. var val;
  16382. for (var i = 0; i < 5; i++) {
  16383. for (var j = 0; j < 5; j++) {
  16384. col[j] = matrix2[j + i * 5];
  16385. }
  16386. for (var j = 0; j < 5; j++) {
  16387. val = 0;
  16388. for (var k = 0; k < 5; k++) {
  16389. val += matrix1[j + k * 5] * col[k];
  16390. }
  16391. out[j + i * 5] = val;
  16392. }
  16393. }
  16394. return out;
  16395. }
  16396. function adjustContrast(matrix, value) {
  16397. var x;
  16398. value = clamp$1(value, -1, 1);
  16399. value *= 100;
  16400. if (value < 0) {
  16401. x = 127 + value / 100 * 127;
  16402. } else {
  16403. x = value % 1;
  16404. if (x === 0) {
  16405. x = DELTA_INDEX[value];
  16406. } else {
  16407. x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x;
  16408. }
  16409. x = x * 127 + 127;
  16410. }
  16411. return multiply(matrix, [
  16412. x / 127,
  16413. 0,
  16414. 0,
  16415. 0,
  16416. 0.5 * (127 - x),
  16417. 0,
  16418. x / 127,
  16419. 0,
  16420. 0,
  16421. 0.5 * (127 - x),
  16422. 0,
  16423. 0,
  16424. x / 127,
  16425. 0,
  16426. 0.5 * (127 - x),
  16427. 0,
  16428. 0,
  16429. 0,
  16430. 1,
  16431. 0,
  16432. 0,
  16433. 0,
  16434. 0,
  16435. 0,
  16436. 1
  16437. ]);
  16438. }
  16439. function adjustBrightness(matrix, value) {
  16440. value = clamp$1(255 * value, -255, 255);
  16441. return multiply(matrix, [
  16442. 1,
  16443. 0,
  16444. 0,
  16445. 0,
  16446. value,
  16447. 0,
  16448. 1,
  16449. 0,
  16450. 0,
  16451. value,
  16452. 0,
  16453. 0,
  16454. 1,
  16455. 0,
  16456. value,
  16457. 0,
  16458. 0,
  16459. 0,
  16460. 1,
  16461. 0,
  16462. 0,
  16463. 0,
  16464. 0,
  16465. 0,
  16466. 1
  16467. ]);
  16468. }
  16469. function adjustColors(matrix, adjustR, adjustG, adjustB) {
  16470. adjustR = clamp$1(adjustR, 0, 2);
  16471. adjustG = clamp$1(adjustG, 0, 2);
  16472. adjustB = clamp$1(adjustB, 0, 2);
  16473. return multiply(matrix, [
  16474. adjustR,
  16475. 0,
  16476. 0,
  16477. 0,
  16478. 0,
  16479. 0,
  16480. adjustG,
  16481. 0,
  16482. 0,
  16483. 0,
  16484. 0,
  16485. 0,
  16486. adjustB,
  16487. 0,
  16488. 0,
  16489. 0,
  16490. 0,
  16491. 0,
  16492. 1,
  16493. 0,
  16494. 0,
  16495. 0,
  16496. 0,
  16497. 0,
  16498. 1
  16499. ]);
  16500. }
  16501. function colorFilter(ir, matrix) {
  16502. return ir.toCanvas().then(function (canvas) {
  16503. return applyColorFilter(canvas, ir.getType(), matrix);
  16504. });
  16505. }
  16506. function applyColorFilter(canvas, type, matrix) {
  16507. var context = get2dContext(canvas);
  16508. function applyMatrix(pixelsData, m) {
  16509. var r, g, b, a;
  16510. 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];
  16511. for (var i = 0; i < data.length; i += 4) {
  16512. r = data[i];
  16513. g = data[i + 1];
  16514. b = data[i + 2];
  16515. a = data[i + 3];
  16516. data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4;
  16517. data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9;
  16518. data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14;
  16519. data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19;
  16520. }
  16521. return pixelsData;
  16522. }
  16523. var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix);
  16524. context.putImageData(pixels, 0, 0);
  16525. return fromCanvas(canvas, type);
  16526. }
  16527. function convoluteFilter(ir, matrix) {
  16528. return ir.toCanvas().then(function (canvas) {
  16529. return applyConvoluteFilter(canvas, ir.getType(), matrix);
  16530. });
  16531. }
  16532. function applyConvoluteFilter(canvas, type, matrix) {
  16533. var context = get2dContext(canvas);
  16534. function applyMatrix(pIn, pOut, aMatrix) {
  16535. function clamp(value, min, max) {
  16536. if (value > max) {
  16537. value = max;
  16538. } else if (value < min) {
  16539. value = min;
  16540. }
  16541. return value;
  16542. }
  16543. var side = Math.round(Math.sqrt(aMatrix.length));
  16544. var halfSide = Math.floor(side / 2);
  16545. var rgba = pIn.data;
  16546. var drgba = pOut.data;
  16547. var w = pIn.width;
  16548. var h = pIn.height;
  16549. for (var y = 0; y < h; y++) {
  16550. for (var x = 0; x < w; x++) {
  16551. var r = 0;
  16552. var g = 0;
  16553. var b = 0;
  16554. for (var cy = 0; cy < side; cy++) {
  16555. for (var cx = 0; cx < side; cx++) {
  16556. var scx = clamp(x + cx - halfSide, 0, w - 1);
  16557. var scy = clamp(y + cy - halfSide, 0, h - 1);
  16558. var innerOffset = (scy * w + scx) * 4;
  16559. var wt = aMatrix[cy * side + cx];
  16560. r += rgba[innerOffset] * wt;
  16561. g += rgba[innerOffset + 1] * wt;
  16562. b += rgba[innerOffset + 2] * wt;
  16563. }
  16564. }
  16565. var offset = (y * w + x) * 4;
  16566. drgba[offset] = clamp(r, 0, 255);
  16567. drgba[offset + 1] = clamp(g, 0, 255);
  16568. drgba[offset + 2] = clamp(b, 0, 255);
  16569. }
  16570. }
  16571. return pOut;
  16572. }
  16573. var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height);
  16574. var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height);
  16575. pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix);
  16576. context.putImageData(pixelsOut, 0, 0);
  16577. return fromCanvas(canvas, type);
  16578. }
  16579. function functionColorFilter(colorFn) {
  16580. var filterImpl = function (canvas, type, value) {
  16581. var context = get2dContext(canvas);
  16582. var lookup = new Array(256);
  16583. function applyLookup(pixelsData, lookupData) {
  16584. var data = pixelsData.data;
  16585. for (var i = 0; i < data.length; i += 4) {
  16586. data[i] = lookupData[data[i]];
  16587. data[i + 1] = lookupData[data[i + 1]];
  16588. data[i + 2] = lookupData[data[i + 2]];
  16589. }
  16590. return pixelsData;
  16591. }
  16592. for (var i = 0; i < lookup.length; i++) {
  16593. lookup[i] = colorFn(i, value);
  16594. }
  16595. var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup);
  16596. context.putImageData(pixels, 0, 0);
  16597. return fromCanvas(canvas, type);
  16598. };
  16599. return function (ir, value) {
  16600. return ir.toCanvas().then(function (canvas) {
  16601. return filterImpl(canvas, ir.getType(), value);
  16602. });
  16603. };
  16604. }
  16605. function complexAdjustableColorFilter(matrixAdjustFn) {
  16606. return function (ir, adjust) {
  16607. return colorFilter(ir, matrixAdjustFn(identity$1(), adjust));
  16608. };
  16609. }
  16610. function basicColorFilter(matrix) {
  16611. return function (ir) {
  16612. return colorFilter(ir, matrix);
  16613. };
  16614. }
  16615. function basicConvolutionFilter(kernel) {
  16616. return function (ir) {
  16617. return convoluteFilter(ir, kernel);
  16618. };
  16619. }
  16620. var invert = basicColorFilter([
  16621. -1,
  16622. 0,
  16623. 0,
  16624. 0,
  16625. 255,
  16626. 0,
  16627. -1,
  16628. 0,
  16629. 0,
  16630. 255,
  16631. 0,
  16632. 0,
  16633. -1,
  16634. 0,
  16635. 255,
  16636. 0,
  16637. 0,
  16638. 0,
  16639. 1,
  16640. 0,
  16641. 0,
  16642. 0,
  16643. 0,
  16644. 0,
  16645. 1
  16646. ]);
  16647. var brightness = complexAdjustableColorFilter(adjustBrightness);
  16648. var contrast = complexAdjustableColorFilter(adjustContrast);
  16649. var colorize = function (ir, adjustR, adjustG, adjustB) {
  16650. return colorFilter(ir, adjustColors(identity$1(), adjustR, adjustG, adjustB));
  16651. };
  16652. var sharpen = basicConvolutionFilter([
  16653. 0,
  16654. -1,
  16655. 0,
  16656. -1,
  16657. 5,
  16658. -1,
  16659. 0,
  16660. -1,
  16661. 0
  16662. ]);
  16663. var gamma = functionColorFilter(function (color, value) {
  16664. return Math.pow(color / 255, 1 - value) * 255;
  16665. });
  16666. function scale(image, dW, dH) {
  16667. var sW = getWidth(image);
  16668. var sH = getHeight(image);
  16669. var wRatio = dW / sW;
  16670. var hRatio = dH / sH;
  16671. var scaleCapped = false;
  16672. if (wRatio < 0.5 || wRatio > 2) {
  16673. wRatio = wRatio < 0.5 ? 0.5 : 2;
  16674. scaleCapped = true;
  16675. }
  16676. if (hRatio < 0.5 || hRatio > 2) {
  16677. hRatio = hRatio < 0.5 ? 0.5 : 2;
  16678. scaleCapped = true;
  16679. }
  16680. var scaled = _scale(image, wRatio, hRatio);
  16681. return !scaleCapped ? scaled : scaled.then(function (tCanvas) {
  16682. return scale(tCanvas, dW, dH);
  16683. });
  16684. }
  16685. function _scale(image, wRatio, hRatio) {
  16686. return new Promise$1(function (resolve) {
  16687. var sW = getWidth(image);
  16688. var sH = getHeight(image);
  16689. var dW = Math.floor(sW * wRatio);
  16690. var dH = Math.floor(sH * hRatio);
  16691. var canvas = create$5(dW, dH);
  16692. var context = get2dContext(canvas);
  16693. context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  16694. resolve(canvas);
  16695. });
  16696. }
  16697. function rotate(ir, angle) {
  16698. return ir.toCanvas().then(function (canvas) {
  16699. return applyRotate(canvas, ir.getType(), angle);
  16700. });
  16701. }
  16702. function applyRotate(image, type, angle) {
  16703. var canvas = create$5(image.width, image.height);
  16704. var context = get2dContext(canvas);
  16705. var translateX = 0;
  16706. var translateY = 0;
  16707. angle = angle < 0 ? 360 + angle : angle;
  16708. if (angle === 90 || angle === 270) {
  16709. resize(canvas, canvas.height, canvas.width);
  16710. }
  16711. if (angle === 90 || angle === 180) {
  16712. translateX = canvas.width;
  16713. }
  16714. if (angle === 270 || angle === 180) {
  16715. translateY = canvas.height;
  16716. }
  16717. context.translate(translateX, translateY);
  16718. context.rotate(angle * Math.PI / 180);
  16719. context.drawImage(image, 0, 0);
  16720. return fromCanvas(canvas, type);
  16721. }
  16722. function flip(ir, axis) {
  16723. return ir.toCanvas().then(function (canvas) {
  16724. return applyFlip(canvas, ir.getType(), axis);
  16725. });
  16726. }
  16727. function applyFlip(image, type, axis) {
  16728. var canvas = create$5(image.width, image.height);
  16729. var context = get2dContext(canvas);
  16730. if (axis === 'v') {
  16731. context.scale(1, -1);
  16732. context.drawImage(image, 0, -canvas.height);
  16733. } else {
  16734. context.scale(-1, 1);
  16735. context.drawImage(image, -canvas.width, 0);
  16736. }
  16737. return fromCanvas(canvas, type);
  16738. }
  16739. function crop(ir, x, y, w, h) {
  16740. return ir.toCanvas().then(function (canvas) {
  16741. return applyCrop(canvas, ir.getType(), x, y, w, h);
  16742. });
  16743. }
  16744. function applyCrop(image, type, x, y, w, h) {
  16745. var canvas = create$5(w, h);
  16746. var context = get2dContext(canvas);
  16747. context.drawImage(image, -x, -y);
  16748. return fromCanvas(canvas, type);
  16749. }
  16750. function resize$1(ir, w, h) {
  16751. return ir.toCanvas().then(function (canvas) {
  16752. return scale(canvas, w, h).then(function (newCanvas) {
  16753. return fromCanvas(newCanvas, ir.getType());
  16754. });
  16755. });
  16756. }
  16757. var invert$1 = function (ir) {
  16758. return invert(ir);
  16759. };
  16760. var sharpen$1 = function (ir) {
  16761. return sharpen(ir);
  16762. };
  16763. var gamma$1 = function (ir, value) {
  16764. return gamma(ir, value);
  16765. };
  16766. var colorize$1 = function (ir, adjustR, adjustG, adjustB) {
  16767. return colorize(ir, adjustR, adjustG, adjustB);
  16768. };
  16769. var brightness$1 = function (ir, adjust) {
  16770. return brightness(ir, adjust);
  16771. };
  16772. var contrast$1 = function (ir, adjust) {
  16773. return contrast(ir, adjust);
  16774. };
  16775. var flip$1 = function (ir, axis) {
  16776. return flip(ir, axis);
  16777. };
  16778. var crop$1 = function (ir, x, y, w, h) {
  16779. return crop(ir, x, y, w, h);
  16780. };
  16781. var resize$2 = function (ir, w, h) {
  16782. return resize$1(ir, w, h);
  16783. };
  16784. var rotate$1 = function (ir, angle) {
  16785. return rotate(ir, angle);
  16786. };
  16787. var renderIcon$1 = function (iconHtml, behaviours) {
  16788. return __assign({
  16789. dom: {
  16790. tag: 'span',
  16791. innerHtml: iconHtml,
  16792. classes: [
  16793. 'tox-icon',
  16794. 'tox-tbtn__icon-wrap'
  16795. ]
  16796. }
  16797. }, behaviours);
  16798. };
  16799. var renderIconFromPack = function (iconName, iconsProvider) {
  16800. return renderIcon$1(get$d(iconName, iconsProvider), {});
  16801. };
  16802. var renderReplacableIconFromPack = function (iconName, iconsProvider) {
  16803. return renderIcon$1(get$d(iconName, iconsProvider), { behaviours: derive$1([Replacing.config({})]) });
  16804. };
  16805. var renderLabel$1 = function (text, prefix, providersBackstage) {
  16806. return {
  16807. dom: {
  16808. tag: 'span',
  16809. innerHtml: providersBackstage.translate(text),
  16810. classes: [prefix + '__select-label']
  16811. },
  16812. behaviours: derive$1([Replacing.config({})])
  16813. };
  16814. };
  16815. var internalToolbarButtonExecute = generate$1('toolbar.button.execute');
  16816. var onToolbarButtonExecute = function (info) {
  16817. return runOnExecute(function (comp, _simulatedEvent) {
  16818. runWithApi(info, comp)(function (itemApi) {
  16819. emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi });
  16820. info.onAction(itemApi);
  16821. });
  16822. });
  16823. };
  16824. var toolbarButtonEventOrder = {
  16825. 'alloy.execute': [
  16826. 'disabling',
  16827. 'alloy.base.behaviour',
  16828. 'toggling',
  16829. 'toolbar-button-events'
  16830. ]
  16831. };
  16832. var updateMenuText = generate$1('update-menu-text');
  16833. var updateMenuIcon = generate$1('update-menu-icon');
  16834. var renderCommonDropdown = function (spec, prefix, sharedBackstage) {
  16835. var editorOffCell = Cell(noop);
  16836. var optMemDisplayText = spec.text.map(function (text) {
  16837. return record(renderLabel$1(text, prefix, sharedBackstage.providers));
  16838. });
  16839. var optMemDisplayIcon = spec.icon.map(function (iconName) {
  16840. return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons));
  16841. });
  16842. var onLeftOrRightInMenu = function (comp, se) {
  16843. var dropdown = Representing.getValue(comp);
  16844. Focusing.focus(dropdown);
  16845. emitWith(dropdown, 'keydown', { raw: se.event().raw() });
  16846. Dropdown.close(dropdown);
  16847. return Option.some(true);
  16848. };
  16849. var role = spec.role.fold(function () {
  16850. return {};
  16851. }, function (role) {
  16852. return { role: role };
  16853. });
  16854. var tooltipAttributes = spec.tooltip.fold(function () {
  16855. return {};
  16856. }, function (tooltip) {
  16857. var translatedTooltip = sharedBackstage.providers.translate(tooltip);
  16858. return {
  16859. 'title': translatedTooltip,
  16860. 'aria-label': translatedTooltip
  16861. };
  16862. });
  16863. var memDropdown = record(Dropdown.sketch(__assign(__assign({}, role), {
  16864. dom: {
  16865. tag: 'button',
  16866. classes: [
  16867. prefix,
  16868. prefix + '--select'
  16869. ].concat(map(spec.classes, function (c) {
  16870. return prefix + '--' + c;
  16871. })),
  16872. attributes: __assign({}, tooltipAttributes)
  16873. },
  16874. components: componentRenderPipeline([
  16875. optMemDisplayIcon.map(function (mem) {
  16876. return mem.asSpec();
  16877. }),
  16878. optMemDisplayText.map(function (mem) {
  16879. return mem.asSpec();
  16880. }),
  16881. Option.some({
  16882. dom: {
  16883. tag: 'div',
  16884. classes: [prefix + '__select-chevron'],
  16885. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  16886. }
  16887. })
  16888. ]),
  16889. matchWidth: true,
  16890. useMinWidth: true,
  16891. dropdownBehaviours: derive$1(__spreadArrays(spec.dropdownBehaviours, [
  16892. DisablingConfigs.button(function () {
  16893. return spec.disabled || sharedBackstage.providers.isReadOnly();
  16894. }),
  16895. receivingConfig(),
  16896. Unselecting.config({}),
  16897. Replacing.config({}),
  16898. config('dropdown-events', [
  16899. onControlAttached(spec, editorOffCell),
  16900. onControlDetached(spec, editorOffCell)
  16901. ]),
  16902. config('menubutton-update-display-text', [
  16903. run(updateMenuText, function (comp, se) {
  16904. optMemDisplayText.bind(function (mem) {
  16905. return mem.getOpt(comp);
  16906. }).each(function (displayText) {
  16907. Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event().text()))]);
  16908. });
  16909. }),
  16910. run(updateMenuIcon, function (comp, se) {
  16911. optMemDisplayIcon.bind(function (mem) {
  16912. return mem.getOpt(comp);
  16913. }).each(function (displayIcon) {
  16914. Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event().icon(), sharedBackstage.providers.icons)]);
  16915. });
  16916. })
  16917. ])
  16918. ])),
  16919. eventOrder: deepMerge(toolbarButtonEventOrder, {
  16920. mousedown: [
  16921. 'focusing',
  16922. 'alloy.base.behaviour',
  16923. 'item-type-events',
  16924. 'normal-dropdown-events'
  16925. ]
  16926. }),
  16927. sandboxBehaviours: derive$1([Keying.config({
  16928. mode: 'special',
  16929. onLeft: onLeftOrRightInMenu,
  16930. onRight: onLeftOrRightInMenu
  16931. })]),
  16932. lazySink: sharedBackstage.getSink,
  16933. toggleClass: prefix + '--active',
  16934. parts: { menu: part(false, spec.columns, spec.presets) },
  16935. fetch: function () {
  16936. return Future.nu(spec.fetch);
  16937. }
  16938. })));
  16939. return memDropdown.asSpec();
  16940. };
  16941. var isMenuItemReference = function (item) {
  16942. return isString(item);
  16943. };
  16944. var isSeparator = function (item) {
  16945. return item.type === 'separator';
  16946. };
  16947. var isExpandingMenuItem = function (item) {
  16948. return has(item, 'getSubmenuItems');
  16949. };
  16950. var separator$1 = { type: 'separator' };
  16951. var unwrapReferences = function (items, menuItems) {
  16952. var realItems = foldl(items, function (acc, item) {
  16953. if (isMenuItemReference(item)) {
  16954. if (item === '') {
  16955. return acc;
  16956. } else if (item === '|') {
  16957. return acc.length > 0 && !isSeparator(acc[acc.length - 1]) ? acc.concat([separator$1]) : acc;
  16958. } else if (has(menuItems, item.toLowerCase())) {
  16959. return acc.concat([menuItems[item.toLowerCase()]]);
  16960. } else {
  16961. return acc;
  16962. }
  16963. } else {
  16964. return acc.concat([item]);
  16965. }
  16966. }, []);
  16967. if (realItems.length > 0 && isSeparator(realItems[realItems.length - 1])) {
  16968. realItems.pop();
  16969. }
  16970. return realItems;
  16971. };
  16972. var getFromExpandingItem = function (item, menuItems) {
  16973. var submenuItems = item.getSubmenuItems();
  16974. var rest = expand(submenuItems, menuItems);
  16975. var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items));
  16976. var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value));
  16977. return {
  16978. item: item,
  16979. menus: newMenus,
  16980. expansions: newExpansions
  16981. };
  16982. };
  16983. var getFromItem = function (item, menuItems) {
  16984. return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : {
  16985. item: item,
  16986. menus: {},
  16987. expansions: {}
  16988. };
  16989. };
  16990. var generateValueIfRequired = function (item) {
  16991. if (isSeparator(item)) {
  16992. return item;
  16993. } else {
  16994. var itemValue = get(item, 'value').getOrThunk(function () {
  16995. return generate$1('generated-menu-item');
  16996. });
  16997. return deepMerge({ value: itemValue }, item);
  16998. }
  16999. };
  17000. var expand = function (items, menuItems) {
  17001. var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems);
  17002. return foldr(realItems, function (acc, item) {
  17003. var itemWithValue = generateValueIfRequired(item);
  17004. var newData = getFromItem(itemWithValue, menuItems);
  17005. return {
  17006. menus: deepMerge(acc.menus, newData.menus),
  17007. items: [newData.item].concat(acc.items),
  17008. expansions: deepMerge(acc.expansions, newData.expansions)
  17009. };
  17010. }, {
  17011. menus: {},
  17012. expansions: {},
  17013. items: []
  17014. });
  17015. };
  17016. var build$2 = function (items, itemResponse, backstage, isHorizontalMenu) {
  17017. var primary = generate$1('primary-menu');
  17018. var data = expand(items, backstage.shared.providers.menuItems());
  17019. if (data.items.length === 0) {
  17020. return Option.none();
  17021. }
  17022. var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu);
  17023. var submenus = map$1(data.menus, function (menuItems, menuName) {
  17024. return createPartialMenu(menuName, menuItems, itemResponse, backstage, false);
  17025. });
  17026. var menus = deepMerge(submenus, wrap$1(primary, mainMenu));
  17027. return Option.from(tieredMenu.tieredData(primary, menus, data.expansions));
  17028. };
  17029. var getMenuButtonApi = function (component) {
  17030. return {
  17031. isDisabled: function () {
  17032. return Disabling.isDisabled(component);
  17033. },
  17034. setDisabled: function (state) {
  17035. return Disabling.set(component, state);
  17036. },
  17037. setActive: function (state) {
  17038. var elm = component.element();
  17039. if (state) {
  17040. add$2(elm, 'tox-tbtn--enabled');
  17041. set$1(elm, 'aria-pressed', true);
  17042. } else {
  17043. remove$4(elm, 'tox-tbtn--enabled');
  17044. remove$1(elm, 'aria-pressed');
  17045. }
  17046. },
  17047. isActive: function () {
  17048. return has$2(component.element(), 'tox-tbtn--enabled');
  17049. }
  17050. };
  17051. };
  17052. var renderMenuButton = function (spec, prefix, backstage, role) {
  17053. return renderCommonDropdown({
  17054. text: spec.text,
  17055. icon: spec.icon,
  17056. tooltip: spec.tooltip,
  17057. role: role,
  17058. fetch: function (callback) {
  17059. spec.fetch(function (items) {
  17060. callback(build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false));
  17061. });
  17062. },
  17063. onSetup: spec.onSetup,
  17064. getApi: getMenuButtonApi,
  17065. columns: 1,
  17066. presets: 'normal',
  17067. classes: [],
  17068. dropdownBehaviours: [Tabstopping.config({})]
  17069. }, prefix, backstage.shared);
  17070. };
  17071. var getFetch$1 = function (items, getButton, backstage) {
  17072. var getMenuItemAction = function (item) {
  17073. return function (api) {
  17074. var newValue = !api.isActive();
  17075. api.setActive(newValue);
  17076. item.storage.set(newValue);
  17077. backstage.shared.getSink().each(function (sink) {
  17078. getButton().getOpt(sink).each(function (orig) {
  17079. focus$1(orig.element());
  17080. emitWith(orig, formActionEvent, {
  17081. name: item.name,
  17082. value: item.storage.get()
  17083. });
  17084. });
  17085. });
  17086. };
  17087. };
  17088. var getMenuItemSetup = function (item) {
  17089. return function (api) {
  17090. api.setActive(item.storage.get());
  17091. };
  17092. };
  17093. return function (success) {
  17094. success(map(items, function (item) {
  17095. var text = item.text.fold(function () {
  17096. return {};
  17097. }, function (text) {
  17098. return { text: text };
  17099. });
  17100. return __assign(__assign({
  17101. type: item.type,
  17102. active: false
  17103. }, text), {
  17104. onAction: getMenuItemAction(item),
  17105. onSetup: getMenuItemSetup(item)
  17106. });
  17107. }));
  17108. };
  17109. };
  17110. var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) {
  17111. if (extraBehaviours === void 0) {
  17112. extraBehaviours = [];
  17113. }
  17114. var action = actionOpt.fold(function () {
  17115. return {};
  17116. }, function (action) {
  17117. return { action: action };
  17118. });
  17119. var common = __assign({
  17120. buttonBehaviours: derive$1([
  17121. DisablingConfigs.button(function () {
  17122. return spec.disabled || providersBackstage.isReadOnly();
  17123. }),
  17124. receivingConfig(),
  17125. Tabstopping.config({}),
  17126. config('button press', [
  17127. preventDefault('click'),
  17128. preventDefault('mousedown')
  17129. ])
  17130. ].concat(extraBehaviours)),
  17131. eventOrder: {
  17132. click: [
  17133. 'button press',
  17134. 'alloy.base.behaviour'
  17135. ],
  17136. mousedown: [
  17137. 'button press',
  17138. 'alloy.base.behaviour'
  17139. ]
  17140. }
  17141. }, action);
  17142. var domFinal = deepMerge(common, { dom: dom });
  17143. return deepMerge(domFinal, { components: components });
  17144. };
  17145. var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) {
  17146. if (extraBehaviours === void 0) {
  17147. extraBehaviours = [];
  17148. }
  17149. var tooltipAttributes = spec.tooltip.map(function (tooltip) {
  17150. return {
  17151. 'aria-label': providersBackstage.translate(tooltip),
  17152. 'title': providersBackstage.translate(tooltip)
  17153. };
  17154. }).getOr({});
  17155. var dom = {
  17156. tag: 'button',
  17157. classes: ['tox-tbtn'],
  17158. attributes: tooltipAttributes
  17159. };
  17160. var icon = spec.icon.map(function (iconName) {
  17161. return renderIconFromPack(iconName, providersBackstage.icons);
  17162. });
  17163. var components = componentRenderPipeline([icon]);
  17164. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17165. };
  17166. var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) {
  17167. if (extraBehaviours === void 0) {
  17168. extraBehaviours = [];
  17169. }
  17170. var iconButtonSpec = renderIconButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours);
  17171. return Button.sketch(iconButtonSpec);
  17172. };
  17173. var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17174. if (extraBehaviours === void 0) {
  17175. extraBehaviours = [];
  17176. }
  17177. if (extraClasses === void 0) {
  17178. extraClasses = [];
  17179. }
  17180. var translatedText = providersBackstage.translate(spec.text);
  17181. var icon = spec.icon ? spec.icon.map(function (iconName) {
  17182. return renderIconFromPack(iconName, providersBackstage.icons);
  17183. }) : Option.none();
  17184. var components = icon.isSome() ? componentRenderPipeline([icon]) : [];
  17185. var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText };
  17186. var classes = __spreadArrays(!spec.primary && !spec.borderless ? [
  17187. 'tox-button',
  17188. 'tox-button--secondary'
  17189. ] : ['tox-button'], icon.isSome() ? ['tox-button--icon'] : [], spec.borderless ? ['tox-button--naked'] : [], extraClasses);
  17190. var dom = __assign(__assign({
  17191. tag: 'button',
  17192. classes: classes
  17193. }, innerHtml), { attributes: { title: translatedText } });
  17194. return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage);
  17195. };
  17196. var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) {
  17197. if (extraBehaviours === void 0) {
  17198. extraBehaviours = [];
  17199. }
  17200. if (extraClasses === void 0) {
  17201. extraClasses = [];
  17202. }
  17203. var buttonSpec = renderButtonSpec(spec, Option.some(action), providersBackstage, extraBehaviours, extraClasses);
  17204. return Button.sketch(buttonSpec);
  17205. };
  17206. var getAction = function (name, buttonType) {
  17207. return function (comp) {
  17208. if (buttonType === 'custom') {
  17209. emitWith(comp, formActionEvent, {
  17210. name: name,
  17211. value: {}
  17212. });
  17213. } else if (buttonType === 'submit') {
  17214. emit(comp, formSubmitEvent);
  17215. } else if (buttonType === 'cancel') {
  17216. emit(comp, formCancelEvent);
  17217. } else {
  17218. domGlobals.console.error('Unknown button type: ', buttonType);
  17219. }
  17220. };
  17221. };
  17222. var isMenuFooterButtonSpec = function (spec, buttonType) {
  17223. return buttonType === 'menu';
  17224. };
  17225. var isNormalFooterButtonSpec = function (spec, buttonType) {
  17226. return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit';
  17227. };
  17228. var renderFooterButton = function (spec, buttonType, backstage) {
  17229. if (isMenuFooterButtonSpec(spec, buttonType)) {
  17230. var getButton = function () {
  17231. return memButton_1;
  17232. };
  17233. var menuButtonSpec = spec;
  17234. var fixedSpec = __assign(__assign({}, spec), {
  17235. onSetup: function (api) {
  17236. api.setDisabled(spec.disabled);
  17237. return noop;
  17238. },
  17239. fetch: getFetch$1(menuButtonSpec.items, getButton, backstage)
  17240. });
  17241. var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Option.none()));
  17242. return memButton_1.asSpec();
  17243. } else if (isNormalFooterButtonSpec(spec, buttonType)) {
  17244. var action = getAction(spec.name, buttonType);
  17245. var buttonSpec = __assign(__assign({}, spec), { borderless: false });
  17246. return renderButton(buttonSpec, action, backstage.shared.providers, []);
  17247. } else {
  17248. domGlobals.console.error('Unknown footer button type: ', buttonType);
  17249. }
  17250. };
  17251. var renderDialogButton = function (spec, providersBackstage) {
  17252. var action = getAction(spec.name, 'custom');
  17253. return renderFormField(Option.none(), FormField.parts().field(__assign({ factory: Button }, renderButtonSpec(spec, Option.some(action), providersBackstage, [
  17254. RepresentingConfigs.memory(''),
  17255. ComposingConfigs.self()
  17256. ]))));
  17257. };
  17258. var schema$i = constant([
  17259. defaulted$1('field1Name', 'field1'),
  17260. defaulted$1('field2Name', 'field2'),
  17261. onStrictHandler('onLockedChange'),
  17262. markers(['lockClass']),
  17263. defaulted$1('locked', false),
  17264. SketchBehaviours.field('coupledFieldBehaviours', [
  17265. Composing,
  17266. Representing
  17267. ])
  17268. ]);
  17269. var getField = function (comp, detail, partName) {
  17270. return getPart(comp, detail, partName).bind(Composing.getCurrent);
  17271. };
  17272. var coupledPart = function (selfName, otherName) {
  17273. return required({
  17274. factory: FormField,
  17275. name: selfName,
  17276. overrides: function (detail) {
  17277. return {
  17278. fieldBehaviours: derive$1([config('coupled-input-behaviour', [run(input(), function (me) {
  17279. getField(me, detail, otherName).each(function (other) {
  17280. getPart(me, detail, 'lock').each(function (lock) {
  17281. if (Toggling.isOn(lock)) {
  17282. detail.onLockedChange(me, other, lock);
  17283. }
  17284. });
  17285. });
  17286. })])])
  17287. };
  17288. }
  17289. });
  17290. };
  17291. var parts$5 = constant([
  17292. coupledPart('field1', 'field2'),
  17293. coupledPart('field2', 'field1'),
  17294. required({
  17295. factory: Button,
  17296. schema: [strict$1('dom')],
  17297. name: 'lock',
  17298. overrides: function (detail) {
  17299. return {
  17300. buttonBehaviours: derive$1([Toggling.config({
  17301. selected: detail.locked,
  17302. toggleClass: detail.markers.lockClass,
  17303. aria: { mode: 'pressed' }
  17304. })])
  17305. };
  17306. }
  17307. })
  17308. ]);
  17309. var factory$7 = function (detail, components, _spec, _externals) {
  17310. return {
  17311. uid: detail.uid,
  17312. dom: detail.dom,
  17313. components: components,
  17314. behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [
  17315. Composing.config({ find: Option.some }),
  17316. Representing.config({
  17317. store: {
  17318. mode: 'manual',
  17319. getValue: function (comp) {
  17320. var _a;
  17321. var parts = getPartsOrDie(comp, detail, [
  17322. 'field1',
  17323. 'field2'
  17324. ]);
  17325. return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a;
  17326. },
  17327. setValue: function (comp, value) {
  17328. var parts = getPartsOrDie(comp, detail, [
  17329. 'field1',
  17330. 'field2'
  17331. ]);
  17332. if (hasNonNullableKey(value, detail.field1Name)) {
  17333. Representing.setValue(parts.field1(), value[detail.field1Name]);
  17334. }
  17335. if (hasNonNullableKey(value, detail.field2Name)) {
  17336. Representing.setValue(parts.field2(), value[detail.field2Name]);
  17337. }
  17338. }
  17339. }
  17340. })
  17341. ]),
  17342. apis: {
  17343. getField1: function (component) {
  17344. return getPart(component, detail, 'field1');
  17345. },
  17346. getField2: function (component) {
  17347. return getPart(component, detail, 'field2');
  17348. },
  17349. getLock: function (component) {
  17350. return getPart(component, detail, 'lock');
  17351. }
  17352. }
  17353. };
  17354. };
  17355. var FormCoupledInputs = composite$1({
  17356. name: 'FormCoupledInputs',
  17357. configFields: schema$i(),
  17358. partFields: parts$5(),
  17359. factory: factory$7,
  17360. apis: {
  17361. getField1: function (apis, component) {
  17362. return apis.getField1(component);
  17363. },
  17364. getField2: function (apis, component) {
  17365. return apis.getField2(component);
  17366. },
  17367. getLock: function (apis, component) {
  17368. return apis.getLock(component);
  17369. }
  17370. }
  17371. });
  17372. var formatSize = function (size) {
  17373. var unitDec = {
  17374. '': 0,
  17375. 'px': 0,
  17376. 'pt': 1,
  17377. 'mm': 1,
  17378. 'pc': 2,
  17379. 'ex': 2,
  17380. 'em': 2,
  17381. 'ch': 2,
  17382. 'rem': 2,
  17383. 'cm': 3,
  17384. 'in': 4,
  17385. '%': 4
  17386. };
  17387. var maxDecimal = function (unit) {
  17388. return unit in unitDec ? unitDec[unit] : 1;
  17389. };
  17390. var numText = size.value.toFixed(maxDecimal(size.unit));
  17391. if (numText.indexOf('.') !== -1) {
  17392. numText = numText.replace(/\.?0*$/, '');
  17393. }
  17394. return numText + size.unit;
  17395. };
  17396. var parseSize = function (sizeText) {
  17397. var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/;
  17398. var match = numPattern.exec(sizeText);
  17399. if (match !== null) {
  17400. var value = parseFloat(match[1]);
  17401. var unit = match[2];
  17402. return Result.value({
  17403. value: value,
  17404. unit: unit
  17405. });
  17406. } else {
  17407. return Result.error(sizeText);
  17408. }
  17409. };
  17410. var convertUnit = function (size, unit) {
  17411. var inInch = {
  17412. '': 96,
  17413. 'px': 96,
  17414. 'pt': 72,
  17415. 'cm': 2.54,
  17416. 'pc': 12,
  17417. 'mm': 25.4,
  17418. 'in': 1
  17419. };
  17420. var supported = function (u) {
  17421. return Object.prototype.hasOwnProperty.call(inInch, u);
  17422. };
  17423. if (size.unit === unit) {
  17424. return Option.some(size.value);
  17425. } else if (supported(size.unit) && supported(unit)) {
  17426. if (inInch[size.unit] === inInch[unit]) {
  17427. return Option.some(size.value);
  17428. } else {
  17429. return Option.some(size.value / inInch[size.unit] * inInch[unit]);
  17430. }
  17431. } else {
  17432. return Option.none();
  17433. }
  17434. };
  17435. var noSizeConversion = function (_input) {
  17436. return Option.none();
  17437. };
  17438. var ratioSizeConversion = function (scale, unit) {
  17439. return function (size) {
  17440. return convertUnit(size, unit).map(function (value) {
  17441. return {
  17442. value: value * scale,
  17443. unit: unit
  17444. };
  17445. });
  17446. };
  17447. };
  17448. var makeRatioConverter = function (currentFieldText, otherFieldText) {
  17449. var cValue = parseSize(currentFieldText).toOption();
  17450. var oValue = parseSize(otherFieldText).toOption();
  17451. return lift2(cValue, oValue, function (cSize, oSize) {
  17452. return convertUnit(cSize, oSize.unit).map(function (val) {
  17453. return oSize.value / val;
  17454. }).map(function (r) {
  17455. return ratioSizeConversion(r, oSize.unit);
  17456. }).getOr(noSizeConversion);
  17457. }).getOr(noSizeConversion);
  17458. };
  17459. var renderSizeInput = function (spec, providersBackstage) {
  17460. var converter = noSizeConversion;
  17461. var ratioEvent = generate$1('ratio-event');
  17462. var pLock = FormCoupledInputs.parts().lock({
  17463. dom: {
  17464. tag: 'button',
  17465. classes: [
  17466. 'tox-lock',
  17467. 'tox-button',
  17468. 'tox-button--naked',
  17469. 'tox-button--icon'
  17470. ],
  17471. attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) }
  17472. },
  17473. components: [
  17474. {
  17475. dom: {
  17476. tag: 'span',
  17477. classes: [
  17478. 'tox-icon',
  17479. 'tox-lock-icon__lock'
  17480. ],
  17481. innerHtml: get$d('lock', providersBackstage.icons)
  17482. }
  17483. },
  17484. {
  17485. dom: {
  17486. tag: 'span',
  17487. classes: [
  17488. 'tox-icon',
  17489. 'tox-lock-icon__unlock'
  17490. ],
  17491. innerHtml: get$d('unlock', providersBackstage.icons)
  17492. }
  17493. }
  17494. ],
  17495. buttonBehaviours: derive$1([
  17496. Disabling.config({
  17497. disabled: function () {
  17498. return spec.disabled || providersBackstage.isReadOnly();
  17499. }
  17500. }),
  17501. receivingConfig(),
  17502. Tabstopping.config({})
  17503. ])
  17504. });
  17505. var formGroup = function (components) {
  17506. return {
  17507. dom: {
  17508. tag: 'div',
  17509. classes: ['tox-form__group']
  17510. },
  17511. components: components
  17512. };
  17513. };
  17514. var getFieldPart = function (isField1) {
  17515. return FormField.parts().field({
  17516. factory: Input,
  17517. inputClasses: ['tox-textfield'],
  17518. inputBehaviours: derive$1([
  17519. Disabling.config({
  17520. disabled: function () {
  17521. return spec.disabled || providersBackstage.isReadOnly();
  17522. }
  17523. }),
  17524. receivingConfig(),
  17525. Tabstopping.config({}),
  17526. config('size-input-events', [
  17527. run(focusin(), function (component, _simulatedEvent) {
  17528. emitWith(component, ratioEvent, { isField1: isField1 });
  17529. }),
  17530. run(change(), function (component, _simulatedEvent) {
  17531. emitWith(component, formChangeEvent, { name: spec.name });
  17532. })
  17533. ])
  17534. ]),
  17535. selectOnFocus: false
  17536. });
  17537. };
  17538. var getLabel = function (label) {
  17539. return {
  17540. dom: {
  17541. tag: 'label',
  17542. classes: ['tox-label'],
  17543. innerHtml: providersBackstage.translate(label)
  17544. }
  17545. };
  17546. };
  17547. var widthField = FormCoupledInputs.parts().field1(formGroup([
  17548. FormField.parts().label(getLabel('Width')),
  17549. getFieldPart(true)
  17550. ]));
  17551. var heightField = FormCoupledInputs.parts().field2(formGroup([
  17552. FormField.parts().label(getLabel('Height')),
  17553. getFieldPart(false)
  17554. ]));
  17555. return FormCoupledInputs.sketch({
  17556. dom: {
  17557. tag: 'div',
  17558. classes: ['tox-form__group']
  17559. },
  17560. components: [{
  17561. dom: {
  17562. tag: 'div',
  17563. classes: ['tox-form__controls-h-stack']
  17564. },
  17565. components: [
  17566. widthField,
  17567. heightField,
  17568. formGroup([
  17569. getLabel('&nbsp;'),
  17570. pLock
  17571. ])
  17572. ]
  17573. }],
  17574. field1Name: 'width',
  17575. field2Name: 'height',
  17576. locked: true,
  17577. markers: { lockClass: 'tox-locked' },
  17578. onLockedChange: function (current, other, _lock) {
  17579. parseSize(Representing.getValue(current)).each(function (size) {
  17580. converter(size).each(function (newSize) {
  17581. Representing.setValue(other, formatSize(newSize));
  17582. });
  17583. });
  17584. },
  17585. coupledFieldBehaviours: derive$1([
  17586. Disabling.config({
  17587. disabled: function () {
  17588. return spec.disabled || providersBackstage.isReadOnly();
  17589. },
  17590. onDisabled: function (comp) {
  17591. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable);
  17592. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable);
  17593. FormCoupledInputs.getLock(comp).each(Disabling.disable);
  17594. },
  17595. onEnabled: function (comp) {
  17596. FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable);
  17597. FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable);
  17598. FormCoupledInputs.getLock(comp).each(Disabling.enable);
  17599. }
  17600. }),
  17601. receivingConfig(),
  17602. config('size-input-events2', [run(ratioEvent, function (component, simulatedEvent) {
  17603. var isField1 = simulatedEvent.event().isField1();
  17604. var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component);
  17605. var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component);
  17606. var value1 = optCurrent.map(Representing.getValue).getOr('');
  17607. var value2 = optOther.map(Representing.getValue).getOr('');
  17608. converter = makeRatioConverter(value1, value2);
  17609. })])
  17610. ])
  17611. });
  17612. };
  17613. var undo = constant(generate$1('undo'));
  17614. var redo = constant(generate$1('redo'));
  17615. var zoom = constant(generate$1('zoom'));
  17616. var back = constant(generate$1('back'));
  17617. var apply = constant(generate$1('apply'));
  17618. var swap = constant(generate$1('swap'));
  17619. var transform = constant(generate$1('transform'));
  17620. var tempTransform = constant(generate$1('temp-transform'));
  17621. var transformApply = constant(generate$1('transform-apply'));
  17622. var internal = {
  17623. undo: undo,
  17624. redo: redo,
  17625. zoom: zoom,
  17626. back: back,
  17627. apply: apply,
  17628. swap: swap,
  17629. transform: transform,
  17630. tempTransform: tempTransform,
  17631. transformApply: transformApply
  17632. };
  17633. var saveState = constant('save-state');
  17634. var disable$1 = constant('disable');
  17635. var enable$1 = constant('enable');
  17636. var external$2 = {
  17637. formActionEvent: formActionEvent,
  17638. saveState: saveState,
  17639. disable: disable$1,
  17640. enable: enable$1
  17641. };
  17642. var renderEditPanel = function (imagePanel, providersBackstage) {
  17643. var createButton = function (text, action, disabled, primary) {
  17644. return record(renderButton({
  17645. name: text,
  17646. text: text,
  17647. disabled: disabled,
  17648. primary: primary,
  17649. icon: Option.none(),
  17650. borderless: false
  17651. }, action, providersBackstage));
  17652. };
  17653. var createIconButton = function (icon, tooltip, action, disabled) {
  17654. return record(renderIconButton({
  17655. name: icon,
  17656. icon: Option.some(icon),
  17657. tooltip: Option.some(tooltip),
  17658. disabled: disabled,
  17659. primary: false,
  17660. borderless: false
  17661. }, action, providersBackstage));
  17662. };
  17663. var disableAllComponents = function (comps, eventcomp) {
  17664. comps.map(function (mem) {
  17665. var component = mem.get(eventcomp);
  17666. if (component.hasConfigured(Disabling)) {
  17667. Disabling.disable(component);
  17668. }
  17669. });
  17670. };
  17671. var enableAllComponents = function (comps, eventcomp) {
  17672. comps.map(function (mem) {
  17673. var component = mem.get(eventcomp);
  17674. if (component.hasConfigured(Disabling)) {
  17675. Disabling.enable(component);
  17676. }
  17677. });
  17678. };
  17679. var panelDom = {
  17680. tag: 'div',
  17681. classes: [
  17682. 'tox-image-tools__toolbar',
  17683. 'tox-image-tools-edit-panel'
  17684. ]
  17685. };
  17686. var noop$1 = noop;
  17687. var emit$1 = function (comp, event, data) {
  17688. emitWith(comp, event, data);
  17689. };
  17690. var emitDisable = function (component) {
  17691. return emit(component, external$2.disable());
  17692. };
  17693. var emitEnable = function (component) {
  17694. return emit(component, external$2.enable());
  17695. };
  17696. var emitTransform = function (comp, transform) {
  17697. emitDisable(comp);
  17698. emit$1(comp, internal.transform(), { transform: transform });
  17699. emitEnable(comp);
  17700. };
  17701. var emitTempTransform = function (comp, transform) {
  17702. emitDisable(comp);
  17703. emit$1(comp, internal.tempTransform(), { transform: transform });
  17704. emitEnable(comp);
  17705. };
  17706. var getBackSwap = function (anyInSystem) {
  17707. return function () {
  17708. memContainer.getOpt(anyInSystem).each(function (container) {
  17709. Replacing.set(container, [ButtonPanel]);
  17710. });
  17711. };
  17712. };
  17713. var emitTransformApply = function (comp, transform) {
  17714. emitDisable(comp);
  17715. emit$1(comp, internal.transformApply(), {
  17716. transform: transform,
  17717. swap: getBackSwap(comp)
  17718. });
  17719. emitEnable(comp);
  17720. };
  17721. var createBackButton = function () {
  17722. return createButton('Back', function (button) {
  17723. return emit$1(button, internal.back(), { swap: getBackSwap(button) });
  17724. }, false, false);
  17725. };
  17726. var createSpacer = function () {
  17727. return record({
  17728. dom: {
  17729. tag: 'div',
  17730. classes: ['tox-spacer']
  17731. },
  17732. behaviours: derive$1([Disabling.config({})])
  17733. });
  17734. };
  17735. var createApplyButton = function () {
  17736. return createButton('Apply', function (button) {
  17737. return emit$1(button, internal.apply(), { swap: getBackSwap(button) });
  17738. }, true, true);
  17739. };
  17740. var makeCropTransform = function () {
  17741. return function (ir) {
  17742. var rect = imagePanel.getRect();
  17743. return crop$1(ir, rect.x, rect.y, rect.w, rect.h);
  17744. };
  17745. };
  17746. var cropPanelComponents = [
  17747. createBackButton(),
  17748. createSpacer(),
  17749. createButton('Apply', function (button) {
  17750. var transform = makeCropTransform();
  17751. emitTransformApply(button, transform);
  17752. imagePanel.hideCrop();
  17753. }, false, true)
  17754. ];
  17755. var CropPanel = Container.sketch({
  17756. dom: panelDom,
  17757. components: cropPanelComponents.map(function (mem) {
  17758. return mem.asSpec();
  17759. }),
  17760. containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [
  17761. run(external$2.disable(), function (comp, _se) {
  17762. disableAllComponents(cropPanelComponents, comp);
  17763. }),
  17764. run(external$2.enable(), function (comp, _se) {
  17765. enableAllComponents(cropPanelComponents, comp);
  17766. })
  17767. ])])
  17768. });
  17769. var memSize = record(renderSizeInput({
  17770. name: 'size',
  17771. label: Option.none(),
  17772. constrain: true,
  17773. disabled: false
  17774. }, providersBackstage));
  17775. var makeResizeTransform = function (width, height) {
  17776. return function (ir) {
  17777. return resize$2(ir, width, height);
  17778. };
  17779. };
  17780. var resizePanelComponents = [
  17781. createBackButton(),
  17782. createSpacer(),
  17783. memSize,
  17784. createSpacer(),
  17785. createButton('Apply', function (button) {
  17786. memSize.getOpt(button).each(function (sizeInput) {
  17787. var value = Representing.getValue(sizeInput);
  17788. var width = parseInt(value.width, 10);
  17789. var height = parseInt(value.height, 10);
  17790. var transform = makeResizeTransform(width, height);
  17791. emitTransformApply(button, transform);
  17792. });
  17793. }, false, true)
  17794. ];
  17795. var ResizePanel = Container.sketch({
  17796. dom: panelDom,
  17797. components: resizePanelComponents.map(function (mem) {
  17798. return mem.asSpec();
  17799. }),
  17800. containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [
  17801. run(external$2.disable(), function (comp, _se) {
  17802. disableAllComponents(resizePanelComponents, comp);
  17803. }),
  17804. run(external$2.enable(), function (comp, _se) {
  17805. enableAllComponents(resizePanelComponents, comp);
  17806. })
  17807. ])])
  17808. });
  17809. var makeValueTransform = function (transform, value) {
  17810. return function (ir) {
  17811. return transform(ir, value);
  17812. };
  17813. };
  17814. var horizontalFlip = makeValueTransform(flip$1, 'h');
  17815. var verticalFlip = makeValueTransform(flip$1, 'v');
  17816. var counterclockwiseRotate = makeValueTransform(rotate$1, -90);
  17817. var clockwiseRotate = makeValueTransform(rotate$1, 90);
  17818. var flipRotateOnAction = function (comp, operation) {
  17819. emitTempTransform(comp, operation);
  17820. };
  17821. var flipRotateComponents = [
  17822. createBackButton(),
  17823. createSpacer(),
  17824. createIconButton('flip-horizontally', 'Flip horizontally', function (button) {
  17825. flipRotateOnAction(button, horizontalFlip);
  17826. }, false),
  17827. createIconButton('flip-vertically', 'Flip vertically', function (button) {
  17828. flipRotateOnAction(button, verticalFlip);
  17829. }, false),
  17830. createIconButton('rotate-left', 'Rotate counterclockwise', function (button) {
  17831. flipRotateOnAction(button, counterclockwiseRotate);
  17832. }, false),
  17833. createIconButton('rotate-right', 'Rotate clockwise', function (button) {
  17834. flipRotateOnAction(button, clockwiseRotate);
  17835. }, false),
  17836. createSpacer(),
  17837. createApplyButton()
  17838. ];
  17839. var FlipRotatePanel = Container.sketch({
  17840. dom: panelDom,
  17841. components: flipRotateComponents.map(function (mem) {
  17842. return mem.asSpec();
  17843. }),
  17844. containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [
  17845. run(external$2.disable(), function (comp, _se) {
  17846. disableAllComponents(flipRotateComponents, comp);
  17847. }),
  17848. run(external$2.enable(), function (comp, _se) {
  17849. enableAllComponents(flipRotateComponents, comp);
  17850. })
  17851. ])])
  17852. });
  17853. var makeSlider = function (label, onChoose, min, value, max) {
  17854. var labelPart = Slider.parts().label({
  17855. dom: {
  17856. tag: 'label',
  17857. classes: ['tox-label'],
  17858. innerHtml: providersBackstage.translate(label)
  17859. }
  17860. });
  17861. var spectrum = Slider.parts().spectrum({
  17862. dom: {
  17863. tag: 'div',
  17864. classes: ['tox-slider__rail'],
  17865. attributes: { role: 'presentation' }
  17866. }
  17867. });
  17868. var thumb = Slider.parts().thumb({
  17869. dom: {
  17870. tag: 'div',
  17871. classes: ['tox-slider__handle'],
  17872. attributes: { role: 'presentation' }
  17873. }
  17874. });
  17875. return record(Slider.sketch({
  17876. dom: {
  17877. tag: 'div',
  17878. classes: ['tox-slider'],
  17879. attributes: { role: 'presentation' }
  17880. },
  17881. model: {
  17882. mode: 'x',
  17883. minX: min,
  17884. maxX: max,
  17885. getInitialValue: constant({ x: constant(value) })
  17886. },
  17887. components: [
  17888. labelPart,
  17889. spectrum,
  17890. thumb
  17891. ],
  17892. sliderBehaviours: derive$1([Focusing.config({})]),
  17893. onChoose: onChoose
  17894. }));
  17895. };
  17896. var makeVariableSlider = function (label, transform, min, value, max) {
  17897. var onChoose = function (slider, _thumb, value) {
  17898. var valTransform = makeValueTransform(transform, value.x() / 100);
  17899. emitTransform(slider, valTransform);
  17900. };
  17901. return makeSlider(label, onChoose, min, value, max);
  17902. };
  17903. var variableFilterPanelComponents = function (label, transform, min, value, max) {
  17904. return [
  17905. createBackButton(),
  17906. makeVariableSlider(label, transform, min, value, max),
  17907. createApplyButton()
  17908. ];
  17909. };
  17910. var createVariableFilterPanel = function (label, transform, min, value, max) {
  17911. var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max);
  17912. return Container.sketch({
  17913. dom: panelDom,
  17914. components: filterPanelComponents.map(function (mem) {
  17915. return mem.asSpec();
  17916. }),
  17917. containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [
  17918. run(external$2.disable(), function (comp, _se) {
  17919. disableAllComponents(filterPanelComponents, comp);
  17920. }),
  17921. run(external$2.enable(), function (comp, _se) {
  17922. enableAllComponents(filterPanelComponents, comp);
  17923. })
  17924. ])])
  17925. });
  17926. };
  17927. var filterPanelComponents = [
  17928. createBackButton(),
  17929. createSpacer(),
  17930. createApplyButton()
  17931. ];
  17932. var FilterPanel = Container.sketch({
  17933. dom: panelDom,
  17934. components: filterPanelComponents.map(function (mem) {
  17935. return mem.asSpec();
  17936. })
  17937. });
  17938. var BrightnessPanel = createVariableFilterPanel('Brightness', brightness$1, -100, 0, 100);
  17939. var ContrastPanel = createVariableFilterPanel('Contrast', contrast$1, -100, 0, 100);
  17940. var GammaPanel = createVariableFilterPanel('Gamma', gamma$1, -100, 0, 100);
  17941. var makeColorTransform = function (red, green, blue) {
  17942. return function (ir) {
  17943. return colorize$1(ir, red, green, blue);
  17944. };
  17945. };
  17946. var makeColorSlider = function (label) {
  17947. var onChoose = function (slider, _thumb, _value) {
  17948. var redOpt = memRed.getOpt(slider);
  17949. var blueOpt = memBlue.getOpt(slider);
  17950. var greenOpt = memGreen.getOpt(slider);
  17951. redOpt.each(function (red) {
  17952. blueOpt.each(function (blue) {
  17953. greenOpt.each(function (green) {
  17954. var r = Representing.getValue(red).x() / 100;
  17955. var g = Representing.getValue(green).x() / 100;
  17956. var b = Representing.getValue(blue).x() / 100;
  17957. var transform = makeColorTransform(r, g, b);
  17958. emitTransform(slider, transform);
  17959. });
  17960. });
  17961. });
  17962. };
  17963. return makeSlider(label, onChoose, 0, 100, 200);
  17964. };
  17965. var memRed = makeColorSlider('R');
  17966. var memGreen = makeColorSlider('G');
  17967. var memBlue = makeColorSlider('B');
  17968. var colorizePanelComponents = [
  17969. createBackButton(),
  17970. memRed,
  17971. memGreen,
  17972. memBlue,
  17973. createApplyButton()
  17974. ];
  17975. var ColorizePanel = Container.sketch({
  17976. dom: panelDom,
  17977. components: colorizePanelComponents.map(function (mem) {
  17978. return mem.asSpec();
  17979. })
  17980. });
  17981. var getTransformPanelEvent = function (panel, transform, update) {
  17982. return function (button) {
  17983. var swap = function () {
  17984. memContainer.getOpt(button).each(function (container) {
  17985. Replacing.set(container, [panel]);
  17986. update(container);
  17987. });
  17988. };
  17989. emit$1(button, internal.swap(), {
  17990. transform: transform,
  17991. swap: swap
  17992. });
  17993. };
  17994. };
  17995. var cropPanelUpdate = function (_anyInSystem) {
  17996. imagePanel.showCrop();
  17997. };
  17998. var resizePanelUpdate = function (anyInSystem) {
  17999. memSize.getOpt(anyInSystem).each(function (sizeInput) {
  18000. var measurements = imagePanel.getMeasurements();
  18001. var width = measurements.width;
  18002. var height = measurements.height;
  18003. Representing.setValue(sizeInput, {
  18004. width: width,
  18005. height: height
  18006. });
  18007. });
  18008. };
  18009. var sharpenTransform = Option.some(sharpen$1);
  18010. var invertTransform = Option.some(invert$1);
  18011. var buttonPanelComponents = [
  18012. createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Option.none(), cropPanelUpdate), false),
  18013. createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Option.none(), resizePanelUpdate), false),
  18014. createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Option.none(), noop$1), false),
  18015. createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Option.none(), noop$1), false),
  18016. createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false),
  18017. createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Option.none(), noop$1), false),
  18018. createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Option.none(), noop$1), false),
  18019. createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Option.none(), noop$1), false),
  18020. createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false)
  18021. ];
  18022. var ButtonPanel = Container.sketch({
  18023. dom: panelDom,
  18024. components: buttonPanelComponents.map(function (mem) {
  18025. return mem.asSpec();
  18026. })
  18027. });
  18028. var container = Container.sketch({
  18029. dom: { tag: 'div' },
  18030. components: [ButtonPanel],
  18031. containerBehaviours: derive$1([Replacing.config({})])
  18032. });
  18033. var memContainer = record(container);
  18034. var getApplyButton = function (anyInSystem) {
  18035. return memContainer.getOpt(anyInSystem).map(function (container) {
  18036. var panel = container.components()[0];
  18037. return panel.components()[panel.components().length - 1];
  18038. });
  18039. };
  18040. return {
  18041. memContainer: memContainer,
  18042. getApplyButton: getApplyButton
  18043. };
  18044. };
  18045. var global$b = tinymce.util.Tools.resolve('tinymce.dom.DomQuery');
  18046. var global$c = tinymce.util.Tools.resolve('tinymce.geom.Rect');
  18047. var global$d = tinymce.util.Tools.resolve('tinymce.util.Observable');
  18048. var global$e = tinymce.util.Tools.resolve('tinymce.util.Tools');
  18049. var global$f = tinymce.util.Tools.resolve('tinymce.util.VK');
  18050. function getDocumentSize(doc) {
  18051. var documentElement, body, scrollWidth, clientWidth;
  18052. var offsetWidth, scrollHeight, clientHeight, offsetHeight;
  18053. var max = Math.max;
  18054. documentElement = doc.documentElement;
  18055. body = doc.body;
  18056. scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  18057. clientWidth = max(documentElement.clientWidth, body.clientWidth);
  18058. offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  18059. scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  18060. clientHeight = max(documentElement.clientHeight, body.clientHeight);
  18061. offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  18062. return {
  18063. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  18064. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  18065. };
  18066. }
  18067. function updateWithTouchData(e) {
  18068. var keys, i;
  18069. if (e.changedTouches) {
  18070. keys = 'screenX screenY pageX pageY clientX clientY'.split(' ');
  18071. for (i = 0; i < keys.length; i++) {
  18072. e[keys[i]] = e.changedTouches[0][keys[i]];
  18073. }
  18074. }
  18075. }
  18076. function DragHelper (id, settings) {
  18077. var $eventOverlay;
  18078. var doc = settings.document || domGlobals.document;
  18079. var downButton;
  18080. var start, stop, drag, startX, startY;
  18081. settings = settings || {};
  18082. var handleElement = doc.getElementById(settings.handle || id);
  18083. start = function (e) {
  18084. var docSize = getDocumentSize(doc);
  18085. var handleElm, cursor;
  18086. updateWithTouchData(e);
  18087. e.preventDefault();
  18088. downButton = e.button;
  18089. handleElm = handleElement;
  18090. startX = e.screenX;
  18091. startY = e.screenY;
  18092. if (domGlobals.window.getComputedStyle) {
  18093. cursor = domGlobals.window.getComputedStyle(handleElm, null).getPropertyValue('cursor');
  18094. } else {
  18095. cursor = handleElm.runtimeStyle.cursor;
  18096. }
  18097. $eventOverlay = global$b('<div></div>').css({
  18098. position: 'absolute',
  18099. top: 0,
  18100. left: 0,
  18101. width: docSize.width,
  18102. height: docSize.height,
  18103. zIndex: 2147483647,
  18104. opacity: 0.0001,
  18105. cursor: cursor
  18106. }).appendTo(doc.body);
  18107. global$b(doc).on('mousemove touchmove', drag).on('mouseup touchend', stop);
  18108. settings.start(e);
  18109. };
  18110. drag = function (e) {
  18111. updateWithTouchData(e);
  18112. if (e.button !== downButton) {
  18113. return stop(e);
  18114. }
  18115. e.deltaX = e.screenX - startX;
  18116. e.deltaY = e.screenY - startY;
  18117. e.preventDefault();
  18118. settings.drag(e);
  18119. };
  18120. stop = function (e) {
  18121. updateWithTouchData(e);
  18122. global$b(doc).off('mousemove touchmove', drag).off('mouseup touchend', stop);
  18123. $eventOverlay.remove();
  18124. if (settings.stop) {
  18125. settings.stop(e);
  18126. }
  18127. };
  18128. this.destroy = function () {
  18129. global$b(handleElement).off();
  18130. };
  18131. global$b(handleElement).on('mousedown touchstart', start);
  18132. }
  18133. var count = 0;
  18134. var create$7 = function (currentRect, viewPortRect, clampRect, containerElm, action) {
  18135. var instance;
  18136. var dragHelpers;
  18137. var blockers;
  18138. var prefix = 'tox-';
  18139. var id = prefix + 'crid-' + count++;
  18140. var handles = [
  18141. {
  18142. name: 'move',
  18143. xMul: 0,
  18144. yMul: 0,
  18145. deltaX: 1,
  18146. deltaY: 1,
  18147. deltaW: 0,
  18148. deltaH: 0,
  18149. label: 'Crop Mask'
  18150. },
  18151. {
  18152. name: 'nw',
  18153. xMul: 0,
  18154. yMul: 0,
  18155. deltaX: 1,
  18156. deltaY: 1,
  18157. deltaW: -1,
  18158. deltaH: -1,
  18159. label: 'Top Left Crop Handle'
  18160. },
  18161. {
  18162. name: 'ne',
  18163. xMul: 1,
  18164. yMul: 0,
  18165. deltaX: 0,
  18166. deltaY: 1,
  18167. deltaW: 1,
  18168. deltaH: -1,
  18169. label: 'Top Right Crop Handle'
  18170. },
  18171. {
  18172. name: 'sw',
  18173. xMul: 0,
  18174. yMul: 1,
  18175. deltaX: 1,
  18176. deltaY: 0,
  18177. deltaW: -1,
  18178. deltaH: 1,
  18179. label: 'Bottom Left Crop Handle'
  18180. },
  18181. {
  18182. name: 'se',
  18183. xMul: 1,
  18184. yMul: 1,
  18185. deltaX: 0,
  18186. deltaY: 0,
  18187. deltaW: 1,
  18188. deltaH: 1,
  18189. label: 'Bottom Right Crop Handle'
  18190. }
  18191. ];
  18192. blockers = [
  18193. 'top',
  18194. 'right',
  18195. 'bottom',
  18196. 'left'
  18197. ];
  18198. var getAbsoluteRect = function (outerRect, relativeRect) {
  18199. return {
  18200. x: relativeRect.x + outerRect.x,
  18201. y: relativeRect.y + outerRect.y,
  18202. w: relativeRect.w,
  18203. h: relativeRect.h
  18204. };
  18205. };
  18206. var getRelativeRect = function (outerRect, innerRect) {
  18207. return {
  18208. x: innerRect.x - outerRect.x,
  18209. y: innerRect.y - outerRect.y,
  18210. w: innerRect.w,
  18211. h: innerRect.h
  18212. };
  18213. };
  18214. var getInnerRect = function () {
  18215. return getRelativeRect(clampRect, currentRect);
  18216. };
  18217. function moveRect(handle, startRect, deltaX, deltaY) {
  18218. var x, y, w, h, rect;
  18219. x = startRect.x;
  18220. y = startRect.y;
  18221. w = startRect.w;
  18222. h = startRect.h;
  18223. x += deltaX * handle.deltaX;
  18224. y += deltaY * handle.deltaY;
  18225. w += deltaX * handle.deltaW;
  18226. h += deltaY * handle.deltaH;
  18227. if (w < 20) {
  18228. w = 20;
  18229. }
  18230. if (h < 20) {
  18231. h = 20;
  18232. }
  18233. rect = currentRect = global$c.clamp({
  18234. x: x,
  18235. y: y,
  18236. w: w,
  18237. h: h
  18238. }, clampRect, handle.name === 'move');
  18239. rect = getRelativeRect(clampRect, rect);
  18240. instance.fire('updateRect', { rect: rect });
  18241. setInnerRect(rect);
  18242. }
  18243. function render() {
  18244. function createDragHelper(handle) {
  18245. var startRect;
  18246. return new DragHelper(id, {
  18247. document: containerElm.ownerDocument,
  18248. handle: id + '-' + handle.name,
  18249. start: function () {
  18250. startRect = currentRect;
  18251. },
  18252. drag: function (e) {
  18253. moveRect(handle, startRect, e.deltaX, e.deltaY);
  18254. }
  18255. });
  18256. }
  18257. global$b('<div id="' + id + '" class="' + prefix + 'croprect-container"' + ' role="grid" aria-dropeffect="execute">').appendTo(containerElm);
  18258. global$e.each(blockers, function (blocker) {
  18259. global$b('#' + id, containerElm).append('<div id="' + id + '-' + blocker + '"class="' + prefix + 'croprect-block" style="display: none" data-mce-bogus="all">');
  18260. });
  18261. global$e.each(handles, function (handle) {
  18262. global$b('#' + id, containerElm).append('<div id="' + id + '-' + handle.name + '" class="' + prefix + 'croprect-handle ' + prefix + 'croprect-handle-' + handle.name + '"' + 'style="display: none" data-mce-bogus="all" role="gridcell" tabindex="-1"' + ' aria-label="' + handle.label + '" aria-grabbed="false" title="' + handle.label + '">');
  18263. });
  18264. dragHelpers = global$e.map(handles, createDragHelper);
  18265. repaint(currentRect);
  18266. global$b(containerElm).on('focusin focusout', function (e) {
  18267. global$b(e.target).attr('aria-grabbed', e.type === 'focus' ? 'true' : 'false');
  18268. });
  18269. global$b(containerElm).on('keydown', function (e) {
  18270. var activeHandle;
  18271. global$e.each(handles, function (handle) {
  18272. if (e.target.id === id + '-' + handle.name) {
  18273. activeHandle = handle;
  18274. return false;
  18275. }
  18276. });
  18277. function moveAndBlock(evt, handle, startRect, deltaX, deltaY) {
  18278. evt.stopPropagation();
  18279. evt.preventDefault();
  18280. moveRect(activeHandle, startRect, deltaX, deltaY);
  18281. }
  18282. switch (e.keyCode) {
  18283. case global$f.LEFT:
  18284. moveAndBlock(e, activeHandle, currentRect, -10, 0);
  18285. break;
  18286. case global$f.RIGHT:
  18287. moveAndBlock(e, activeHandle, currentRect, 10, 0);
  18288. break;
  18289. case global$f.UP:
  18290. moveAndBlock(e, activeHandle, currentRect, 0, -10);
  18291. break;
  18292. case global$f.DOWN:
  18293. moveAndBlock(e, activeHandle, currentRect, 0, 10);
  18294. break;
  18295. case global$f.ENTER:
  18296. case global$f.SPACEBAR:
  18297. e.preventDefault();
  18298. action();
  18299. break;
  18300. }
  18301. });
  18302. }
  18303. function toggleVisibility(state) {
  18304. var selectors;
  18305. selectors = global$e.map(handles, function (handle) {
  18306. return '#' + id + '-' + handle.name;
  18307. }).concat(global$e.map(blockers, function (blocker) {
  18308. return '#' + id + '-' + blocker;
  18309. })).join(',');
  18310. if (state) {
  18311. global$b(selectors, containerElm).show();
  18312. } else {
  18313. global$b(selectors, containerElm).hide();
  18314. }
  18315. }
  18316. function repaint(rect) {
  18317. function updateElementRect(name, rect) {
  18318. if (rect.h < 0) {
  18319. rect.h = 0;
  18320. }
  18321. if (rect.w < 0) {
  18322. rect.w = 0;
  18323. }
  18324. global$b('#' + id + '-' + name, containerElm).css({
  18325. left: rect.x,
  18326. top: rect.y,
  18327. width: rect.w,
  18328. height: rect.h
  18329. });
  18330. }
  18331. global$e.each(handles, function (handle) {
  18332. global$b('#' + id + '-' + handle.name, containerElm).css({
  18333. left: rect.w * handle.xMul + rect.x,
  18334. top: rect.h * handle.yMul + rect.y
  18335. });
  18336. });
  18337. updateElementRect('top', {
  18338. x: viewPortRect.x,
  18339. y: viewPortRect.y,
  18340. w: viewPortRect.w,
  18341. h: rect.y - viewPortRect.y
  18342. });
  18343. updateElementRect('right', {
  18344. x: rect.x + rect.w,
  18345. y: rect.y,
  18346. w: viewPortRect.w - rect.x - rect.w + viewPortRect.x,
  18347. h: rect.h
  18348. });
  18349. updateElementRect('bottom', {
  18350. x: viewPortRect.x,
  18351. y: rect.y + rect.h,
  18352. w: viewPortRect.w,
  18353. h: viewPortRect.h - rect.y - rect.h + viewPortRect.y
  18354. });
  18355. updateElementRect('left', {
  18356. x: viewPortRect.x,
  18357. y: rect.y,
  18358. w: rect.x - viewPortRect.x,
  18359. h: rect.h
  18360. });
  18361. updateElementRect('move', rect);
  18362. }
  18363. function setRect(rect) {
  18364. currentRect = rect;
  18365. repaint(currentRect);
  18366. }
  18367. function setViewPortRect(rect) {
  18368. viewPortRect = rect;
  18369. repaint(currentRect);
  18370. }
  18371. function setInnerRect(rect) {
  18372. setRect(getAbsoluteRect(clampRect, rect));
  18373. }
  18374. function setClampRect(rect) {
  18375. clampRect = rect;
  18376. repaint(currentRect);
  18377. }
  18378. function destroy() {
  18379. global$e.each(dragHelpers, function (helper) {
  18380. helper.destroy();
  18381. });
  18382. dragHelpers = [];
  18383. }
  18384. render();
  18385. instance = global$e.extend({
  18386. toggleVisibility: toggleVisibility,
  18387. setClampRect: setClampRect,
  18388. setRect: setRect,
  18389. getInnerRect: getInnerRect,
  18390. setInnerRect: setInnerRect,
  18391. setViewPortRect: setViewPortRect,
  18392. destroy: destroy
  18393. }, global$d);
  18394. return instance;
  18395. };
  18396. var CropRect = { create: create$7 };
  18397. var loadImage = function (image) {
  18398. return new global$4(function (resolve) {
  18399. var loaded = function () {
  18400. image.removeEventListener('load', loaded);
  18401. resolve(image);
  18402. };
  18403. if (image.complete) {
  18404. resolve(image);
  18405. } else {
  18406. image.addEventListener('load', loaded);
  18407. }
  18408. });
  18409. };
  18410. var renderImagePanel = function (initialUrl) {
  18411. var memBg = record({
  18412. dom: {
  18413. tag: 'div',
  18414. classes: ['tox-image-tools__image-bg'],
  18415. attributes: { role: 'presentation' }
  18416. }
  18417. });
  18418. var zoomState = Cell(1);
  18419. var cropRect = Cell(Option.none());
  18420. var rectState = Cell({
  18421. x: 0,
  18422. y: 0,
  18423. w: 1,
  18424. h: 1
  18425. });
  18426. var viewRectState = Cell({
  18427. x: 0,
  18428. y: 0,
  18429. w: 1,
  18430. h: 1
  18431. });
  18432. var repaintImg = function (anyInSystem, img) {
  18433. memContainer.getOpt(anyInSystem).each(function (panel) {
  18434. var zoom = zoomState.get();
  18435. var panelW = get$7(panel.element());
  18436. var panelH = get$6(panel.element());
  18437. var width = img.dom().naturalWidth * zoom;
  18438. var height = img.dom().naturalHeight * zoom;
  18439. var left = Math.max(0, panelW / 2 - width / 2);
  18440. var top = Math.max(0, panelH / 2 - height / 2);
  18441. var css = {
  18442. left: left.toString() + 'px',
  18443. top: top.toString() + 'px',
  18444. width: width.toString() + 'px',
  18445. height: height.toString() + 'px',
  18446. position: 'absolute'
  18447. };
  18448. setAll$1(img, css);
  18449. memBg.getOpt(panel).each(function (bg) {
  18450. setAll$1(bg.element(), css);
  18451. });
  18452. cropRect.get().each(function (cRect) {
  18453. var rect = rectState.get();
  18454. cRect.setRect({
  18455. x: rect.x * zoom + left,
  18456. y: rect.y * zoom + top,
  18457. w: rect.w * zoom,
  18458. h: rect.h * zoom
  18459. });
  18460. cRect.setClampRect({
  18461. x: left,
  18462. y: top,
  18463. w: width,
  18464. h: height
  18465. });
  18466. cRect.setViewPortRect({
  18467. x: 0,
  18468. y: 0,
  18469. w: panelW,
  18470. h: panelH
  18471. });
  18472. });
  18473. });
  18474. };
  18475. var zoomFit = function (anyInSystem, img) {
  18476. memContainer.getOpt(anyInSystem).each(function (panel) {
  18477. var panelW = get$7(panel.element());
  18478. var panelH = get$6(panel.element());
  18479. var width = img.dom().naturalWidth;
  18480. var height = img.dom().naturalHeight;
  18481. var zoom = Math.min(panelW / width, panelH / height);
  18482. if (zoom >= 1) {
  18483. zoomState.set(1);
  18484. } else {
  18485. zoomState.set(zoom);
  18486. }
  18487. });
  18488. };
  18489. var updateSrc = function (anyInSystem, url) {
  18490. var img = Element.fromTag('img');
  18491. set$1(img, 'src', url);
  18492. return loadImage(img.dom()).then(function () {
  18493. return memContainer.getOpt(anyInSystem).map(function (panel) {
  18494. var aImg = external({ element: img });
  18495. Replacing.replaceAt(panel, 1, Option.some(aImg));
  18496. var lastViewRect = viewRectState.get();
  18497. var viewRect = {
  18498. x: 0,
  18499. y: 0,
  18500. w: img.dom().naturalWidth,
  18501. h: img.dom().naturalHeight
  18502. };
  18503. viewRectState.set(viewRect);
  18504. var rect = global$c.inflate(viewRect, -20, -20);
  18505. rectState.set(rect);
  18506. if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) {
  18507. zoomFit(panel, img);
  18508. }
  18509. repaintImg(panel, img);
  18510. return img;
  18511. });
  18512. });
  18513. };
  18514. var zoom = function (anyInSystem, direction) {
  18515. var currentZoom = zoomState.get();
  18516. var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1);
  18517. zoomState.set(newZoom);
  18518. memContainer.getOpt(anyInSystem).each(function (panel) {
  18519. var img = panel.components()[1].element();
  18520. repaintImg(panel, img);
  18521. });
  18522. };
  18523. var showCrop = function () {
  18524. cropRect.get().each(function (cRect) {
  18525. cRect.toggleVisibility(true);
  18526. });
  18527. };
  18528. var hideCrop = function () {
  18529. cropRect.get().each(function (cRect) {
  18530. cRect.toggleVisibility(false);
  18531. });
  18532. };
  18533. var getRect = function () {
  18534. return rectState.get();
  18535. };
  18536. var container = Container.sketch({
  18537. dom: {
  18538. tag: 'div',
  18539. classes: ['tox-image-tools__image']
  18540. },
  18541. components: [
  18542. memBg.asSpec(),
  18543. {
  18544. dom: {
  18545. tag: 'img',
  18546. attributes: { src: initialUrl }
  18547. }
  18548. },
  18549. {
  18550. dom: { tag: 'div' },
  18551. behaviours: derive$1([config('image-panel-crop-events', [runOnAttached(function (comp) {
  18552. memContainer.getOpt(comp).each(function (container) {
  18553. var el = container.element().dom();
  18554. var cRect = CropRect.create({
  18555. x: 10,
  18556. y: 10,
  18557. w: 100,
  18558. h: 100
  18559. }, {
  18560. x: 0,
  18561. y: 0,
  18562. w: 200,
  18563. h: 200
  18564. }, {
  18565. x: 0,
  18566. y: 0,
  18567. w: 200,
  18568. h: 200
  18569. }, el, function () {
  18570. });
  18571. cRect.toggleVisibility(false);
  18572. cRect.on('updateRect', function (e) {
  18573. var rect = e.rect;
  18574. var zoom = zoomState.get();
  18575. var newRect = {
  18576. x: Math.round(rect.x / zoom),
  18577. y: Math.round(rect.y / zoom),
  18578. w: Math.round(rect.w / zoom),
  18579. h: Math.round(rect.h / zoom)
  18580. };
  18581. rectState.set(newRect);
  18582. });
  18583. cropRect.set(Option.some(cRect));
  18584. });
  18585. })])])
  18586. }
  18587. ],
  18588. containerBehaviours: derive$1([
  18589. Replacing.config({}),
  18590. config('image-panel-events', [runOnAttached(function (comp) {
  18591. updateSrc(comp, initialUrl);
  18592. })])
  18593. ])
  18594. });
  18595. var memContainer = record(container);
  18596. var getMeasurements = function () {
  18597. var viewRect = viewRectState.get();
  18598. return {
  18599. width: viewRect.w,
  18600. height: viewRect.h
  18601. };
  18602. };
  18603. return {
  18604. memContainer: memContainer,
  18605. updateSrc: updateSrc,
  18606. zoom: zoom,
  18607. showCrop: showCrop,
  18608. hideCrop: hideCrop,
  18609. getRect: getRect,
  18610. getMeasurements: getMeasurements
  18611. };
  18612. };
  18613. var createButton = function (innerHtml, icon, disabled, action, providersBackstage) {
  18614. return renderIconButton({
  18615. name: innerHtml,
  18616. icon: Option.some(icon),
  18617. disabled: disabled,
  18618. tooltip: Option.some(innerHtml),
  18619. primary: false,
  18620. borderless: false
  18621. }, action, providersBackstage);
  18622. };
  18623. var setButtonEnabled = function (button, enabled) {
  18624. if (enabled) {
  18625. Disabling.enable(button);
  18626. } else {
  18627. Disabling.disable(button);
  18628. }
  18629. };
  18630. var renderSideBar = function (providersBackstage) {
  18631. var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) {
  18632. memUndo.getOpt(anyInSystem).each(function (undo) {
  18633. setButtonEnabled(undo, undoEnabled);
  18634. });
  18635. memRedo.getOpt(anyInSystem).each(function (redo) {
  18636. setButtonEnabled(redo, redoEnabled);
  18637. });
  18638. };
  18639. var memUndo = record(createButton('Undo', 'undo', true, function (button) {
  18640. emitWith(button, internal.undo(), { direction: 1 });
  18641. }, providersBackstage));
  18642. var memRedo = record(createButton('Redo', 'redo', true, function (button) {
  18643. emitWith(button, internal.redo(), { direction: 1 });
  18644. }, providersBackstage));
  18645. var container = Container.sketch({
  18646. dom: {
  18647. tag: 'div',
  18648. classes: [
  18649. 'tox-image-tools__toolbar',
  18650. 'tox-image-tools__sidebar'
  18651. ]
  18652. },
  18653. components: [
  18654. memUndo.asSpec(),
  18655. memRedo.asSpec(),
  18656. createButton('Zoom in', 'zoom-in', false, function (button) {
  18657. emitWith(button, internal.zoom(), { direction: 1 });
  18658. }, providersBackstage),
  18659. createButton('Zoom out', 'zoom-out', false, function (button) {
  18660. emitWith(button, internal.zoom(), { direction: -1 });
  18661. }, providersBackstage)
  18662. ]
  18663. });
  18664. return {
  18665. container: container,
  18666. updateButtonUndoStates: updateButtonUndoStates
  18667. };
  18668. };
  18669. function UndoStack () {
  18670. var data = [];
  18671. var index = -1;
  18672. function add(state) {
  18673. var removed;
  18674. removed = data.splice(++index);
  18675. data.push(state);
  18676. return {
  18677. state: state,
  18678. removed: removed
  18679. };
  18680. }
  18681. function undo() {
  18682. if (canUndo()) {
  18683. return data[--index];
  18684. }
  18685. }
  18686. function redo() {
  18687. if (canRedo()) {
  18688. return data[++index];
  18689. }
  18690. }
  18691. function canUndo() {
  18692. return index > 0;
  18693. }
  18694. function canRedo() {
  18695. return index !== -1 && index < data.length - 1;
  18696. }
  18697. return {
  18698. data: data,
  18699. add: add,
  18700. undo: undo,
  18701. redo: redo,
  18702. canUndo: canUndo,
  18703. canRedo: canRedo
  18704. };
  18705. }
  18706. var makeState = function (initialState) {
  18707. var blobState = Cell(initialState);
  18708. var tempState = Cell(Option.none());
  18709. var undoStack = UndoStack();
  18710. undoStack.add(initialState);
  18711. var getBlobState = function () {
  18712. return blobState.get();
  18713. };
  18714. var setBlobState = function (state) {
  18715. blobState.set(state);
  18716. };
  18717. var getTempState = function () {
  18718. return tempState.get().fold(function () {
  18719. return blobState.get();
  18720. }, function (temp) {
  18721. return temp;
  18722. });
  18723. };
  18724. var updateTempState = function (blob) {
  18725. var newTempState = createState(blob);
  18726. destroyTempState();
  18727. tempState.set(Option.some(newTempState));
  18728. return newTempState.url;
  18729. };
  18730. var createState = function (blob) {
  18731. return {
  18732. blob: blob,
  18733. url: domGlobals.URL.createObjectURL(blob)
  18734. };
  18735. };
  18736. var destroyState = function (state) {
  18737. domGlobals.URL.revokeObjectURL(state.url);
  18738. };
  18739. var destroyStates = function (states) {
  18740. global$e.each(states, destroyState);
  18741. };
  18742. var destroyTempState = function () {
  18743. tempState.get().each(destroyState);
  18744. tempState.set(Option.none());
  18745. };
  18746. var addBlobState = function (blob) {
  18747. var newState = createState(blob);
  18748. setBlobState(newState);
  18749. var removed = undoStack.add(newState).removed;
  18750. destroyStates(removed);
  18751. return newState.url;
  18752. };
  18753. var addTempState = function (blob) {
  18754. var newState = createState(blob);
  18755. tempState.set(Option.some(newState));
  18756. return newState.url;
  18757. };
  18758. var applyTempState = function (postApply) {
  18759. return tempState.get().fold(function () {
  18760. }, function (temp) {
  18761. addBlobState(temp.blob);
  18762. postApply();
  18763. });
  18764. };
  18765. var undo = function () {
  18766. var currentState = undoStack.undo();
  18767. setBlobState(currentState);
  18768. return currentState.url;
  18769. };
  18770. var redo = function () {
  18771. var currentState = undoStack.redo();
  18772. setBlobState(currentState);
  18773. return currentState.url;
  18774. };
  18775. var getHistoryStates = function () {
  18776. var undoEnabled = undoStack.canUndo();
  18777. var redoEnabled = undoStack.canRedo();
  18778. return {
  18779. undoEnabled: undoEnabled,
  18780. redoEnabled: redoEnabled
  18781. };
  18782. };
  18783. return {
  18784. getBlobState: getBlobState,
  18785. setBlobState: setBlobState,
  18786. addBlobState: addBlobState,
  18787. getTempState: getTempState,
  18788. updateTempState: updateTempState,
  18789. addTempState: addTempState,
  18790. applyTempState: applyTempState,
  18791. destroyTempState: destroyTempState,
  18792. undo: undo,
  18793. redo: redo,
  18794. getHistoryStates: getHistoryStates
  18795. };
  18796. };
  18797. var renderImageTools = function (detail, providersBackstage) {
  18798. var state = makeState(detail.currentState);
  18799. var zoom = function (anyInSystem, simulatedEvent) {
  18800. var direction = simulatedEvent.event().direction();
  18801. imagePanel.zoom(anyInSystem, direction);
  18802. };
  18803. var updateButtonUndoStates = function (anyInSystem) {
  18804. var historyStates = state.getHistoryStates();
  18805. sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled);
  18806. emitWith(anyInSystem, external$2.formActionEvent, {
  18807. name: external$2.saveState(),
  18808. value: historyStates.undoEnabled
  18809. });
  18810. };
  18811. var disableUndoRedo = function (anyInSystem) {
  18812. sideBar.updateButtonUndoStates(anyInSystem, false, false);
  18813. };
  18814. var undo = function (anyInSystem, _simulatedEvent) {
  18815. var url = state.undo();
  18816. updateSrc(anyInSystem, url).then(function (_oImg) {
  18817. unblock(anyInSystem);
  18818. updateButtonUndoStates(anyInSystem);
  18819. });
  18820. };
  18821. var redo = function (anyInSystem, _simulatedEvent) {
  18822. var url = state.redo();
  18823. updateSrc(anyInSystem, url).then(function (_oImg) {
  18824. unblock(anyInSystem);
  18825. updateButtonUndoStates(anyInSystem);
  18826. });
  18827. };
  18828. var imageResultToBlob = function (ir) {
  18829. return ir.toBlob();
  18830. };
  18831. var block = function (anyInSystem) {
  18832. emitWith(anyInSystem, external$2.formActionEvent, {
  18833. name: external$2.disable(),
  18834. value: {}
  18835. });
  18836. };
  18837. var unblock = function (anyInSystem) {
  18838. editPanel.getApplyButton(anyInSystem).each(function (applyButton) {
  18839. Disabling.enable(applyButton);
  18840. });
  18841. emitWith(anyInSystem, external$2.formActionEvent, {
  18842. name: external$2.enable(),
  18843. value: {}
  18844. });
  18845. };
  18846. var updateSrc = function (anyInSystem, src) {
  18847. block(anyInSystem);
  18848. return imagePanel.updateSrc(anyInSystem, src);
  18849. };
  18850. var blobManipulate = function (anyInSystem, blob, filter, action, swap) {
  18851. block(anyInSystem);
  18852. return blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) {
  18853. return updateSrc(anyInSystem, url).then(function (oImg) {
  18854. updateButtonUndoStates(anyInSystem);
  18855. swap();
  18856. unblock(anyInSystem);
  18857. return oImg;
  18858. });
  18859. }).catch(function (err) {
  18860. domGlobals.console.log(err);
  18861. unblock(anyInSystem);
  18862. return err;
  18863. });
  18864. };
  18865. var manipulate = function (anyInSystem, filter, swap) {
  18866. var blob = state.getBlobState().blob;
  18867. var action = function (blob) {
  18868. return state.updateTempState(blob);
  18869. };
  18870. blobManipulate(anyInSystem, blob, filter, action, swap);
  18871. };
  18872. var tempManipulate = function (anyInSystem, filter) {
  18873. var blob = state.getTempState().blob;
  18874. var action = function (blob) {
  18875. return state.addTempState(blob);
  18876. };
  18877. blobManipulate(anyInSystem, blob, filter, action, noop);
  18878. };
  18879. var manipulateApply = function (anyInSystem, filter, swap) {
  18880. var blob = state.getBlobState().blob;
  18881. var action = function (blob) {
  18882. var url = state.addBlobState(blob);
  18883. destroyTempState(anyInSystem);
  18884. return url;
  18885. };
  18886. blobManipulate(anyInSystem, blob, filter, action, swap);
  18887. };
  18888. var apply = function (anyInSystem, simulatedEvent) {
  18889. var postApply = function () {
  18890. destroyTempState(anyInSystem);
  18891. var swap = simulatedEvent.event().swap();
  18892. swap();
  18893. };
  18894. state.applyTempState(postApply);
  18895. };
  18896. var destroyTempState = function (anyInSystem) {
  18897. var currentUrl = state.getBlobState().url;
  18898. state.destroyTempState();
  18899. updateButtonUndoStates(anyInSystem);
  18900. return currentUrl;
  18901. };
  18902. var cancel = function (anyInSystem) {
  18903. var currentUrl = destroyTempState(anyInSystem);
  18904. updateSrc(anyInSystem, currentUrl).then(function (_oImg) {
  18905. unblock(anyInSystem);
  18906. });
  18907. };
  18908. var back = function (anyInSystem, simulatedEvent) {
  18909. cancel(anyInSystem);
  18910. var swap = simulatedEvent.event().swap();
  18911. swap();
  18912. imagePanel.hideCrop();
  18913. };
  18914. var transform = function (anyInSystem, simulatedEvent) {
  18915. return manipulate(anyInSystem, simulatedEvent.event().transform(), noop);
  18916. };
  18917. var tempTransform = function (anyInSystem, simulatedEvent) {
  18918. return tempManipulate(anyInSystem, simulatedEvent.event().transform());
  18919. };
  18920. var transformApply = function (anyInSystem, simulatedEvent) {
  18921. return manipulateApply(anyInSystem, simulatedEvent.event().transform(), simulatedEvent.event().swap());
  18922. };
  18923. var imagePanel = renderImagePanel(detail.currentState.url);
  18924. var sideBar = renderSideBar(providersBackstage);
  18925. var editPanel = renderEditPanel(imagePanel, providersBackstage);
  18926. var swap = function (anyInSystem, simulatedEvent) {
  18927. disableUndoRedo(anyInSystem);
  18928. var transform = simulatedEvent.event().transform();
  18929. var swap = simulatedEvent.event().swap();
  18930. transform.fold(function () {
  18931. swap();
  18932. }, function (transform) {
  18933. manipulate(anyInSystem, transform, swap);
  18934. });
  18935. };
  18936. return {
  18937. dom: {
  18938. tag: 'div',
  18939. attributes: { role: 'presentation' }
  18940. },
  18941. components: [
  18942. editPanel.memContainer.asSpec(),
  18943. imagePanel.memContainer.asSpec(),
  18944. sideBar.container
  18945. ],
  18946. behaviours: derive$1([
  18947. Representing.config({
  18948. store: {
  18949. mode: 'manual',
  18950. getValue: function () {
  18951. return state.getBlobState();
  18952. }
  18953. }
  18954. }),
  18955. config('image-tools-events', [
  18956. run(internal.undo(), undo),
  18957. run(internal.redo(), redo),
  18958. run(internal.zoom(), zoom),
  18959. run(internal.back(), back),
  18960. run(internal.apply(), apply),
  18961. run(internal.transform(), transform),
  18962. run(internal.tempTransform(), tempTransform),
  18963. run(internal.transformApply(), transformApply),
  18964. run(internal.swap(), swap)
  18965. ]),
  18966. ComposingConfigs.self()
  18967. ])
  18968. };
  18969. };
  18970. var factory$8 = function (detail, _spec) {
  18971. var options = map(detail.options, function (option) {
  18972. return {
  18973. dom: {
  18974. tag: 'option',
  18975. value: option.value,
  18976. innerHtml: option.text
  18977. }
  18978. };
  18979. });
  18980. var initialValues = detail.data.map(function (v) {
  18981. return wrap$1('initialValue', v);
  18982. }).getOr({});
  18983. return {
  18984. uid: detail.uid,
  18985. dom: {
  18986. tag: 'select',
  18987. classes: detail.selectClasses,
  18988. attributes: detail.selectAttributes
  18989. },
  18990. components: options,
  18991. behaviours: augment(detail.selectBehaviours, [
  18992. Focusing.config({}),
  18993. Representing.config({
  18994. store: __assign({
  18995. mode: 'manual',
  18996. getValue: function (select) {
  18997. return get$5(select.element());
  18998. },
  18999. setValue: function (select, newValue) {
  19000. var found = find(detail.options, function (opt) {
  19001. return opt.value === newValue;
  19002. });
  19003. if (found.isSome()) {
  19004. set$3(select.element(), newValue);
  19005. }
  19006. }
  19007. }, initialValues)
  19008. })
  19009. ])
  19010. };
  19011. };
  19012. var HtmlSelect = single$2({
  19013. name: 'HtmlSelect',
  19014. configFields: [
  19015. strict$1('options'),
  19016. field$1('selectBehaviours', [
  19017. Focusing,
  19018. Representing
  19019. ]),
  19020. defaulted$1('selectClasses', []),
  19021. defaulted$1('selectAttributes', {}),
  19022. option('data')
  19023. ],
  19024. factory: factory$8
  19025. });
  19026. var renderSelectBox = function (spec, providersBackstage) {
  19027. var translatedOptions = map(spec.items, function (item) {
  19028. return {
  19029. text: providersBackstage.translate(item.text),
  19030. value: item.value
  19031. };
  19032. });
  19033. var pLabel = spec.label.map(function (label) {
  19034. return renderLabel(label, providersBackstage);
  19035. });
  19036. var pField = FormField.parts().field({
  19037. dom: {},
  19038. selectAttributes: { size: spec.size },
  19039. options: translatedOptions,
  19040. factory: HtmlSelect,
  19041. selectBehaviours: derive$1([
  19042. Disabling.config({
  19043. disabled: function () {
  19044. return spec.disabled || providersBackstage.isReadOnly();
  19045. }
  19046. }),
  19047. Tabstopping.config({}),
  19048. config('selectbox-change', [run(change(), function (component, _) {
  19049. emitWith(component, formChangeEvent, { name: spec.name });
  19050. })])
  19051. ])
  19052. });
  19053. var chevron = spec.size > 1 ? Option.none() : Option.some({
  19054. dom: {
  19055. tag: 'div',
  19056. classes: ['tox-selectfield__icon-js'],
  19057. innerHtml: get$d('chevron-down', providersBackstage.icons)
  19058. }
  19059. });
  19060. var selectWrap = {
  19061. dom: {
  19062. tag: 'div',
  19063. classes: ['tox-selectfield']
  19064. },
  19065. components: flatten([
  19066. [pField],
  19067. chevron.toArray()
  19068. ])
  19069. };
  19070. return FormField.sketch({
  19071. dom: {
  19072. tag: 'div',
  19073. classes: ['tox-form__group']
  19074. },
  19075. components: flatten([
  19076. pLabel.toArray(),
  19077. [selectWrap]
  19078. ]),
  19079. fieldBehaviours: derive$1([
  19080. Disabling.config({
  19081. disabled: function () {
  19082. return spec.disabled || providersBackstage.isReadOnly();
  19083. },
  19084. onDisabled: function (comp) {
  19085. FormField.getField(comp).each(Disabling.disable);
  19086. },
  19087. onEnabled: function (comp) {
  19088. FormField.getField(comp).each(Disabling.enable);
  19089. }
  19090. }),
  19091. receivingConfig()
  19092. ])
  19093. });
  19094. };
  19095. var renderTextField = function (spec, providersBackstage) {
  19096. var pLabel = spec.label.map(function (label) {
  19097. return renderLabel(label, providersBackstage);
  19098. });
  19099. var baseInputBehaviours = [
  19100. Disabling.config({
  19101. disabled: function () {
  19102. return spec.disabled || providersBackstage.isReadOnly();
  19103. }
  19104. }),
  19105. receivingConfig(),
  19106. Keying.config({
  19107. mode: 'execution',
  19108. useEnter: spec.multiline !== true,
  19109. useControlEnter: spec.multiline === true,
  19110. execute: function (comp) {
  19111. emit(comp, formSubmitEvent);
  19112. return Option.some(true);
  19113. }
  19114. }),
  19115. config('textfield-change', [
  19116. run(input(), function (component, _) {
  19117. emitWith(component, formChangeEvent, { name: spec.name });
  19118. }),
  19119. run(postPaste(), function (component, _) {
  19120. emitWith(component, formChangeEvent, { name: spec.name });
  19121. })
  19122. ]),
  19123. Tabstopping.config({})
  19124. ];
  19125. var validatingBehaviours = spec.validation.map(function (vl) {
  19126. return Invalidating.config({
  19127. getRoot: function (input) {
  19128. return parent(input.element());
  19129. },
  19130. invalidClass: 'tox-invalid',
  19131. validator: {
  19132. validate: function (input) {
  19133. var v = Representing.getValue(input);
  19134. var result = vl.validator(v);
  19135. return Future.pure(result === true ? Result.value(v) : Result.error(result));
  19136. },
  19137. validateOnLoad: vl.validateOnLoad
  19138. }
  19139. });
  19140. }).toArray();
  19141. var placeholder = spec.placeholder.fold(constant({}), function (p) {
  19142. return { placeholder: providersBackstage.translate(p) };
  19143. });
  19144. var inputMode = spec.inputMode.fold(constant({}), function (mode) {
  19145. return { inputmode: mode };
  19146. });
  19147. var inputAttributes = __assign(__assign({}, placeholder), inputMode);
  19148. var pField = FormField.parts().field({
  19149. tag: spec.multiline === true ? 'textarea' : 'input',
  19150. inputAttributes: inputAttributes,
  19151. inputClasses: [spec.classname],
  19152. inputBehaviours: derive$1(flatten([
  19153. baseInputBehaviours,
  19154. validatingBehaviours
  19155. ])),
  19156. selectOnFocus: false,
  19157. factory: Input
  19158. });
  19159. var extraClasses = spec.flex ? ['tox-form__group--stretched'] : [];
  19160. var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []);
  19161. var extraBehaviours = [
  19162. Disabling.config({
  19163. disabled: function () {
  19164. return spec.disabled || providersBackstage.isReadOnly();
  19165. },
  19166. onDisabled: function (comp) {
  19167. FormField.getField(comp).each(Disabling.disable);
  19168. },
  19169. onEnabled: function (comp) {
  19170. FormField.getField(comp).each(Disabling.enable);
  19171. }
  19172. }),
  19173. receivingConfig()
  19174. ];
  19175. return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours);
  19176. };
  19177. var renderInput = function (spec, providersBackstage) {
  19178. return renderTextField({
  19179. name: spec.name,
  19180. multiline: false,
  19181. label: spec.label,
  19182. inputMode: spec.inputMode,
  19183. placeholder: spec.placeholder,
  19184. flex: false,
  19185. disabled: spec.disabled,
  19186. classname: 'tox-textfield',
  19187. validation: Option.none(),
  19188. maximized: spec.maximized
  19189. }, providersBackstage);
  19190. };
  19191. var renderTextarea = function (spec, providersBackstage) {
  19192. return renderTextField({
  19193. name: spec.name,
  19194. multiline: true,
  19195. label: spec.label,
  19196. inputMode: Option.none(),
  19197. placeholder: spec.placeholder,
  19198. flex: true,
  19199. disabled: spec.disabled,
  19200. classname: 'tox-textarea',
  19201. validation: Option.none(),
  19202. maximized: spec.maximized
  19203. }, providersBackstage);
  19204. };
  19205. var events$c = function (streamConfig, streamState) {
  19206. var streams = streamConfig.stream.streams;
  19207. var processor = streams.setup(streamConfig, streamState);
  19208. return derive([
  19209. run(streamConfig.event, processor),
  19210. runOnDetached(function () {
  19211. return streamState.cancel();
  19212. })
  19213. ].concat(streamConfig.cancelEvent.map(function (e) {
  19214. return [run(e, function () {
  19215. return streamState.cancel();
  19216. })];
  19217. }).getOr([])));
  19218. };
  19219. var ActiveStreaming = /*#__PURE__*/Object.freeze({
  19220. __proto__: null,
  19221. events: events$c
  19222. });
  19223. var throttle = function (_config) {
  19224. var state = Cell(null);
  19225. var readState = function () {
  19226. return { timer: state.get() !== null ? 'set' : 'unset' };
  19227. };
  19228. var setTimer = function (t) {
  19229. state.set(t);
  19230. };
  19231. var cancel = function () {
  19232. var t = state.get();
  19233. if (t !== null) {
  19234. t.cancel();
  19235. }
  19236. };
  19237. return nu$5({
  19238. readState: readState,
  19239. setTimer: setTimer,
  19240. cancel: cancel
  19241. });
  19242. };
  19243. var init$6 = function (spec) {
  19244. return spec.stream.streams.state(spec);
  19245. };
  19246. var StreamingState = /*#__PURE__*/Object.freeze({
  19247. __proto__: null,
  19248. throttle: throttle,
  19249. init: init$6
  19250. });
  19251. var setup$2 = function (streamInfo, streamState) {
  19252. var sInfo = streamInfo.stream;
  19253. var throttler = last$2(streamInfo.onStream, sInfo.delay);
  19254. streamState.setTimer(throttler);
  19255. return function (component, simulatedEvent) {
  19256. throttler.throttle(component, simulatedEvent);
  19257. if (sInfo.stopEvent) {
  19258. simulatedEvent.stop();
  19259. }
  19260. };
  19261. };
  19262. var StreamingSchema = [
  19263. strictOf('stream', choose$1('mode', {
  19264. throttle: [
  19265. strict$1('delay'),
  19266. defaulted$1('stopEvent', true),
  19267. output('streams', {
  19268. setup: setup$2,
  19269. state: throttle
  19270. })
  19271. ]
  19272. })),
  19273. defaulted$1('event', 'input'),
  19274. option('cancelEvent'),
  19275. onStrictHandler('onStream')
  19276. ];
  19277. var Streaming = create$1({
  19278. fields: StreamingSchema,
  19279. name: 'streaming',
  19280. active: ActiveStreaming,
  19281. state: StreamingState
  19282. });
  19283. var setValueFromItem = function (model, input, item) {
  19284. var itemData = Representing.getValue(item);
  19285. Representing.setValue(input, itemData);
  19286. setCursorAtEnd(input);
  19287. };
  19288. var setSelectionOn = function (input, f) {
  19289. var el = input.element();
  19290. var value = get$5(el);
  19291. var node = el.dom();
  19292. if (get$2(el, 'type') !== 'number') {
  19293. f(node, value);
  19294. }
  19295. };
  19296. var setCursorAtEnd = function (input) {
  19297. setSelectionOn(input, function (node, value) {
  19298. return node.setSelectionRange(value.length, value.length);
  19299. });
  19300. };
  19301. var setSelectionToEnd = function (input, startOffset) {
  19302. setSelectionOn(input, function (node, value) {
  19303. return node.setSelectionRange(startOffset, value.length);
  19304. });
  19305. };
  19306. var attemptSelectOver = function (model, input, item) {
  19307. if (!model.selectsOver) {
  19308. return Option.none();
  19309. } else {
  19310. var currentValue = Representing.getValue(input);
  19311. var inputDisplay_1 = model.getDisplayText(currentValue);
  19312. var itemValue = Representing.getValue(item);
  19313. var itemDisplay = model.getDisplayText(itemValue);
  19314. return itemDisplay.indexOf(inputDisplay_1) === 0 ? Option.some(function () {
  19315. setValueFromItem(model, input, item);
  19316. setSelectionToEnd(input, inputDisplay_1.length);
  19317. }) : Option.none();
  19318. }
  19319. };
  19320. var itemExecute = constant('alloy.typeahead.itemexecute');
  19321. var make$5 = function (detail, components, spec, externals) {
  19322. var navigateList = function (comp, simulatedEvent, highlighter) {
  19323. detail.previewing.set(false);
  19324. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19325. if (Sandboxing.isOpen(sandbox)) {
  19326. Composing.getCurrent(sandbox).each(function (menu) {
  19327. Highlighting.getHighlighted(menu).fold(function () {
  19328. highlighter(menu);
  19329. }, function () {
  19330. dispatchEvent(sandbox, menu.element(), 'keydown', simulatedEvent);
  19331. });
  19332. });
  19333. } else {
  19334. var onOpenSync = function (sandbox) {
  19335. Composing.getCurrent(sandbox).each(highlighter);
  19336. };
  19337. open$1(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19338. }
  19339. };
  19340. var focusBehaviours$1 = focusBehaviours(detail);
  19341. var mapFetch = function (comp) {
  19342. return function (tdata) {
  19343. return tdata.map(function (data) {
  19344. var menus = values(data.menus);
  19345. var items = bind(menus, function (menu) {
  19346. return filter(menu.items, function (item) {
  19347. return item.type === 'item';
  19348. });
  19349. });
  19350. var repState = Representing.getState(comp);
  19351. repState.update(map(items, function (item) {
  19352. return item.data;
  19353. }));
  19354. return data;
  19355. });
  19356. };
  19357. };
  19358. var behaviours = [
  19359. Focusing.config({}),
  19360. Representing.config({
  19361. onSetValue: detail.onSetValue,
  19362. store: __assign({
  19363. mode: 'dataset',
  19364. getDataKey: function (comp) {
  19365. return get$5(comp.element());
  19366. },
  19367. getFallbackEntry: function (itemString) {
  19368. return {
  19369. value: itemString,
  19370. meta: {}
  19371. };
  19372. },
  19373. setValue: function (comp, data) {
  19374. set$3(comp.element(), detail.model.getDisplayText(data));
  19375. }
  19376. }, detail.initialData.map(function (d) {
  19377. return wrap$1('initialValue', d);
  19378. }).getOr({}))
  19379. }),
  19380. Streaming.config({
  19381. stream: {
  19382. mode: 'throttle',
  19383. delay: detail.responseTime,
  19384. stopEvent: false
  19385. },
  19386. onStream: function (component, _simulatedEvent) {
  19387. var sandbox = Coupling.getCoupled(component, 'sandbox');
  19388. var focusInInput = Focusing.isFocused(component);
  19389. if (focusInInput) {
  19390. if (get$5(component.element()).length >= detail.minChars) {
  19391. var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) {
  19392. return Highlighting.getHighlighted(menu).map(Representing.getValue);
  19393. });
  19394. detail.previewing.set(true);
  19395. var onOpenSync = function (_sandbox) {
  19396. Composing.getCurrent(sandbox).each(function (menu) {
  19397. previousValue_1.fold(function () {
  19398. if (detail.model.selectsOver) {
  19399. Highlighting.highlightFirst(menu);
  19400. }
  19401. }, function (pv) {
  19402. Highlighting.highlightBy(menu, function (item) {
  19403. var itemData = Representing.getValue(item);
  19404. return itemData.value === pv.value;
  19405. });
  19406. Highlighting.getHighlighted(menu).orThunk(function () {
  19407. Highlighting.highlightFirst(menu);
  19408. return Option.none();
  19409. });
  19410. });
  19411. });
  19412. };
  19413. open$1(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19414. }
  19415. }
  19416. },
  19417. cancelEvent: typeaheadCancel()
  19418. }),
  19419. Keying.config({
  19420. mode: 'special',
  19421. onDown: function (comp, simulatedEvent) {
  19422. navigateList(comp, simulatedEvent, Highlighting.highlightFirst);
  19423. return Option.some(true);
  19424. },
  19425. onEscape: function (comp) {
  19426. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19427. if (Sandboxing.isOpen(sandbox)) {
  19428. Sandboxing.close(sandbox);
  19429. return Option.some(true);
  19430. }
  19431. return Option.none();
  19432. },
  19433. onUp: function (comp, simulatedEvent) {
  19434. navigateList(comp, simulatedEvent, Highlighting.highlightLast);
  19435. return Option.some(true);
  19436. },
  19437. onEnter: function (comp) {
  19438. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19439. var sandboxIsOpen = Sandboxing.isOpen(sandbox);
  19440. if (sandboxIsOpen && !detail.previewing.get()) {
  19441. return Composing.getCurrent(sandbox).bind(function (menu) {
  19442. return Highlighting.getHighlighted(menu);
  19443. }).map(function (item) {
  19444. emitWith(comp, itemExecute(), { item: item });
  19445. return true;
  19446. });
  19447. } else {
  19448. var currentValue = Representing.getValue(comp);
  19449. emit(comp, typeaheadCancel());
  19450. detail.onExecute(sandbox, comp, currentValue);
  19451. if (sandboxIsOpen) {
  19452. Sandboxing.close(sandbox);
  19453. }
  19454. return Option.some(true);
  19455. }
  19456. }
  19457. }),
  19458. Toggling.config({
  19459. toggleClass: detail.markers.openClass,
  19460. aria: { mode: 'expanded' }
  19461. }),
  19462. Coupling.config({
  19463. others: {
  19464. sandbox: function (hotspot) {
  19465. return makeSandbox(detail, hotspot, {
  19466. onOpen: function () {
  19467. return Toggling.on(hotspot);
  19468. },
  19469. onClose: function () {
  19470. return Toggling.off(hotspot);
  19471. }
  19472. });
  19473. }
  19474. }
  19475. }),
  19476. config('typeaheadevents', [
  19477. runOnExecute(function (comp) {
  19478. var onOpenSync = noop;
  19479. togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  19480. }),
  19481. run(itemExecute(), function (comp, se) {
  19482. var sandbox = Coupling.getCoupled(comp, 'sandbox');
  19483. setValueFromItem(detail.model, comp, se.event().item());
  19484. emit(comp, typeaheadCancel());
  19485. detail.onItemExecute(comp, sandbox, se.event().item(), Representing.getValue(comp));
  19486. Sandboxing.close(sandbox);
  19487. setCursorAtEnd(comp);
  19488. })
  19489. ].concat(detail.dismissOnBlur ? [run(postBlur(), function (typeahead) {
  19490. var sandbox = Coupling.getCoupled(typeahead, 'sandbox');
  19491. if (search(sandbox.element()).isNone()) {
  19492. Sandboxing.close(sandbox);
  19493. }
  19494. })] : []))
  19495. ];
  19496. return {
  19497. uid: detail.uid,
  19498. dom: dom$2(deepMerge(detail, {
  19499. inputAttributes: {
  19500. 'role': 'combobox',
  19501. 'aria-autocomplete': 'list',
  19502. 'aria-haspopup': 'true'
  19503. }
  19504. })),
  19505. behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)),
  19506. eventOrder: detail.eventOrder
  19507. };
  19508. };
  19509. var schema$j = constant([
  19510. option('lazySink'),
  19511. strict$1('fetch'),
  19512. defaulted$1('minChars', 5),
  19513. defaulted$1('responseTime', 1000),
  19514. onHandler('onOpen'),
  19515. defaulted$1('getHotspot', Option.some),
  19516. defaulted$1('getAnchorOverrides', constant({})),
  19517. defaulted$1('layouts', Option.none()),
  19518. defaulted$1('eventOrder', {}),
  19519. defaultedObjOf('model', {}, [
  19520. defaulted$1('getDisplayText', function (itemData) {
  19521. return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value;
  19522. }),
  19523. defaulted$1('selectsOver', true),
  19524. defaulted$1('populateFromBrowse', true)
  19525. ]),
  19526. onHandler('onSetValue'),
  19527. onKeyboardHandler('onExecute'),
  19528. onHandler('onItemExecute'),
  19529. defaulted$1('inputClasses', []),
  19530. defaulted$1('inputAttributes', {}),
  19531. defaulted$1('inputStyles', {}),
  19532. defaulted$1('matchWidth', true),
  19533. defaulted$1('useMinWidth', false),
  19534. defaulted$1('dismissOnBlur', true),
  19535. markers(['openClass']),
  19536. option('initialData'),
  19537. field$1('typeaheadBehaviours', [
  19538. Focusing,
  19539. Representing,
  19540. Streaming,
  19541. Keying,
  19542. Toggling,
  19543. Coupling
  19544. ]),
  19545. state$1('previewing', function () {
  19546. return Cell(true);
  19547. })
  19548. ].concat(schema$f()).concat(sandboxFields()));
  19549. var parts$6 = constant([external$1({
  19550. schema: [tieredMenuMarkers()],
  19551. name: 'menu',
  19552. overrides: function (detail) {
  19553. return {
  19554. fakeFocus: true,
  19555. onHighlight: function (menu, item) {
  19556. if (!detail.previewing.get()) {
  19557. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19558. if (detail.model.populateFromBrowse) {
  19559. setValueFromItem(detail.model, input, item);
  19560. }
  19561. });
  19562. } else {
  19563. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19564. attemptSelectOver(detail.model, input, item).fold(function () {
  19565. return Highlighting.dehighlight(menu, item);
  19566. }, function (fn) {
  19567. return fn();
  19568. });
  19569. });
  19570. }
  19571. detail.previewing.set(false);
  19572. },
  19573. onExecute: function (menu, item) {
  19574. return menu.getSystem().getByUid(detail.uid).toOption().map(function (typeahead) {
  19575. emitWith(typeahead, itemExecute(), { item: item });
  19576. return true;
  19577. });
  19578. },
  19579. onHover: function (menu, item) {
  19580. detail.previewing.set(false);
  19581. menu.getSystem().getByUid(detail.uid).each(function (input) {
  19582. if (detail.model.populateFromBrowse) {
  19583. setValueFromItem(detail.model, input, item);
  19584. }
  19585. });
  19586. }
  19587. };
  19588. }
  19589. })]);
  19590. var Typeahead = composite$1({
  19591. name: 'Typeahead',
  19592. configFields: schema$j(),
  19593. partFields: parts$6(),
  19594. factory: make$5
  19595. });
  19596. var wrap$2 = function (delegate) {
  19597. var toCached = function () {
  19598. return wrap$2(delegate.toCached());
  19599. };
  19600. var bindFuture = function (f) {
  19601. return wrap$2(delegate.bind(function (resA) {
  19602. return resA.fold(function (err) {
  19603. return Future.pure(Result.error(err));
  19604. }, function (a) {
  19605. return f(a);
  19606. });
  19607. }));
  19608. };
  19609. var bindResult = function (f) {
  19610. return wrap$2(delegate.map(function (resA) {
  19611. return resA.bind(f);
  19612. }));
  19613. };
  19614. var mapResult = function (f) {
  19615. return wrap$2(delegate.map(function (resA) {
  19616. return resA.map(f);
  19617. }));
  19618. };
  19619. var mapError = function (f) {
  19620. return wrap$2(delegate.map(function (resA) {
  19621. return resA.mapError(f);
  19622. }));
  19623. };
  19624. var foldResult = function (whenError, whenValue) {
  19625. return delegate.map(function (res) {
  19626. return res.fold(whenError, whenValue);
  19627. });
  19628. };
  19629. var withTimeout = function (timeout, errorThunk) {
  19630. return wrap$2(Future.nu(function (callback) {
  19631. var timedOut = false;
  19632. var timer = domGlobals.setTimeout(function () {
  19633. timedOut = true;
  19634. callback(Result.error(errorThunk()));
  19635. }, timeout);
  19636. delegate.get(function (result) {
  19637. if (!timedOut) {
  19638. domGlobals.clearTimeout(timer);
  19639. callback(result);
  19640. }
  19641. });
  19642. }));
  19643. };
  19644. return __assign(__assign({}, delegate), {
  19645. toCached: toCached,
  19646. bindFuture: bindFuture,
  19647. bindResult: bindResult,
  19648. mapResult: mapResult,
  19649. mapError: mapError,
  19650. foldResult: foldResult,
  19651. withTimeout: withTimeout
  19652. });
  19653. };
  19654. var nu$c = function (worker) {
  19655. return wrap$2(Future.nu(worker));
  19656. };
  19657. var value$2 = function (value) {
  19658. return wrap$2(Future.pure(Result.value(value)));
  19659. };
  19660. var error$1 = function (error) {
  19661. return wrap$2(Future.pure(Result.error(error)));
  19662. };
  19663. var fromResult$1 = function (result) {
  19664. return wrap$2(Future.pure(result));
  19665. };
  19666. var fromFuture = function (future) {
  19667. return wrap$2(future.map(Result.value));
  19668. };
  19669. var fromPromise = function (promise) {
  19670. return nu$c(function (completer) {
  19671. promise.then(function (value) {
  19672. completer(Result.value(value));
  19673. }, function (error) {
  19674. completer(Result.error(error));
  19675. });
  19676. });
  19677. };
  19678. var FutureResult = {
  19679. nu: nu$c,
  19680. wrap: wrap$2,
  19681. pure: value$2,
  19682. value: value$2,
  19683. error: error$1,
  19684. fromResult: fromResult$1,
  19685. fromFuture: fromFuture,
  19686. fromPromise: fromPromise
  19687. };
  19688. var separator$2 = { type: 'separator' };
  19689. var toMenuItem = function (target) {
  19690. return {
  19691. type: 'menuitem',
  19692. value: target.url,
  19693. text: target.title,
  19694. meta: { attach: target.attach },
  19695. onAction: function () {
  19696. }
  19697. };
  19698. };
  19699. var staticMenuItem = function (title, url) {
  19700. return {
  19701. type: 'menuitem',
  19702. value: url,
  19703. text: title,
  19704. meta: { attach: undefined },
  19705. onAction: function () {
  19706. }
  19707. };
  19708. };
  19709. var toMenuItems = function (targets) {
  19710. return map(targets, toMenuItem);
  19711. };
  19712. var filterLinkTargets = function (type, targets) {
  19713. return filter(targets, function (target) {
  19714. return target.type === type;
  19715. });
  19716. };
  19717. var filteredTargets = function (type, targets) {
  19718. return toMenuItems(filterLinkTargets(type, targets));
  19719. };
  19720. var headerTargets = function (linkInfo) {
  19721. return filteredTargets('header', linkInfo.targets);
  19722. };
  19723. var anchorTargets = function (linkInfo) {
  19724. return filteredTargets('anchor', linkInfo.targets);
  19725. };
  19726. var anchorTargetTop = function (linkInfo) {
  19727. return Option.from(linkInfo.anchorTop).map(function (url) {
  19728. return staticMenuItem('<top>', url);
  19729. }).toArray();
  19730. };
  19731. var anchorTargetBottom = function (linkInfo) {
  19732. return Option.from(linkInfo.anchorBottom).map(function (url) {
  19733. return staticMenuItem('<bottom>', url);
  19734. }).toArray();
  19735. };
  19736. var historyTargets = function (history) {
  19737. return map(history, function (url) {
  19738. return staticMenuItem(url, url);
  19739. });
  19740. };
  19741. var joinMenuLists = function (items) {
  19742. return foldl(items, function (a, b) {
  19743. var bothEmpty = a.length === 0 || b.length === 0;
  19744. return bothEmpty ? a.concat(b) : a.concat(separator$2, b);
  19745. }, []);
  19746. };
  19747. var filterByQuery = function (term, menuItems) {
  19748. var lowerCaseTerm = term.toLowerCase();
  19749. return filter(menuItems, function (item) {
  19750. var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text;
  19751. return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm);
  19752. });
  19753. };
  19754. var getItems = function (fileType, input, urlBackstage) {
  19755. var urlInputValue = Representing.getValue(input);
  19756. var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value;
  19757. var info = urlBackstage.getLinkInformation();
  19758. return info.fold(function () {
  19759. return [];
  19760. }, function (linkInfo) {
  19761. var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType)));
  19762. return fileType === 'file' ? joinMenuLists([
  19763. history,
  19764. filterByQuery(term, headerTargets(linkInfo)),
  19765. filterByQuery(term, flatten([
  19766. anchorTargetTop(linkInfo),
  19767. anchorTargets(linkInfo),
  19768. anchorTargetBottom(linkInfo)
  19769. ]))
  19770. ]) : history;
  19771. });
  19772. };
  19773. var errorId = generate$1('aria-invalid');
  19774. var renderUrlInput = function (spec, backstage, urlBackstage) {
  19775. var _a;
  19776. var providersBackstage = backstage.shared.providers;
  19777. var updateHistory = function (component) {
  19778. var urlEntry = Representing.getValue(component);
  19779. urlBackstage.addToHistory(urlEntry.value, spec.filetype);
  19780. };
  19781. var pField = FormField.parts().field({
  19782. factory: Typeahead,
  19783. dismissOnBlur: true,
  19784. inputClasses: ['tox-textfield'],
  19785. sandboxClasses: ['tox-dialog__popups'],
  19786. inputAttributes: {
  19787. 'aria-errormessage': errorId,
  19788. 'type': 'url'
  19789. },
  19790. minChars: 0,
  19791. responseTime: 0,
  19792. fetch: function (input) {
  19793. var items = getItems(spec.filetype, input, urlBackstage);
  19794. var tdata = build$2(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false);
  19795. return Future.pure(tdata);
  19796. },
  19797. getHotspot: function (comp) {
  19798. return memUrlBox.getOpt(comp);
  19799. },
  19800. onSetValue: function (comp, _newValue) {
  19801. if (comp.hasConfigured(Invalidating)) {
  19802. Invalidating.run(comp).get(noop);
  19803. }
  19804. },
  19805. typeaheadBehaviours: derive$1(flatten([
  19806. urlBackstage.getValidationHandler().map(function (handler) {
  19807. return Invalidating.config({
  19808. getRoot: function (comp) {
  19809. return parent(comp.element());
  19810. },
  19811. invalidClass: 'tox-control-wrap--status-invalid',
  19812. notify: {
  19813. onInvalid: function (comp, err) {
  19814. memInvalidIcon.getOpt(comp).each(function (invalidComp) {
  19815. set$1(invalidComp.element(), 'title', providersBackstage.translate(err));
  19816. });
  19817. }
  19818. },
  19819. validator: {
  19820. validate: function (input) {
  19821. var urlEntry = Representing.getValue(input);
  19822. return FutureResult.nu(function (completer) {
  19823. handler({
  19824. type: spec.filetype,
  19825. url: urlEntry.value
  19826. }, function (validation) {
  19827. if (validation.status === 'invalid') {
  19828. var err = Result.error(validation.message);
  19829. completer(err);
  19830. } else {
  19831. var val = Result.value(validation.message);
  19832. completer(val);
  19833. }
  19834. });
  19835. });
  19836. },
  19837. validateOnLoad: false
  19838. }
  19839. });
  19840. }).toArray(),
  19841. [
  19842. Disabling.config({
  19843. disabled: function () {
  19844. return spec.disabled || providersBackstage.isReadOnly();
  19845. }
  19846. }),
  19847. Tabstopping.config({}),
  19848. config('urlinput-events', flatten([
  19849. spec.filetype === 'file' ? [run(input(), function (comp) {
  19850. emitWith(comp, formChangeEvent, { name: spec.name });
  19851. })] : [],
  19852. [
  19853. run(change(), function (comp) {
  19854. emitWith(comp, formChangeEvent, { name: spec.name });
  19855. updateHistory(comp);
  19856. }),
  19857. run(postPaste(), function (comp) {
  19858. emitWith(comp, formChangeEvent, { name: spec.name });
  19859. updateHistory(comp);
  19860. })
  19861. ]
  19862. ]))
  19863. ]
  19864. ])),
  19865. eventOrder: (_a = {}, _a[input()] = [
  19866. 'streaming',
  19867. 'urlinput-events',
  19868. 'invalidating'
  19869. ], _a),
  19870. model: {
  19871. getDisplayText: function (itemData) {
  19872. return itemData.value;
  19873. },
  19874. selectsOver: false,
  19875. populateFromBrowse: false
  19876. },
  19877. markers: { openClass: 'tox-textfield--popup-open' },
  19878. lazySink: backstage.shared.getSink,
  19879. parts: { menu: part(false, 1, 'normal') },
  19880. onExecute: function (_menu, component, _entry) {
  19881. emitWith(component, formSubmitEvent, {});
  19882. },
  19883. onItemExecute: function (typeahead, _sandbox, _item, _value) {
  19884. updateHistory(typeahead);
  19885. emitWith(typeahead, formChangeEvent, { name: spec.name });
  19886. }
  19887. });
  19888. var pLabel = spec.label.map(function (label) {
  19889. return renderLabel(label, providersBackstage);
  19890. });
  19891. var makeIcon = function (name, errId, icon, label) {
  19892. if (icon === void 0) {
  19893. icon = name;
  19894. }
  19895. if (label === void 0) {
  19896. label = name;
  19897. }
  19898. return {
  19899. dom: {
  19900. tag: 'div',
  19901. classes: [
  19902. 'tox-icon',
  19903. 'tox-control-wrap__status-icon-' + name
  19904. ],
  19905. innerHtml: get$d(icon, providersBackstage.icons),
  19906. attributes: __assign({
  19907. 'title': providersBackstage.translate(label),
  19908. 'aria-live': 'polite'
  19909. }, errId.fold(function () {
  19910. return {};
  19911. }, function (id) {
  19912. return { id: id };
  19913. }))
  19914. }
  19915. };
  19916. };
  19917. var memInvalidIcon = record(makeIcon('invalid', Option.some(errorId), 'warning'));
  19918. var memStatus = record({
  19919. dom: {
  19920. tag: 'div',
  19921. classes: ['tox-control-wrap__status-icon-wrap']
  19922. },
  19923. components: [memInvalidIcon.asSpec()]
  19924. });
  19925. var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype);
  19926. var browseUrlEvent = generate$1('browser.url.event');
  19927. var memUrlBox = record({
  19928. dom: {
  19929. tag: 'div',
  19930. classes: ['tox-control-wrap']
  19931. },
  19932. components: [
  19933. pField,
  19934. memStatus.asSpec()
  19935. ],
  19936. behaviours: derive$1([Disabling.config({
  19937. disabled: function () {
  19938. return spec.disabled || providersBackstage.isReadOnly();
  19939. }
  19940. })])
  19941. });
  19942. var memUrlPickerButton = record(renderButton({
  19943. name: spec.name,
  19944. icon: Option.some('browse'),
  19945. text: spec.label.getOr(''),
  19946. disabled: spec.disabled,
  19947. primary: false,
  19948. borderless: true
  19949. }, function (component) {
  19950. return emit(component, browseUrlEvent);
  19951. }, providersBackstage, [], ['tox-browse-url']));
  19952. var controlHWrapper = function () {
  19953. return {
  19954. dom: {
  19955. tag: 'div',
  19956. classes: ['tox-form__controls-h-stack']
  19957. },
  19958. components: flatten([
  19959. [memUrlBox.asSpec()],
  19960. optUrlPicker.map(function () {
  19961. return memUrlPickerButton.asSpec();
  19962. }).toArray()
  19963. ])
  19964. };
  19965. };
  19966. var openUrlPicker = function (comp) {
  19967. Composing.getCurrent(comp).each(function (field) {
  19968. var componentData = Representing.getValue(field);
  19969. var urlData = __assign({ fieldname: spec.name }, componentData);
  19970. optUrlPicker.each(function (picker) {
  19971. picker(urlData).get(function (chosenData) {
  19972. Representing.setValue(field, chosenData);
  19973. emitWith(comp, formChangeEvent, { name: spec.name });
  19974. });
  19975. });
  19976. });
  19977. };
  19978. return FormField.sketch({
  19979. dom: renderFormFieldDom(),
  19980. components: pLabel.toArray().concat([controlHWrapper()]),
  19981. fieldBehaviours: derive$1([
  19982. Disabling.config({
  19983. disabled: function () {
  19984. return spec.disabled || providersBackstage.isReadOnly();
  19985. },
  19986. onDisabled: function (comp) {
  19987. FormField.getField(comp).each(Disabling.disable);
  19988. memUrlPickerButton.getOpt(comp).each(Disabling.disable);
  19989. },
  19990. onEnabled: function (comp) {
  19991. FormField.getField(comp).each(Disabling.enable);
  19992. memUrlPickerButton.getOpt(comp).each(Disabling.enable);
  19993. }
  19994. }),
  19995. receivingConfig(),
  19996. config('url-input-events', [run(browseUrlEvent, openUrlPicker)])
  19997. ])
  19998. });
  19999. };
  20000. var renderCheckbox = function (spec, providerBackstage) {
  20001. var repBehaviour = Representing.config({
  20002. store: {
  20003. mode: 'manual',
  20004. getValue: function (comp) {
  20005. var el = comp.element().dom();
  20006. return el.checked;
  20007. },
  20008. setValue: function (comp, value) {
  20009. var el = comp.element().dom();
  20010. el.checked = value;
  20011. }
  20012. }
  20013. });
  20014. var toggleCheckboxHandler = function (comp) {
  20015. comp.element().dom().click();
  20016. return Option.some(true);
  20017. };
  20018. var pField = FormField.parts().field({
  20019. factory: { sketch: identity },
  20020. dom: {
  20021. tag: 'input',
  20022. classes: ['tox-checkbox__input'],
  20023. attributes: { type: 'checkbox' }
  20024. },
  20025. behaviours: derive$1([
  20026. ComposingConfigs.self(),
  20027. Disabling.config({
  20028. disabled: function () {
  20029. return spec.disabled || providerBackstage.isReadOnly();
  20030. }
  20031. }),
  20032. Tabstopping.config({}),
  20033. Focusing.config({}),
  20034. repBehaviour,
  20035. Keying.config({
  20036. mode: 'special',
  20037. onEnter: toggleCheckboxHandler,
  20038. onSpace: toggleCheckboxHandler,
  20039. stopSpaceKeyup: true
  20040. }),
  20041. config('checkbox-events', [run(change(), function (component, _) {
  20042. emitWith(component, formChangeEvent, { name: spec.name });
  20043. })])
  20044. ])
  20045. });
  20046. var pLabel = FormField.parts().label({
  20047. dom: {
  20048. tag: 'span',
  20049. classes: ['tox-checkbox__label'],
  20050. innerHtml: providerBackstage.translate(spec.label)
  20051. },
  20052. behaviours: derive$1([Unselecting.config({})])
  20053. });
  20054. var makeIcon = function (className) {
  20055. var iconName = className === 'checked' ? 'selected' : 'unselected';
  20056. return {
  20057. dom: {
  20058. tag: 'span',
  20059. classes: [
  20060. 'tox-icon',
  20061. 'tox-checkbox-icon__' + className
  20062. ],
  20063. innerHtml: get$d(iconName, providerBackstage.icons)
  20064. }
  20065. };
  20066. };
  20067. var memIcons = record({
  20068. dom: {
  20069. tag: 'div',
  20070. classes: ['tox-checkbox__icons']
  20071. },
  20072. components: [
  20073. makeIcon('checked'),
  20074. makeIcon('unchecked')
  20075. ]
  20076. });
  20077. return FormField.sketch({
  20078. dom: {
  20079. tag: 'label',
  20080. classes: ['tox-checkbox']
  20081. },
  20082. components: [
  20083. pField,
  20084. memIcons.asSpec(),
  20085. pLabel
  20086. ],
  20087. fieldBehaviours: derive$1([
  20088. Disabling.config({
  20089. disabled: function () {
  20090. return spec.disabled || providerBackstage.isReadOnly();
  20091. },
  20092. disableClass: 'tox-checkbox--disabled',
  20093. onDisabled: function (comp) {
  20094. FormField.getField(comp).each(Disabling.disable);
  20095. },
  20096. onEnabled: function (comp) {
  20097. FormField.getField(comp).each(Disabling.enable);
  20098. }
  20099. }),
  20100. receivingConfig()
  20101. ])
  20102. });
  20103. };
  20104. var renderHtmlPanel = function (spec) {
  20105. if (spec.presets === 'presentation') {
  20106. return Container.sketch({
  20107. dom: {
  20108. tag: 'div',
  20109. classes: ['tox-form__group'],
  20110. innerHtml: spec.html
  20111. }
  20112. });
  20113. } else {
  20114. return Container.sketch({
  20115. dom: {
  20116. tag: 'div',
  20117. classes: ['tox-form__group'],
  20118. innerHtml: spec.html,
  20119. attributes: { role: 'document' }
  20120. },
  20121. containerBehaviours: derive$1([
  20122. Tabstopping.config({}),
  20123. Focusing.config({})
  20124. ])
  20125. });
  20126. }
  20127. };
  20128. var renderLabel$2 = function (spec, backstageShared) {
  20129. var label = {
  20130. dom: {
  20131. tag: 'label',
  20132. innerHtml: backstageShared.providers.translate(spec.label),
  20133. classes: ['tox-label']
  20134. }
  20135. };
  20136. var comps = map(spec.items, backstageShared.interpreter);
  20137. return {
  20138. dom: {
  20139. tag: 'div',
  20140. classes: ['tox-form__group']
  20141. },
  20142. components: [label].concat(comps),
  20143. behaviours: derive$1([
  20144. ComposingConfigs.self(),
  20145. Replacing.config({}),
  20146. RepresentingConfigs.domHtml(Option.none()),
  20147. Keying.config({ mode: 'acyclic' })
  20148. ])
  20149. };
  20150. };
  20151. var renderCollection = function (spec, providersBackstage) {
  20152. var pLabel = spec.label.map(function (label) {
  20153. return renderLabel(label, providersBackstage);
  20154. });
  20155. var runOnItem = function (f) {
  20156. return function (comp, se) {
  20157. closest$3(se.event().target(), '[data-collection-item-value]').each(function (target) {
  20158. f(comp, se, target, get$2(target, 'data-collection-item-value'));
  20159. });
  20160. };
  20161. };
  20162. var escapeAttribute = function (ch) {
  20163. if (ch === '"') {
  20164. return '&quot;';
  20165. }
  20166. return ch;
  20167. };
  20168. var setContents = function (comp, items) {
  20169. var htmlLines = map(items, function (item) {
  20170. var itemText = global$5.translate(item.text);
  20171. var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : '';
  20172. var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>';
  20173. var mapItemName = {
  20174. '_': ' ',
  20175. ' - ': ' ',
  20176. '-': ' '
  20177. };
  20178. var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) {
  20179. return mapItemName[match];
  20180. });
  20181. var readonlyClass = providersBackstage.isReadOnly() ? ' tox-collection__item--state-disabled' : '';
  20182. return '<div class="tox-collection__item' + readonlyClass + '" tabindex="-1" data-collection-item-value="' + escapeAttribute(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>';
  20183. });
  20184. var chunks = spec.columns > 1 && spec.columns !== 'auto' ? chunk(htmlLines, spec.columns) : [htmlLines];
  20185. var html = map(chunks, function (ch) {
  20186. return '<div class="tox-collection__group">' + ch.join('') + '</div>';
  20187. });
  20188. set(comp.element(), html.join(''));
  20189. };
  20190. var onClick = runOnItem(function (comp, se, tgt, itemValue) {
  20191. se.stop();
  20192. if (!providersBackstage.isReadOnly()) {
  20193. emitWith(comp, formActionEvent, {
  20194. name: spec.name,
  20195. value: itemValue
  20196. });
  20197. }
  20198. });
  20199. var collectionEvents = [
  20200. run(mouseover(), runOnItem(function (comp, se, tgt) {
  20201. focus$1(tgt);
  20202. })),
  20203. run(click(), onClick),
  20204. run(tap(), onClick),
  20205. run(focusin(), runOnItem(function (comp, se, tgt) {
  20206. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20207. remove$4(currentActive, activeClass);
  20208. });
  20209. add$2(tgt, activeClass);
  20210. })),
  20211. run(focusout(), runOnItem(function (comp) {
  20212. descendant$1(comp.element(), '.' + activeClass).each(function (currentActive) {
  20213. remove$4(currentActive, activeClass);
  20214. });
  20215. })),
  20216. runOnExecute(runOnItem(function (comp, se, tgt, itemValue) {
  20217. emitWith(comp, formActionEvent, {
  20218. name: spec.name,
  20219. value: itemValue
  20220. });
  20221. }))
  20222. ];
  20223. var iterCollectionItems = function (comp, applyAttributes) {
  20224. return map(descendants(comp.element(), '.tox-collection__item'), applyAttributes);
  20225. };
  20226. var pField = FormField.parts().field({
  20227. dom: {
  20228. tag: 'div',
  20229. classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list'])
  20230. },
  20231. components: [],
  20232. factory: { sketch: identity },
  20233. behaviours: derive$1([
  20234. Disabling.config({
  20235. disabled: providersBackstage.isReadOnly,
  20236. onDisabled: function (comp) {
  20237. iterCollectionItems(comp, function (childElm) {
  20238. add$2(childElm, 'tox-collection__item--state-disabled');
  20239. set$1(childElm, 'aria-disabled', true);
  20240. });
  20241. },
  20242. onEnabled: function (comp) {
  20243. iterCollectionItems(comp, function (childElm) {
  20244. remove$4(childElm, 'tox-collection__item--state-disabled');
  20245. remove$1(childElm, 'aria-disabled');
  20246. });
  20247. }
  20248. }),
  20249. receivingConfig(),
  20250. Replacing.config({}),
  20251. Representing.config({
  20252. store: {
  20253. mode: 'memory',
  20254. initialValue: []
  20255. },
  20256. onSetValue: function (comp, items) {
  20257. setContents(comp, items);
  20258. if (spec.columns === 'auto') {
  20259. detectSize(comp, 5, 'tox-collection__item').each(function (_a) {
  20260. var numRows = _a.numRows, numColumns = _a.numColumns;
  20261. Keying.setGridSize(comp, numRows, numColumns);
  20262. });
  20263. }
  20264. emit(comp, formResizeEvent);
  20265. }
  20266. }),
  20267. Tabstopping.config({}),
  20268. Keying.config(deriveCollectionMovement(spec.columns, 'normal')),
  20269. config('collection-events', collectionEvents)
  20270. ]),
  20271. eventOrder: {
  20272. 'alloy.execute': [
  20273. 'disabling',
  20274. 'alloy.base.behaviour',
  20275. 'collection-events'
  20276. ]
  20277. }
  20278. });
  20279. var extraClasses = ['tox-form__group--collection'];
  20280. return renderFormFieldWith(pLabel, pField, extraClasses, []);
  20281. };
  20282. var renderTable = function (spec, providersBackstage) {
  20283. var renderTh = function (text) {
  20284. return {
  20285. dom: {
  20286. tag: 'th',
  20287. innerHtml: providersBackstage.translate(text)
  20288. }
  20289. };
  20290. };
  20291. var renderHeader = function (header) {
  20292. return {
  20293. dom: { tag: 'thead' },
  20294. components: [{
  20295. dom: { tag: 'tr' },
  20296. components: map(header, renderTh)
  20297. }]
  20298. };
  20299. };
  20300. var renderTd = function (text) {
  20301. return {
  20302. dom: {
  20303. tag: 'td',
  20304. innerHtml: providersBackstage.translate(text)
  20305. }
  20306. };
  20307. };
  20308. var renderTr = function (row) {
  20309. return {
  20310. dom: { tag: 'tr' },
  20311. components: map(row, renderTd)
  20312. };
  20313. };
  20314. var renderRows = function (rows) {
  20315. return {
  20316. dom: { tag: 'tbody' },
  20317. components: map(rows, renderTr)
  20318. };
  20319. };
  20320. return {
  20321. dom: {
  20322. tag: 'table',
  20323. classes: ['tox-dialog__table']
  20324. },
  20325. components: [
  20326. renderHeader(spec.header),
  20327. renderRows(spec.cells)
  20328. ],
  20329. behaviours: derive$1([
  20330. Tabstopping.config({}),
  20331. Focusing.config({})
  20332. ])
  20333. };
  20334. };
  20335. var renderPanel = function (spec, backstage) {
  20336. return {
  20337. dom: {
  20338. tag: 'div',
  20339. classes: spec.classes
  20340. },
  20341. components: map(spec.items, backstage.shared.interpreter)
  20342. };
  20343. };
  20344. var make$6 = function (render) {
  20345. return function (parts, spec, backstage) {
  20346. return get(spec, 'name').fold(function () {
  20347. return render(spec, backstage);
  20348. }, function (fieldName) {
  20349. return parts.field(fieldName, render(spec, backstage));
  20350. });
  20351. };
  20352. };
  20353. var makeIframe = function (render) {
  20354. return function (parts, spec, backstage) {
  20355. var iframeSpec = deepMerge(spec, { source: 'dynamic' });
  20356. return make$6(render)(parts, iframeSpec, backstage);
  20357. };
  20358. };
  20359. var factories = {
  20360. bar: make$6(function (spec, backstage) {
  20361. return renderBar(spec, backstage.shared);
  20362. }),
  20363. collection: make$6(function (spec, backstage) {
  20364. return renderCollection(spec, backstage.shared.providers);
  20365. }),
  20366. alertbanner: make$6(function (spec, backstage) {
  20367. return renderAlertBanner(spec, backstage.shared.providers);
  20368. }),
  20369. input: make$6(function (spec, backstage) {
  20370. return renderInput(spec, backstage.shared.providers);
  20371. }),
  20372. textarea: make$6(function (spec, backstage) {
  20373. return renderTextarea(spec, backstage.shared.providers);
  20374. }),
  20375. label: make$6(function (spec, backstage) {
  20376. return renderLabel$2(spec, backstage.shared);
  20377. }),
  20378. iframe: makeIframe(function (spec, backstage) {
  20379. return renderIFrame(spec, backstage.shared.providers);
  20380. }),
  20381. button: make$6(function (spec, backstage) {
  20382. return renderDialogButton(spec, backstage.shared.providers);
  20383. }),
  20384. checkbox: make$6(function (spec, backstage) {
  20385. return renderCheckbox(spec, backstage.shared.providers);
  20386. }),
  20387. colorinput: make$6(function (spec, backstage) {
  20388. return renderColorInput(spec, backstage.shared, backstage.colorinput);
  20389. }),
  20390. colorpicker: make$6(renderColorPicker),
  20391. dropzone: make$6(function (spec, backstage) {
  20392. return renderDropZone(spec, backstage.shared.providers);
  20393. }),
  20394. grid: make$6(function (spec, backstage) {
  20395. return renderGrid(spec, backstage.shared);
  20396. }),
  20397. selectbox: make$6(function (spec, backstage) {
  20398. return renderSelectBox(spec, backstage.shared.providers);
  20399. }),
  20400. sizeinput: make$6(function (spec, backstage) {
  20401. return renderSizeInput(spec, backstage.shared.providers);
  20402. }),
  20403. urlinput: make$6(function (spec, backstage) {
  20404. return renderUrlInput(spec, backstage, backstage.urlinput);
  20405. }),
  20406. customeditor: make$6(renderCustomEditor),
  20407. htmlpanel: make$6(renderHtmlPanel),
  20408. imagetools: make$6(function (spec, backstage) {
  20409. return renderImageTools(spec, backstage.shared.providers);
  20410. }),
  20411. table: make$6(function (spec, backstage) {
  20412. return renderTable(spec, backstage.shared.providers);
  20413. }),
  20414. panel: make$6(function (spec, backstage) {
  20415. return renderPanel(spec, backstage);
  20416. })
  20417. };
  20418. var noFormParts = {
  20419. field: function (_name, spec) {
  20420. return spec;
  20421. }
  20422. };
  20423. var interpretInForm = function (parts, spec, oldBackstage) {
  20424. var newBackstage = deepMerge(oldBackstage, {
  20425. shared: {
  20426. interpreter: function (childSpec) {
  20427. return interpretParts(parts, childSpec, newBackstage);
  20428. }
  20429. }
  20430. });
  20431. return interpretParts(parts, spec, newBackstage);
  20432. };
  20433. var interpretParts = function (parts, spec, backstage) {
  20434. return get(factories, spec.type).fold(function () {
  20435. domGlobals.console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec);
  20436. return spec;
  20437. }, function (factory) {
  20438. return factory(parts, spec, backstage);
  20439. });
  20440. };
  20441. var interpretWithoutForm = function (spec, backstage) {
  20442. var parts = noFormParts;
  20443. return interpretParts(parts, spec, backstage);
  20444. };
  20445. var bubbleAlignments = {
  20446. valignCentre: [],
  20447. alignCentre: [],
  20448. alignLeft: [],
  20449. alignRight: [],
  20450. right: [],
  20451. left: [],
  20452. bottom: [],
  20453. top: []
  20454. };
  20455. var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20456. var bubble = nu$8(-12, 12, bubbleAlignments);
  20457. var overrides = { maxHeightFunction: expandable() };
  20458. var editableAreaAnchor = function () {
  20459. return {
  20460. anchor: 'node',
  20461. root: getBody(owner(contentAreaElement())),
  20462. node: Option.from(contentAreaElement()),
  20463. bubble: bubble,
  20464. layouts: {
  20465. onRtl: function () {
  20466. return [northwest$3];
  20467. },
  20468. onLtr: function () {
  20469. return [northeast$3];
  20470. }
  20471. },
  20472. overrides: overrides
  20473. };
  20474. };
  20475. var standardAnchor = function () {
  20476. return {
  20477. anchor: 'hotspot',
  20478. hotspot: lazyAnchorbar(),
  20479. bubble: bubble,
  20480. layouts: {
  20481. onRtl: function () {
  20482. return [southeast$1];
  20483. },
  20484. onLtr: function () {
  20485. return [southwest$1];
  20486. }
  20487. },
  20488. overrides: overrides
  20489. };
  20490. };
  20491. return function () {
  20492. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20493. };
  20494. };
  20495. var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) {
  20496. var editableAreaAnchor = function () {
  20497. return {
  20498. anchor: 'node',
  20499. root: getBody(owner(contentAreaElement())),
  20500. node: Option.from(contentAreaElement()),
  20501. layouts: {
  20502. onRtl: function () {
  20503. return [north$3];
  20504. },
  20505. onLtr: function () {
  20506. return [north$3];
  20507. }
  20508. }
  20509. };
  20510. };
  20511. var standardAnchor = function () {
  20512. return {
  20513. anchor: 'hotspot',
  20514. hotspot: lazyAnchorbar(),
  20515. layouts: {
  20516. onRtl: function () {
  20517. return [south$1];
  20518. },
  20519. onLtr: function () {
  20520. return [south$1];
  20521. }
  20522. }
  20523. };
  20524. };
  20525. return function () {
  20526. return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor();
  20527. };
  20528. };
  20529. var getCursorAnchor = function (editor, bodyElement) {
  20530. return function () {
  20531. return {
  20532. anchor: 'selection',
  20533. root: bodyElement(),
  20534. getSelection: function () {
  20535. var rng = editor.selection.getRng();
  20536. return Option.some(Selection.range(Element.fromDom(rng.startContainer), rng.startOffset, Element.fromDom(rng.endContainer), rng.endOffset));
  20537. }
  20538. };
  20539. };
  20540. };
  20541. var getNodeAnchor = function (bodyElement) {
  20542. return function (element) {
  20543. return {
  20544. anchor: 'node',
  20545. root: bodyElement(),
  20546. node: element
  20547. };
  20548. };
  20549. };
  20550. var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) {
  20551. var useFixedToolbarContainer = useFixedContainer(editor);
  20552. var bodyElement = function () {
  20553. return Element.fromDom(editor.getBody());
  20554. };
  20555. var contentAreaElement = function () {
  20556. return Element.fromDom(editor.getContentAreaContainer());
  20557. };
  20558. var lazyUseEditableAreaAnchor = function () {
  20559. return useFixedToolbarContainer || !isToolbarTop();
  20560. };
  20561. return {
  20562. inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  20563. banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor),
  20564. cursor: getCursorAnchor(editor, bodyElement),
  20565. node: getNodeAnchor(bodyElement)
  20566. };
  20567. };
  20568. var colorPicker = function (editor) {
  20569. return function (callback, value) {
  20570. var dialog = colorPickerDialog(editor);
  20571. dialog(callback, value);
  20572. };
  20573. };
  20574. var hasCustomColors$1 = function (editor) {
  20575. return function () {
  20576. return hasCustomColors(editor);
  20577. };
  20578. };
  20579. var getColors$2 = function (editor) {
  20580. return function () {
  20581. return getColors(editor);
  20582. };
  20583. };
  20584. var getColorCols$2 = function (editor) {
  20585. return function () {
  20586. return getColorCols$1(editor);
  20587. };
  20588. };
  20589. var ColorInputBackstage = function (editor) {
  20590. return {
  20591. colorPicker: colorPicker(editor),
  20592. hasCustomColors: hasCustomColors$1(editor),
  20593. getColors: getColors$2(editor),
  20594. getColorCols: getColorCols$2(editor)
  20595. };
  20596. };
  20597. var isDraggableModal$1 = function (editor) {
  20598. return function () {
  20599. return isDraggableModal(editor);
  20600. };
  20601. };
  20602. var DialogBackstage = function (editor) {
  20603. return { isDraggableModal: isDraggableModal$1(editor) };
  20604. };
  20605. var HeaderBackstage = function (editor) {
  20606. var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top');
  20607. return {
  20608. isPositionedAtTop: function () {
  20609. return mode.get() === 'top';
  20610. },
  20611. getDockingMode: mode.get,
  20612. setDockingMode: mode.set
  20613. };
  20614. };
  20615. var defaultStyleFormats = [
  20616. {
  20617. title: 'Headings',
  20618. items: [
  20619. {
  20620. title: 'Heading 1',
  20621. format: 'h1'
  20622. },
  20623. {
  20624. title: 'Heading 2',
  20625. format: 'h2'
  20626. },
  20627. {
  20628. title: 'Heading 3',
  20629. format: 'h3'
  20630. },
  20631. {
  20632. title: 'Heading 4',
  20633. format: 'h4'
  20634. },
  20635. {
  20636. title: 'Heading 5',
  20637. format: 'h5'
  20638. },
  20639. {
  20640. title: 'Heading 6',
  20641. format: 'h6'
  20642. }
  20643. ]
  20644. },
  20645. {
  20646. title: 'Inline',
  20647. items: [
  20648. {
  20649. title: 'Bold',
  20650. format: 'bold'
  20651. },
  20652. {
  20653. title: 'Italic',
  20654. format: 'italic'
  20655. },
  20656. {
  20657. title: 'Underline',
  20658. format: 'underline'
  20659. },
  20660. {
  20661. title: 'Strikethrough',
  20662. format: 'strikethrough'
  20663. },
  20664. {
  20665. title: 'Superscript',
  20666. format: 'superscript'
  20667. },
  20668. {
  20669. title: 'Subscript',
  20670. format: 'subscript'
  20671. },
  20672. {
  20673. title: 'Code',
  20674. format: 'code'
  20675. }
  20676. ]
  20677. },
  20678. {
  20679. title: 'Blocks',
  20680. items: [
  20681. {
  20682. title: 'Paragraph',
  20683. format: 'p'
  20684. },
  20685. {
  20686. title: 'Blockquote',
  20687. format: 'blockquote'
  20688. },
  20689. {
  20690. title: 'Div',
  20691. format: 'div'
  20692. },
  20693. {
  20694. title: 'Pre',
  20695. format: 'pre'
  20696. }
  20697. ]
  20698. },
  20699. {
  20700. title: 'Align',
  20701. items: [
  20702. {
  20703. title: 'Left',
  20704. format: 'alignleft'
  20705. },
  20706. {
  20707. title: 'Center',
  20708. format: 'aligncenter'
  20709. },
  20710. {
  20711. title: 'Right',
  20712. format: 'alignright'
  20713. },
  20714. {
  20715. title: 'Justify',
  20716. format: 'alignjustify'
  20717. }
  20718. ]
  20719. }
  20720. ];
  20721. var isNestedFormat = function (format) {
  20722. return has(format, 'items');
  20723. };
  20724. var isBlockFormat = function (format) {
  20725. return has(format, 'block');
  20726. };
  20727. var isInlineFormat = function (format) {
  20728. return has(format, 'inline');
  20729. };
  20730. var isSelectorFormat = function (format) {
  20731. return has(format, 'selector');
  20732. };
  20733. var mapFormats = function (userFormats) {
  20734. return foldl(userFormats, function (acc, fmt) {
  20735. if (isNestedFormat(fmt)) {
  20736. var result = mapFormats(fmt.items);
  20737. return {
  20738. customFormats: acc.customFormats.concat(result.customFormats),
  20739. formats: acc.formats.concat([{
  20740. title: fmt.title,
  20741. items: result.formats
  20742. }])
  20743. };
  20744. } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) {
  20745. var formatName = 'custom-' + fmt.title.toLowerCase();
  20746. return {
  20747. customFormats: acc.customFormats.concat([{
  20748. name: formatName,
  20749. format: fmt
  20750. }]),
  20751. formats: acc.formats.concat([{
  20752. title: fmt.title,
  20753. format: formatName,
  20754. icon: fmt.icon
  20755. }])
  20756. };
  20757. } else {
  20758. return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) });
  20759. }
  20760. }, {
  20761. customFormats: [],
  20762. formats: []
  20763. });
  20764. };
  20765. var registerCustomFormats = function (editor, userFormats) {
  20766. var result = mapFormats(userFormats);
  20767. var registerFormats = function (customFormats) {
  20768. each(customFormats, function (fmt) {
  20769. if (!editor.formatter.has(fmt.name)) {
  20770. editor.formatter.register(fmt.name, fmt.format);
  20771. }
  20772. });
  20773. };
  20774. if (editor.formatter) {
  20775. registerFormats(result.customFormats);
  20776. } else {
  20777. editor.on('init', function () {
  20778. registerFormats(result.customFormats);
  20779. });
  20780. }
  20781. return result.formats;
  20782. };
  20783. var getStyleFormats = function (editor) {
  20784. return getUserStyleFormats(editor).map(function (userFormats) {
  20785. var registeredUserFormats = registerCustomFormats(editor, userFormats);
  20786. return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats;
  20787. }).getOr(defaultStyleFormats);
  20788. };
  20789. var processBasic = function (item, isSelectedFor, getPreviewFor) {
  20790. var formatterSpec = {
  20791. type: 'formatter',
  20792. isSelected: isSelectedFor(item.format),
  20793. getStylePreview: getPreviewFor(item.format)
  20794. };
  20795. return deepMerge(item, formatterSpec);
  20796. };
  20797. var register$3 = function (editor, formats, isSelectedFor, getPreviewFor) {
  20798. var enrichSupported = function (item) {
  20799. return processBasic(item, isSelectedFor, getPreviewFor);
  20800. };
  20801. var enrichMenu = function (item) {
  20802. var submenuSpec = { type: 'submenu' };
  20803. return deepMerge(item, submenuSpec);
  20804. };
  20805. var enrichCustom = function (item) {
  20806. var formatName = generate$1(item.title);
  20807. var customSpec = {
  20808. type: 'formatter',
  20809. format: formatName,
  20810. isSelected: isSelectedFor(formatName),
  20811. getStylePreview: getPreviewFor(formatName)
  20812. };
  20813. var newItem = deepMerge(item, customSpec);
  20814. editor.formatter.register(formatName, newItem);
  20815. return newItem;
  20816. };
  20817. var doEnrich = function (items) {
  20818. return map(items, function (item) {
  20819. var keys$1 = keys(item);
  20820. if (hasNonNullableKey(item, 'items')) {
  20821. var newItems_1 = doEnrich(item.items);
  20822. return deepMerge(enrichMenu(item), {
  20823. getStyleItems: function () {
  20824. return newItems_1;
  20825. }
  20826. });
  20827. } else if (hasNonNullableKey(item, 'format')) {
  20828. return enrichSupported(item);
  20829. } else if (keys$1.length === 1 && contains(keys$1, 'title')) {
  20830. return deepMerge(item, { type: 'separator' });
  20831. } else {
  20832. return enrichCustom(item);
  20833. }
  20834. });
  20835. };
  20836. return doEnrich(formats);
  20837. };
  20838. var init$7 = function (editor) {
  20839. var isSelectedFor = function (format) {
  20840. return function () {
  20841. return editor.formatter.match(format);
  20842. };
  20843. };
  20844. var getPreviewFor = function (format) {
  20845. return function () {
  20846. var fmt = editor.formatter.get(format);
  20847. return fmt !== undefined ? Option.some({
  20848. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  20849. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  20850. }) : Option.none();
  20851. };
  20852. };
  20853. var flatten = function (fmt) {
  20854. var subs = fmt.items;
  20855. return subs !== undefined && subs.length > 0 ? bind(subs, flatten) : [fmt.format];
  20856. };
  20857. var settingsFormats = Cell([]);
  20858. var settingsFlattenedFormats = Cell([]);
  20859. var eventsFormats = Cell([]);
  20860. var eventsFlattenedFormats = Cell([]);
  20861. var replaceSettings = Cell(false);
  20862. editor.on('PreInit', function (_e) {
  20863. var formats = getStyleFormats(editor);
  20864. var enriched = register$3(editor, formats, isSelectedFor, getPreviewFor);
  20865. settingsFormats.set(enriched);
  20866. settingsFlattenedFormats.set(bind(enriched, flatten));
  20867. });
  20868. editor.on('addStyleModifications', function (e) {
  20869. var modifications = register$3(editor, e.items, isSelectedFor, getPreviewFor);
  20870. eventsFormats.set(modifications);
  20871. replaceSettings.set(e.replace);
  20872. eventsFlattenedFormats.set(bind(modifications, flatten));
  20873. });
  20874. var getData = function () {
  20875. var fromSettings = replaceSettings.get() ? [] : settingsFormats.get();
  20876. var fromEvents = eventsFormats.get();
  20877. return fromSettings.concat(fromEvents);
  20878. };
  20879. var getFlattenedKeys = function () {
  20880. var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get();
  20881. var fromEvents = eventsFlattenedFormats.get();
  20882. return fromSettings.concat(fromEvents);
  20883. };
  20884. return {
  20885. getData: getData,
  20886. getFlattenedKeys: getFlattenedKeys
  20887. };
  20888. };
  20889. var trim$1 = global$e.trim;
  20890. var hasContentEditableState = function (value) {
  20891. return function (node) {
  20892. if (node && node.nodeType === 1) {
  20893. if (node.contentEditable === value) {
  20894. return true;
  20895. }
  20896. if (node.getAttribute('data-mce-contenteditable') === value) {
  20897. return true;
  20898. }
  20899. }
  20900. return false;
  20901. };
  20902. };
  20903. var isContentEditableTrue = hasContentEditableState('true');
  20904. var isContentEditableFalse = hasContentEditableState('false');
  20905. var create$8 = function (type, title, url, level, attach) {
  20906. return {
  20907. type: type,
  20908. title: title,
  20909. url: url,
  20910. level: level,
  20911. attach: attach
  20912. };
  20913. };
  20914. var isChildOfContentEditableTrue = function (node) {
  20915. while (node = node.parentNode) {
  20916. var value = node.contentEditable;
  20917. if (value && value !== 'inherit') {
  20918. return isContentEditableTrue(node);
  20919. }
  20920. }
  20921. return false;
  20922. };
  20923. var select = function (selector, root) {
  20924. return map(descendants(Element.fromDom(root), selector), function (element) {
  20925. return element.dom();
  20926. });
  20927. };
  20928. var getElementText = function (elm) {
  20929. return elm.innerText || elm.textContent;
  20930. };
  20931. var getOrGenerateId = function (elm) {
  20932. return elm.id ? elm.id : generate$1('h');
  20933. };
  20934. var isAnchor = function (elm) {
  20935. return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined;
  20936. };
  20937. var isValidAnchor = function (elm) {
  20938. return isAnchor(elm) && isEditable(elm);
  20939. };
  20940. var isHeader = function (elm) {
  20941. return elm && /^(H[1-6])$/.test(elm.nodeName);
  20942. };
  20943. var isEditable = function (elm) {
  20944. return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm);
  20945. };
  20946. var isValidHeader = function (elm) {
  20947. return isHeader(elm) && isEditable(elm);
  20948. };
  20949. var getLevel = function (elm) {
  20950. return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0;
  20951. };
  20952. var headerTarget = function (elm) {
  20953. var headerId = getOrGenerateId(elm);
  20954. var attach = function () {
  20955. elm.id = headerId;
  20956. };
  20957. return create$8('header', getElementText(elm), '#' + headerId, getLevel(elm), attach);
  20958. };
  20959. var anchorTarget = function (elm) {
  20960. var anchorId = elm.id || elm.name;
  20961. var anchorText = getElementText(elm);
  20962. return create$8('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop);
  20963. };
  20964. var getHeaderTargets = function (elms) {
  20965. return map(filter(elms, isValidHeader), headerTarget);
  20966. };
  20967. var getAnchorTargets = function (elms) {
  20968. return map(filter(elms, isValidAnchor), anchorTarget);
  20969. };
  20970. var getTargetElements = function (elm) {
  20971. var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm);
  20972. return elms;
  20973. };
  20974. var hasTitle = function (target) {
  20975. return trim$1(target.title).length > 0;
  20976. };
  20977. var find$5 = function (elm) {
  20978. var elms = getTargetElements(elm);
  20979. return filter(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle);
  20980. };
  20981. var LinkTargets = { find: find$5 };
  20982. var STORAGE_KEY = 'tinymce-url-history';
  20983. var HISTORY_LENGTH = 5;
  20984. var isHttpUrl = function (url) {
  20985. return isString(url) && /^https?/.test(url);
  20986. };
  20987. var isArrayOfUrl = function (a) {
  20988. return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl);
  20989. };
  20990. var isRecordOfUrlArray = function (r) {
  20991. return isObject(r) && find$1(r, function (value) {
  20992. return !isArrayOfUrl(value);
  20993. }).isNone();
  20994. };
  20995. var getAllHistory = function () {
  20996. var unparsedHistory = global$9.getItem(STORAGE_KEY);
  20997. if (unparsedHistory === null) {
  20998. return {};
  20999. }
  21000. var history;
  21001. try {
  21002. history = JSON.parse(unparsedHistory);
  21003. } catch (e) {
  21004. if (e instanceof SyntaxError) {
  21005. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e);
  21006. return {};
  21007. }
  21008. throw e;
  21009. }
  21010. if (!isRecordOfUrlArray(history)) {
  21011. domGlobals.console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history);
  21012. return {};
  21013. }
  21014. return history;
  21015. };
  21016. var setAllHistory = function (history) {
  21017. if (!isRecordOfUrlArray(history)) {
  21018. throw new Error('Bad format for history:\n' + JSON.stringify(history));
  21019. }
  21020. global$9.setItem(STORAGE_KEY, JSON.stringify(history));
  21021. };
  21022. var getHistory = function (fileType) {
  21023. var history = getAllHistory();
  21024. return Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  21025. };
  21026. var addToHistory = function (url, fileType) {
  21027. if (!isHttpUrl(url)) {
  21028. return;
  21029. }
  21030. var history = getAllHistory();
  21031. var items = Object.prototype.hasOwnProperty.call(history, fileType) ? history[fileType] : [];
  21032. var itemsWithoutUrl = filter(items, function (item) {
  21033. return item !== url;
  21034. });
  21035. history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH);
  21036. setAllHistory(history);
  21037. };
  21038. var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
  21039. var isTruthy = function (value) {
  21040. return !!value;
  21041. };
  21042. var makeMap = function (value) {
  21043. return map$1(global$e.makeMap(value, /[, ]/), isTruthy);
  21044. };
  21045. var getOpt$1 = function (obj, key) {
  21046. return hasOwnProperty$2.call(obj, key) ? Option.some(obj[key]) : Option.none();
  21047. };
  21048. var getTextSetting = function (settings, name, defaultValue) {
  21049. var value = getOpt$1(settings, name).getOr(defaultValue);
  21050. return isString(value) ? Option.some(value) : Option.none();
  21051. };
  21052. var getPicker = function (settings) {
  21053. return Option.some(settings.file_picker_callback).filter(isFunction);
  21054. };
  21055. var getPickerTypes = function (settings) {
  21056. var optFileTypes = Option.some(settings.file_picker_types).filter(isTruthy);
  21057. var optLegacyTypes = Option.some(settings.file_browser_callback_types).filter(isTruthy);
  21058. var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap);
  21059. return getPicker(settings).fold(function () {
  21060. return false;
  21061. }, function (_picker) {
  21062. return optTypes.fold(function () {
  21063. return true;
  21064. }, function (types) {
  21065. return keys(types).length > 0 ? types : false;
  21066. });
  21067. });
  21068. };
  21069. var getPickerSetting = function (settings, filetype) {
  21070. var pickerTypes = getPickerTypes(settings);
  21071. if (isBoolean(pickerTypes)) {
  21072. return pickerTypes ? getPicker(settings) : Option.none();
  21073. } else {
  21074. return pickerTypes[filetype] ? getPicker(settings) : Option.none();
  21075. }
  21076. };
  21077. var getUrlPicker = function (editor, filetype) {
  21078. return getPickerSetting(editor.settings, filetype).map(function (picker) {
  21079. return function (entry) {
  21080. return Future.nu(function (completer) {
  21081. var handler = function (value, meta) {
  21082. if (!isString(value)) {
  21083. throw new Error('Expected value to be string');
  21084. }
  21085. if (meta !== undefined && !isObject(meta)) {
  21086. throw new Error('Expected meta to be a object');
  21087. }
  21088. var r = {
  21089. value: value,
  21090. meta: meta
  21091. };
  21092. completer(r);
  21093. };
  21094. var meta = __assign({
  21095. filetype: filetype,
  21096. fieldname: entry.fieldname
  21097. }, Option.from(entry.meta).getOr({}));
  21098. picker.call(editor, handler, entry.value, meta);
  21099. });
  21100. };
  21101. });
  21102. };
  21103. var getLinkInformation = function (editor) {
  21104. if (editor.settings.typeahead_urls === false) {
  21105. return Option.none();
  21106. }
  21107. return Option.some({
  21108. targets: LinkTargets.find(editor.getBody()),
  21109. anchorTop: getTextSetting(editor.settings, 'anchor_top', '#top').getOrUndefined(),
  21110. anchorBottom: getTextSetting(editor.settings, 'anchor_bottom', '#bottom').getOrUndefined()
  21111. });
  21112. };
  21113. var getValidationHandler = function (editor) {
  21114. var optValidator = Option.from(editor.settings.file_picker_validator_handler).filter(isFunction);
  21115. return optValidator.orThunk(function () {
  21116. return Option.from(editor.settings.filepicker_validator_handler).filter(isFunction);
  21117. });
  21118. };
  21119. var UrlInputBackstage = function (editor) {
  21120. return {
  21121. getHistory: getHistory,
  21122. addToHistory: addToHistory,
  21123. getLinkInformation: function () {
  21124. return getLinkInformation(editor);
  21125. },
  21126. getValidationHandler: function () {
  21127. return getValidationHandler(editor);
  21128. },
  21129. getUrlPicker: function (filetype) {
  21130. return getUrlPicker(editor, filetype);
  21131. }
  21132. };
  21133. };
  21134. var init$8 = function (sink, editor, lazyAnchorbar) {
  21135. var contextMenuState = Cell(false);
  21136. var toolbar = HeaderBackstage(editor);
  21137. var backstage = {
  21138. shared: {
  21139. providers: {
  21140. icons: function () {
  21141. return editor.ui.registry.getAll().icons;
  21142. },
  21143. menuItems: function () {
  21144. return editor.ui.registry.getAll().menuItems;
  21145. },
  21146. translate: global$5.translate,
  21147. isReadOnly: function () {
  21148. return editor.mode.isReadOnly();
  21149. }
  21150. },
  21151. interpreter: function (s) {
  21152. return interpretWithoutForm(s, backstage);
  21153. },
  21154. anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop),
  21155. header: toolbar,
  21156. getSink: function () {
  21157. return Result.value(sink);
  21158. }
  21159. },
  21160. urlinput: UrlInputBackstage(editor),
  21161. styleselect: init$7(editor),
  21162. colorinput: ColorInputBackstage(editor),
  21163. dialog: DialogBackstage(editor),
  21164. isContextMenuOpen: function () {
  21165. return contextMenuState.get();
  21166. },
  21167. setContextMenuState: function (state) {
  21168. return contextMenuState.set(state);
  21169. }
  21170. };
  21171. return backstage;
  21172. };
  21173. var expandable$1 = constant(function (element, available) {
  21174. setMax$1(element, Math.floor(available));
  21175. });
  21176. var showContextToolbarEvent = 'contexttoolbar-show';
  21177. var hideContextToolbarEvent = 'contexttoolbar-hide';
  21178. var schema$k = constant([
  21179. strict$1('items'),
  21180. markers(['itemSelector']),
  21181. field$1('tgroupBehaviours', [Keying])
  21182. ]);
  21183. var parts$7 = constant([group({
  21184. name: 'items',
  21185. unit: 'item'
  21186. })]);
  21187. var factory$9 = function (detail, components, _spec, _externals) {
  21188. return {
  21189. uid: detail.uid,
  21190. dom: detail.dom,
  21191. components: components,
  21192. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  21193. mode: 'flow',
  21194. selector: detail.markers.itemSelector
  21195. })]),
  21196. domModification: { attributes: { role: 'toolbar' } }
  21197. };
  21198. };
  21199. var ToolbarGroup = composite$1({
  21200. name: 'ToolbarGroup',
  21201. configFields: schema$k(),
  21202. partFields: parts$7(),
  21203. factory: factory$9
  21204. });
  21205. var schema$l = constant([
  21206. strict$1('dom'),
  21207. defaulted$1('shell', true),
  21208. field$1('toolbarBehaviours', [Replacing])
  21209. ]);
  21210. var enhanceGroups = function () {
  21211. return { behaviours: derive$1([Replacing.config({})]) };
  21212. };
  21213. var parts$8 = constant([optional({
  21214. name: 'groups',
  21215. overrides: enhanceGroups
  21216. })]);
  21217. var factory$a = function (detail, components, _spec, _externals) {
  21218. var setGroups = function (toolbar, groups) {
  21219. getGroupContainer(toolbar).fold(function () {
  21220. domGlobals.console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21221. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  21222. }, function (container) {
  21223. Replacing.set(container, groups);
  21224. });
  21225. };
  21226. var getGroupContainer = function (component) {
  21227. return detail.shell ? Option.some(component) : getPart(component, detail, 'groups');
  21228. };
  21229. var extra = detail.shell ? {
  21230. behaviours: [Replacing.config({})],
  21231. components: []
  21232. } : {
  21233. behaviours: [],
  21234. components: components
  21235. };
  21236. return {
  21237. uid: detail.uid,
  21238. dom: detail.dom,
  21239. components: extra.components,
  21240. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  21241. apis: { setGroups: setGroups },
  21242. domModification: { attributes: { role: 'group' } }
  21243. };
  21244. };
  21245. var Toolbar = composite$1({
  21246. name: 'Toolbar',
  21247. configFields: schema$l(),
  21248. partFields: parts$8(),
  21249. factory: factory$a,
  21250. apis: {
  21251. setGroups: function (apis, toolbar, groups) {
  21252. apis.setGroups(toolbar, groups);
  21253. }
  21254. }
  21255. });
  21256. var generate$6 = function (xs, f) {
  21257. var init = {
  21258. len: 0,
  21259. list: []
  21260. };
  21261. var r = foldl(xs, function (b, a) {
  21262. var value = f(a, b.len);
  21263. return value.fold(constant(b), function (v) {
  21264. return {
  21265. len: v.finish(),
  21266. list: b.list.concat([v])
  21267. };
  21268. });
  21269. }, init);
  21270. return r.list;
  21271. };
  21272. var output$1 = function (within, extra, withinWidth) {
  21273. return {
  21274. within: constant(within),
  21275. extra: constant(extra),
  21276. withinWidth: constant(withinWidth)
  21277. };
  21278. };
  21279. var apportion = function (units, total, len) {
  21280. var parray = generate$6(units, function (unit, current) {
  21281. var width = len(unit);
  21282. return Option.some({
  21283. element: constant(unit),
  21284. start: constant(current),
  21285. finish: constant(current + width),
  21286. width: constant(width)
  21287. });
  21288. });
  21289. var within = filter(parray, function (unit) {
  21290. return unit.finish() <= total;
  21291. });
  21292. var withinWidth = foldr(within, function (acc, el) {
  21293. return acc + el.width();
  21294. }, 0);
  21295. var extra = parray.slice(within.length);
  21296. return {
  21297. within: constant(within),
  21298. extra: constant(extra),
  21299. withinWidth: constant(withinWidth)
  21300. };
  21301. };
  21302. var toUnit = function (parray) {
  21303. return map(parray, function (unit) {
  21304. return unit.element();
  21305. });
  21306. };
  21307. var fitLast = function (within, extra, withinWidth) {
  21308. var fits = toUnit(within.concat(extra));
  21309. return output$1(fits, [], withinWidth);
  21310. };
  21311. var overflow = function (within, extra, overflower, withinWidth) {
  21312. var fits = toUnit(within).concat([overflower]);
  21313. return output$1(fits, toUnit(extra), withinWidth);
  21314. };
  21315. var fitAll = function (within, extra, withinWidth) {
  21316. return output$1(toUnit(within), [], withinWidth);
  21317. };
  21318. var tryFit = function (total, units, len) {
  21319. var divide = apportion(units, total, len);
  21320. return divide.extra().length === 0 ? Option.some(divide) : Option.none();
  21321. };
  21322. var partition$3 = function (total, units, len, overflower) {
  21323. var divide = tryFit(total, units, len).getOrThunk(function () {
  21324. return apportion(units, total - len(overflower), len);
  21325. });
  21326. var within = divide.within();
  21327. var extra = divide.extra();
  21328. var withinWidth = divide.withinWidth();
  21329. if (extra.length === 1 && extra[0].width() <= len(overflower)) {
  21330. return fitLast(within, extra, withinWidth);
  21331. } else if (extra.length >= 1) {
  21332. return overflow(within, extra, overflower, withinWidth);
  21333. } else {
  21334. return fitAll(within, extra, withinWidth);
  21335. }
  21336. };
  21337. var setGroups = function (toolbar, storedGroups) {
  21338. var bGroups = map(storedGroups, function (g) {
  21339. return premade$1(g);
  21340. });
  21341. Toolbar.setGroups(toolbar, bGroups);
  21342. };
  21343. var findFocusedComp = function (comps) {
  21344. return findMap(comps, function (comp) {
  21345. return search(comp.element()).bind(function (focusedElm) {
  21346. return comp.getSystem().getByDom(focusedElm).toOption();
  21347. });
  21348. });
  21349. };
  21350. var refresh = function (toolbar, detail, setOverflow) {
  21351. var primary = getPartOrDie(toolbar, detail, 'primary');
  21352. var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup');
  21353. set$2(primary.element(), 'visibility', 'hidden');
  21354. var groups = detail.builtGroups.get().concat([overflowGroup]);
  21355. var focusedComp = findFocusedComp(groups);
  21356. setOverflow([]);
  21357. setGroups(primary, groups);
  21358. var availableWidth = get$7(primary.element());
  21359. var overflows = partition$3(availableWidth, detail.builtGroups.get(), function (comp) {
  21360. return get$7(comp.element());
  21361. }, overflowGroup);
  21362. if (overflows.extra().length === 0) {
  21363. Replacing.remove(primary, overflowGroup);
  21364. setOverflow([]);
  21365. } else {
  21366. setGroups(primary, overflows.within());
  21367. setOverflow(overflows.extra());
  21368. }
  21369. remove$6(primary.element(), 'visibility');
  21370. reflow(primary.element());
  21371. focusedComp.each(Focusing.focus);
  21372. };
  21373. var schema$m = constant([
  21374. field$1('splitToolbarBehaviours', [Coupling]),
  21375. state$1('builtGroups', function () {
  21376. return Cell([]);
  21377. })
  21378. ]);
  21379. var schema$n = constant([
  21380. markers(['overflowToggledClass']),
  21381. optionFunction('getOverflowBounds'),
  21382. strict$1('lazySink'),
  21383. state$1('overflowGroups', function () {
  21384. return Cell([]);
  21385. })
  21386. ].concat(schema$m()));
  21387. var parts$9 = constant([
  21388. required({
  21389. factory: Toolbar,
  21390. schema: schema$l(),
  21391. name: 'primary'
  21392. }),
  21393. external$1({
  21394. schema: schema$l(),
  21395. name: 'overflow'
  21396. }),
  21397. external$1({ name: 'overflow-button' }),
  21398. external$1({ name: 'overflow-group' })
  21399. ]);
  21400. var schema$o = constant([
  21401. markers(['toggledClass']),
  21402. strict$1('lazySink'),
  21403. strictFunction('fetch'),
  21404. optionFunction('getBounds'),
  21405. optionObjOf('fireDismissalEventInstead', [defaulted$1('event', dismissRequested())]),
  21406. schema$1()
  21407. ]);
  21408. var parts$a = constant([
  21409. external$1({
  21410. name: 'button',
  21411. overrides: function (detail) {
  21412. return {
  21413. dom: { attributes: { 'aria-haspopup': 'true' } },
  21414. buttonBehaviours: derive$1([Toggling.config({
  21415. toggleClass: detail.markers.toggledClass,
  21416. aria: { mode: 'expanded' },
  21417. toggleOnExecute: false
  21418. })])
  21419. };
  21420. }
  21421. }),
  21422. external$1({
  21423. factory: Toolbar,
  21424. schema: schema$l(),
  21425. name: 'toolbar',
  21426. overrides: function (detail) {
  21427. return {
  21428. toolbarBehaviours: derive$1([Keying.config({
  21429. mode: 'cyclic',
  21430. onEscape: function (comp) {
  21431. getPart(comp, detail, 'button').each(Focusing.focus);
  21432. return Option.none();
  21433. }
  21434. })])
  21435. };
  21436. }
  21437. })
  21438. ]);
  21439. var toggle$2 = function (button, externals) {
  21440. var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox');
  21441. if (Sandboxing.isOpen(toolbarSandbox)) {
  21442. Sandboxing.close(toolbarSandbox);
  21443. } else {
  21444. Sandboxing.open(toolbarSandbox, externals.toolbar());
  21445. }
  21446. };
  21447. var position$2 = function (button, toolbar, detail, layouts) {
  21448. var bounds = detail.getBounds.map(function (bounder) {
  21449. return bounder();
  21450. });
  21451. var sink = detail.lazySink(button).getOrDie();
  21452. Positioning.positionWithinBounds(sink, {
  21453. anchor: 'hotspot',
  21454. hotspot: button,
  21455. layouts: layouts,
  21456. overrides: { maxWidthFunction: expandable$1() }
  21457. }, toolbar, bounds);
  21458. };
  21459. var setGroups$1 = function (button, toolbar, detail, layouts, groups) {
  21460. Toolbar.setGroups(toolbar, groups);
  21461. position$2(button, toolbar, detail, layouts);
  21462. Toggling.on(button);
  21463. };
  21464. var makeSandbox$1 = function (button, spec, detail) {
  21465. var ariaOwner = manager();
  21466. var onOpen = function (sandbox, toolbar) {
  21467. detail.fetch().get(function (groups) {
  21468. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21469. ariaOwner.link(button.element());
  21470. Keying.focusIn(toolbar);
  21471. });
  21472. };
  21473. var onClose = function () {
  21474. Toggling.off(button);
  21475. Focusing.focus(button);
  21476. ariaOwner.unlink(button.element());
  21477. };
  21478. return {
  21479. dom: {
  21480. tag: 'div',
  21481. attributes: { id: ariaOwner.id }
  21482. },
  21483. behaviours: derive$1([
  21484. Keying.config({
  21485. mode: 'special',
  21486. onEscape: function (comp) {
  21487. Sandboxing.close(comp);
  21488. return Option.some(true);
  21489. }
  21490. }),
  21491. Sandboxing.config({
  21492. onOpen: onOpen,
  21493. onClose: onClose,
  21494. isPartOf: function (container, data, queryElem) {
  21495. return isPartOf(data, queryElem) || isPartOf(button, queryElem);
  21496. },
  21497. getAttachPoint: function () {
  21498. return detail.lazySink(button).getOrDie();
  21499. }
  21500. }),
  21501. Receiving.config({
  21502. channels: __assign(__assign({}, receivingChannel(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) {
  21503. return { fireEventInstead: { event: fe.event } };
  21504. }).getOr({})))), receivingChannel$1({
  21505. doReposition: function () {
  21506. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21507. position$2(button, toolbar, detail, spec.layouts);
  21508. });
  21509. }
  21510. }))
  21511. })
  21512. ])
  21513. };
  21514. };
  21515. var factory$b = function (detail, components, spec, externals) {
  21516. return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), {
  21517. action: function (button) {
  21518. toggle$2(button, externals);
  21519. },
  21520. buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({
  21521. others: {
  21522. toolbarSandbox: function (button) {
  21523. return makeSandbox$1(button, spec, detail);
  21524. }
  21525. }
  21526. })])
  21527. }))), {
  21528. apis: {
  21529. setGroups: function (button, groups) {
  21530. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21531. setGroups$1(button, toolbar, detail, spec.layouts, groups);
  21532. });
  21533. },
  21534. reposition: function (button) {
  21535. Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) {
  21536. position$2(button, toolbar, detail, spec.layouts);
  21537. });
  21538. },
  21539. toggle: function (button) {
  21540. toggle$2(button, externals);
  21541. },
  21542. getToolbar: function (button) {
  21543. return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox'));
  21544. }
  21545. }
  21546. });
  21547. };
  21548. var FloatingToolbarButton = composite$1({
  21549. name: 'FloatingToolbarButton',
  21550. factory: factory$b,
  21551. configFields: schema$o(),
  21552. partFields: parts$a(),
  21553. apis: {
  21554. setGroups: function (apis, button, groups) {
  21555. apis.setGroups(button, groups);
  21556. },
  21557. reposition: function (apis, button) {
  21558. apis.reposition(button);
  21559. },
  21560. toggle: function (apis, button) {
  21561. apis.toggle(button);
  21562. },
  21563. getToolbar: function (apis, button) {
  21564. return apis.getToolbar(button);
  21565. }
  21566. }
  21567. });
  21568. var buildGroups = function (comps) {
  21569. return map(comps, function (g) {
  21570. return premade$1(g);
  21571. });
  21572. };
  21573. var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) {
  21574. refresh(toolbar, detail, function (overflowGroups) {
  21575. detail.overflowGroups.set(overflowGroups);
  21576. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21577. FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups));
  21578. });
  21579. });
  21580. };
  21581. var factory$c = function (detail, components, spec, externals) {
  21582. var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({
  21583. fetch: function () {
  21584. return Future.nu(function (resolve) {
  21585. resolve(buildGroups(detail.overflowGroups.get()));
  21586. });
  21587. },
  21588. layouts: {
  21589. onLtr: function () {
  21590. return [
  21591. southwest$1,
  21592. southeast$1
  21593. ];
  21594. },
  21595. onRtl: function () {
  21596. return [
  21597. southeast$1,
  21598. southwest$1
  21599. ];
  21600. },
  21601. onBottomLtr: function () {
  21602. return [
  21603. northwest$1,
  21604. northeast$1
  21605. ];
  21606. },
  21607. onBottomRtl: function () {
  21608. return [
  21609. northeast$1,
  21610. northwest$1
  21611. ];
  21612. }
  21613. },
  21614. getBounds: spec.getOverflowBounds,
  21615. lazySink: detail.lazySink,
  21616. fireDismissalEventInstead: {},
  21617. markers: { toggledClass: detail.markers.overflowToggledClass },
  21618. parts: {
  21619. button: externals['overflow-button'](),
  21620. toolbar: externals.overflow()
  21621. }
  21622. }));
  21623. return {
  21624. uid: detail.uid,
  21625. dom: detail.dom,
  21626. components: components,
  21627. behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({
  21628. others: {
  21629. overflowGroup: function () {
  21630. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] }));
  21631. }
  21632. }
  21633. })]),
  21634. apis: {
  21635. setGroups: function (toolbar, groups) {
  21636. detail.builtGroups.set(map(groups, toolbar.getSystem().build));
  21637. refresh$1(toolbar, memFloatingToolbarButton, detail);
  21638. },
  21639. refresh: function (toolbar) {
  21640. return refresh$1(toolbar, memFloatingToolbarButton, detail);
  21641. },
  21642. toggle: function (toolbar) {
  21643. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21644. FloatingToolbarButton.toggle(floatingToolbarButton);
  21645. });
  21646. },
  21647. reposition: function (toolbar) {
  21648. memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) {
  21649. FloatingToolbarButton.reposition(floatingToolbarButton);
  21650. });
  21651. },
  21652. getOverflow: function (toolbar) {
  21653. return memFloatingToolbarButton.getOpt(toolbar).bind(function (floatingToolbarButton) {
  21654. return FloatingToolbarButton.getToolbar(floatingToolbarButton);
  21655. });
  21656. }
  21657. },
  21658. domModification: { attributes: { role: 'group' } }
  21659. };
  21660. };
  21661. var SplitFloatingToolbar = composite$1({
  21662. name: 'SplitFloatingToolbar',
  21663. configFields: schema$n(),
  21664. partFields: parts$9(),
  21665. factory: factory$c,
  21666. apis: {
  21667. setGroups: function (apis, toolbar, groups) {
  21668. apis.setGroups(toolbar, groups);
  21669. },
  21670. refresh: function (apis, toolbar) {
  21671. apis.refresh(toolbar);
  21672. },
  21673. reposition: function (apis, toolbar) {
  21674. apis.reposition(toolbar);
  21675. },
  21676. toggle: function (apis, toolbar) {
  21677. apis.toggle(toolbar);
  21678. },
  21679. getOverflow: function (apis, toolbar) {
  21680. return apis.getOverflow(toolbar);
  21681. }
  21682. }
  21683. });
  21684. var getAnimationRoot = function (component, slideConfig) {
  21685. return slideConfig.getAnimationRoot.fold(function () {
  21686. return component.element();
  21687. }, function (get) {
  21688. return get(component);
  21689. });
  21690. };
  21691. var getDimensionProperty = function (slideConfig) {
  21692. return slideConfig.dimension.property;
  21693. };
  21694. var getDimension = function (slideConfig, elem) {
  21695. return slideConfig.dimension.getDimension(elem);
  21696. };
  21697. var disableTransitions = function (component, slideConfig) {
  21698. var root = getAnimationRoot(component, slideConfig);
  21699. remove$5(root, [
  21700. slideConfig.shrinkingClass,
  21701. slideConfig.growingClass
  21702. ]);
  21703. };
  21704. var setShrunk = function (component, slideConfig) {
  21705. remove$4(component.element(), slideConfig.openClass);
  21706. add$2(component.element(), slideConfig.closedClass);
  21707. set$2(component.element(), getDimensionProperty(slideConfig), '0px');
  21708. reflow(component.element());
  21709. };
  21710. var setGrown = function (component, slideConfig) {
  21711. remove$4(component.element(), slideConfig.closedClass);
  21712. add$2(component.element(), slideConfig.openClass);
  21713. remove$6(component.element(), getDimensionProperty(slideConfig));
  21714. };
  21715. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  21716. slideState.setCollapsed();
  21717. set$2(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
  21718. reflow(component.element());
  21719. disableTransitions(component, slideConfig);
  21720. setShrunk(component, slideConfig);
  21721. slideConfig.onStartShrink(component);
  21722. slideConfig.onShrunk(component);
  21723. };
  21724. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  21725. var size = calculatedSize.getOrThunk(function () {
  21726. return getDimension(slideConfig, component.element());
  21727. });
  21728. slideState.setCollapsed();
  21729. set$2(component.element(), getDimensionProperty(slideConfig), size);
  21730. reflow(component.element());
  21731. var root = getAnimationRoot(component, slideConfig);
  21732. remove$4(root, slideConfig.growingClass);
  21733. add$2(root, slideConfig.shrinkingClass);
  21734. setShrunk(component, slideConfig);
  21735. slideConfig.onStartShrink(component);
  21736. };
  21737. var doStartSmartShrink = function (component, slideConfig, slideState) {
  21738. var size = getDimension(slideConfig, component.element());
  21739. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  21740. shrinker(component, slideConfig, slideState, Option.some(size));
  21741. };
  21742. var doStartGrow = function (component, slideConfig, slideState) {
  21743. var root = getAnimationRoot(component, slideConfig);
  21744. var wasShrinking = has$2(root, slideConfig.shrinkingClass);
  21745. var beforeSize = getDimension(slideConfig, component.element());
  21746. setGrown(component, slideConfig);
  21747. var fullSize = getDimension(slideConfig, component.element());
  21748. var startPartialGrow = function () {
  21749. set$2(component.element(), getDimensionProperty(slideConfig), beforeSize);
  21750. reflow(component.element());
  21751. };
  21752. var startCompleteGrow = function () {
  21753. setShrunk(component, slideConfig);
  21754. };
  21755. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  21756. setStartSize();
  21757. remove$4(root, slideConfig.shrinkingClass);
  21758. add$2(root, slideConfig.growingClass);
  21759. setGrown(component, slideConfig);
  21760. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21761. slideState.setExpanded();
  21762. slideConfig.onStartGrow(component);
  21763. };
  21764. var refresh$2 = function (component, slideConfig, slideState) {
  21765. if (slideState.isExpanded()) {
  21766. remove$6(component.element(), getDimensionProperty(slideConfig));
  21767. var fullSize = getDimension(slideConfig, component.element());
  21768. set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
  21769. }
  21770. };
  21771. var grow = function (component, slideConfig, slideState) {
  21772. if (!slideState.isExpanded()) {
  21773. doStartGrow(component, slideConfig, slideState);
  21774. }
  21775. };
  21776. var shrink = function (component, slideConfig, slideState) {
  21777. if (slideState.isExpanded()) {
  21778. doStartSmartShrink(component, slideConfig, slideState);
  21779. }
  21780. };
  21781. var immediateShrink = function (component, slideConfig, slideState) {
  21782. if (slideState.isExpanded()) {
  21783. doImmediateShrink(component, slideConfig, slideState, Option.none());
  21784. }
  21785. };
  21786. var hasGrown = function (component, slideConfig, slideState) {
  21787. return slideState.isExpanded();
  21788. };
  21789. var hasShrunk = function (component, slideConfig, slideState) {
  21790. return slideState.isCollapsed();
  21791. };
  21792. var isGrowing = function (component, slideConfig, _slideState) {
  21793. var root = getAnimationRoot(component, slideConfig);
  21794. return has$2(root, slideConfig.growingClass) === true;
  21795. };
  21796. var isShrinking = function (component, slideConfig, _slideState) {
  21797. var root = getAnimationRoot(component, slideConfig);
  21798. return has$2(root, slideConfig.shrinkingClass) === true;
  21799. };
  21800. var isTransitioning = function (component, slideConfig, slideState) {
  21801. return isGrowing(component, slideConfig) === true || isShrinking(component, slideConfig) === true;
  21802. };
  21803. var toggleGrow = function (component, slideConfig, slideState) {
  21804. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  21805. f(component, slideConfig, slideState);
  21806. };
  21807. var SlidingApis = /*#__PURE__*/Object.freeze({
  21808. __proto__: null,
  21809. refresh: refresh$2,
  21810. grow: grow,
  21811. shrink: shrink,
  21812. immediateShrink: immediateShrink,
  21813. hasGrown: hasGrown,
  21814. hasShrunk: hasShrunk,
  21815. isGrowing: isGrowing,
  21816. isShrinking: isShrinking,
  21817. isTransitioning: isTransitioning,
  21818. toggleGrow: toggleGrow,
  21819. disableTransitions: disableTransitions
  21820. });
  21821. var exhibit$6 = function (base, slideConfig, _slideState) {
  21822. var expanded = slideConfig.expanded;
  21823. return expanded ? nu$6({
  21824. classes: [slideConfig.openClass],
  21825. styles: {}
  21826. }) : nu$6({
  21827. classes: [slideConfig.closedClass],
  21828. styles: wrap$1(slideConfig.dimension.property, '0px')
  21829. });
  21830. };
  21831. var events$d = function (slideConfig, slideState) {
  21832. return derive([runOnSource(transitionend(), function (component, simulatedEvent) {
  21833. var raw = simulatedEvent.event().raw();
  21834. if (raw.propertyName === slideConfig.dimension.property) {
  21835. disableTransitions(component, slideConfig);
  21836. if (slideState.isExpanded()) {
  21837. remove$6(component.element(), slideConfig.dimension.property);
  21838. }
  21839. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  21840. notify(component);
  21841. }
  21842. })]);
  21843. };
  21844. var ActiveSliding = /*#__PURE__*/Object.freeze({
  21845. __proto__: null,
  21846. exhibit: exhibit$6,
  21847. events: events$d
  21848. });
  21849. var SlidingSchema = [
  21850. strict$1('closedClass'),
  21851. strict$1('openClass'),
  21852. strict$1('shrinkingClass'),
  21853. strict$1('growingClass'),
  21854. option('getAnimationRoot'),
  21855. onHandler('onShrunk'),
  21856. onHandler('onStartShrink'),
  21857. onHandler('onGrown'),
  21858. onHandler('onStartGrow'),
  21859. defaulted$1('expanded', false),
  21860. strictOf('dimension', choose$1('property', {
  21861. width: [
  21862. output('property', 'width'),
  21863. output('getDimension', function (elem) {
  21864. return get$7(elem) + 'px';
  21865. })
  21866. ],
  21867. height: [
  21868. output('property', 'height'),
  21869. output('getDimension', function (elem) {
  21870. return get$6(elem) + 'px';
  21871. })
  21872. ]
  21873. }))
  21874. ];
  21875. var init$9 = function (spec) {
  21876. var state = Cell(spec.expanded);
  21877. var readState = function () {
  21878. return 'expanded: ' + state.get();
  21879. };
  21880. return nu$5({
  21881. isExpanded: function () {
  21882. return state.get() === true;
  21883. },
  21884. isCollapsed: function () {
  21885. return state.get() === false;
  21886. },
  21887. setCollapsed: curry(state.set, false),
  21888. setExpanded: curry(state.set, true),
  21889. readState: readState
  21890. });
  21891. };
  21892. var SlidingState = /*#__PURE__*/Object.freeze({
  21893. __proto__: null,
  21894. init: init$9
  21895. });
  21896. var Sliding = create$1({
  21897. fields: SlidingSchema,
  21898. name: 'sliding',
  21899. active: ActiveSliding,
  21900. apis: SlidingApis,
  21901. state: SlidingState
  21902. });
  21903. var schema$p = constant([
  21904. markers([
  21905. 'closedClass',
  21906. 'openClass',
  21907. 'shrinkingClass',
  21908. 'growingClass',
  21909. 'overflowToggledClass'
  21910. ]),
  21911. onHandler('onOpened'),
  21912. onHandler('onClosed')
  21913. ].concat(schema$m()));
  21914. var parts$b = constant([
  21915. required({
  21916. factory: Toolbar,
  21917. schema: schema$l(),
  21918. name: 'primary'
  21919. }),
  21920. required({
  21921. factory: Toolbar,
  21922. schema: schema$l(),
  21923. name: 'overflow',
  21924. overrides: function (detail) {
  21925. return {
  21926. toolbarBehaviours: derive$1([
  21927. Sliding.config({
  21928. dimension: { property: 'height' },
  21929. closedClass: detail.markers.closedClass,
  21930. openClass: detail.markers.openClass,
  21931. shrinkingClass: detail.markers.shrinkingClass,
  21932. growingClass: detail.markers.growingClass,
  21933. onShrunk: function (comp) {
  21934. getPart(comp, detail, 'overflow-button').each(function (button) {
  21935. Toggling.off(button);
  21936. Focusing.focus(button);
  21937. });
  21938. detail.onClosed(comp);
  21939. },
  21940. onGrown: function (comp) {
  21941. Keying.focusIn(comp);
  21942. detail.onOpened(comp);
  21943. },
  21944. onStartGrow: function (comp) {
  21945. getPart(comp, detail, 'overflow-button').each(Toggling.on);
  21946. }
  21947. }),
  21948. Keying.config({
  21949. mode: 'acyclic',
  21950. onEscape: function (comp) {
  21951. getPart(comp, detail, 'overflow-button').each(Focusing.focus);
  21952. return Option.some(true);
  21953. }
  21954. })
  21955. ])
  21956. };
  21957. }
  21958. }),
  21959. external$1({
  21960. name: 'overflow-button',
  21961. overrides: function (detail) {
  21962. return {
  21963. buttonBehaviours: derive$1([Toggling.config({
  21964. toggleClass: detail.markers.overflowToggledClass,
  21965. aria: { mode: 'pressed' },
  21966. toggleOnExecute: false
  21967. })])
  21968. };
  21969. }
  21970. }),
  21971. external$1({ name: 'overflow-group' })
  21972. ]);
  21973. var toggleToolbar = function (toolbar, detail) {
  21974. getPart(toolbar, detail, 'overflow').each(function (overf) {
  21975. refresh$3(toolbar, detail);
  21976. Sliding.toggleGrow(overf);
  21977. });
  21978. };
  21979. var refresh$3 = function (toolbar, detail) {
  21980. getPart(toolbar, detail, 'overflow').each(function (overflow) {
  21981. refresh(toolbar, detail, function (groups) {
  21982. var builtGroups = map(groups, function (g) {
  21983. return premade$1(g);
  21984. });
  21985. Toolbar.setGroups(overflow, builtGroups);
  21986. });
  21987. getPart(toolbar, detail, 'overflow-button').each(function (button) {
  21988. if (Sliding.hasGrown(overflow)) {
  21989. Toggling.on(button);
  21990. }
  21991. });
  21992. Sliding.refresh(overflow);
  21993. });
  21994. };
  21995. var factory$d = function (detail, components, spec, externals) {
  21996. var toolbarToggleEvent = 'alloy.toolbar.toggle';
  21997. var doSetGroups = function (toolbar, groups) {
  21998. var built = map(groups, toolbar.getSystem().build);
  21999. detail.builtGroups.set(built);
  22000. };
  22001. return {
  22002. uid: detail.uid,
  22003. dom: detail.dom,
  22004. components: components,
  22005. behaviours: augment(detail.splitToolbarBehaviours, [
  22006. Coupling.config({
  22007. others: {
  22008. overflowGroup: function (toolbar) {
  22009. return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), {
  22010. items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), {
  22011. action: function (_button) {
  22012. emit(toolbar, toolbarToggleEvent);
  22013. }
  22014. }))]
  22015. }));
  22016. }
  22017. }
  22018. }),
  22019. config('toolbar-toggle-events', [run(toolbarToggleEvent, function (toolbar) {
  22020. getPart(toolbar, detail, 'overflow').each(function (overf) {
  22021. refresh$3(toolbar, detail);
  22022. Sliding.toggleGrow(overf);
  22023. });
  22024. })])
  22025. ]),
  22026. apis: {
  22027. setGroups: function (toolbar, groups) {
  22028. doSetGroups(toolbar, groups);
  22029. refresh$3(toolbar, detail);
  22030. },
  22031. refresh: function (toolbar) {
  22032. return refresh$3(toolbar, detail);
  22033. },
  22034. toggle: function (toolbar) {
  22035. return toggleToolbar(toolbar, detail);
  22036. }
  22037. },
  22038. domModification: { attributes: { role: 'group' } }
  22039. };
  22040. };
  22041. var SplitSlidingToolbar = composite$1({
  22042. name: 'SplitSlidingToolbar',
  22043. configFields: schema$p(),
  22044. partFields: parts$b(),
  22045. factory: factory$d,
  22046. apis: {
  22047. setGroups: function (apis, toolbar, groups) {
  22048. apis.setGroups(toolbar, groups);
  22049. },
  22050. refresh: function (apis, toolbar) {
  22051. apis.refresh(toolbar);
  22052. },
  22053. toggle: function (apis, toolbar) {
  22054. apis.toggle(toolbar);
  22055. }
  22056. }
  22057. });
  22058. var toolbarHeightChange = constant(generate$1('toolbar-height-change'));
  22059. var renderToolbarGroupCommon = function (toolbarGroup) {
  22060. var attributes = toolbarGroup.title.fold(function () {
  22061. return {};
  22062. }, function (title) {
  22063. return { attributes: { title: title } };
  22064. });
  22065. return {
  22066. dom: __assign({
  22067. tag: 'div',
  22068. classes: ['tox-toolbar__group']
  22069. }, attributes),
  22070. components: [ToolbarGroup.parts().items({})],
  22071. items: toolbarGroup.items,
  22072. markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' },
  22073. tgroupBehaviours: derive$1([
  22074. Tabstopping.config({}),
  22075. Focusing.config({})
  22076. ])
  22077. };
  22078. };
  22079. var renderToolbarGroup = function (toolbarGroup) {
  22080. return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup));
  22081. };
  22082. var getToolbarbehaviours = function (toolbarSpec, modeName) {
  22083. var onAttached = runOnAttached(function (component) {
  22084. var groups = map(toolbarSpec.initGroups, renderToolbarGroup);
  22085. Toolbar.setGroups(component, groups);
  22086. });
  22087. return derive$1([
  22088. DisablingConfigs.toolbarButton(toolbarSpec.providers.isReadOnly),
  22089. receivingConfig(),
  22090. Keying.config({
  22091. mode: modeName,
  22092. onEscape: toolbarSpec.onEscape,
  22093. selector: '.tox-toolbar__group'
  22094. }),
  22095. config('toolbar-events', [onAttached])
  22096. ]);
  22097. };
  22098. var renderMoreToolbarCommon = function (toolbarSpec) {
  22099. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22100. return {
  22101. uid: toolbarSpec.uid,
  22102. dom: {
  22103. tag: 'div',
  22104. classes: ['tox-toolbar-overlord']
  22105. },
  22106. parts: {
  22107. 'overflow-group': renderToolbarGroupCommon({
  22108. title: Option.none(),
  22109. items: []
  22110. }),
  22111. 'overflow-button': renderIconButtonSpec({
  22112. name: 'more',
  22113. icon: Option.some('more-drawer'),
  22114. disabled: false,
  22115. tooltip: Option.some('More...'),
  22116. primary: false,
  22117. borderless: false
  22118. }, Option.none(), toolbarSpec.providers)
  22119. },
  22120. splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  22121. };
  22122. };
  22123. var renderFloatingMoreToolbar = function (toolbarSpec) {
  22124. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  22125. var overflowXOffset = 4;
  22126. var primary = SplitFloatingToolbar.parts().primary({
  22127. dom: {
  22128. tag: 'div',
  22129. classes: ['tox-toolbar__primary']
  22130. }
  22131. });
  22132. return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22133. lazySink: toolbarSpec.getSink,
  22134. getOverflowBounds: function () {
  22135. var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element();
  22136. var headerBounds = absolute$1(headerElem);
  22137. var docElem = documentElement(headerElem);
  22138. var docBounds = absolute$1(docElem);
  22139. var height = Math.max(docElem.dom().scrollHeight, docBounds.height);
  22140. return bounds$1(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height);
  22141. },
  22142. parts: __assign(__assign({}, baseSpec.parts), {
  22143. overflow: {
  22144. dom: {
  22145. tag: 'div',
  22146. classes: ['tox-toolbar__overflow'],
  22147. attributes: toolbarSpec.attributes
  22148. }
  22149. }
  22150. }),
  22151. components: [primary],
  22152. markers: { overflowToggledClass: 'tox-tbtn--enabled' }
  22153. }));
  22154. };
  22155. var renderSlidingMoreToolbar = function (toolbarSpec) {
  22156. var primary = SplitSlidingToolbar.parts().primary({
  22157. dom: {
  22158. tag: 'div',
  22159. classes: ['tox-toolbar__primary']
  22160. }
  22161. });
  22162. var overflow = SplitSlidingToolbar.parts().overflow({
  22163. dom: {
  22164. tag: 'div',
  22165. classes: ['tox-toolbar__overflow']
  22166. }
  22167. });
  22168. var baseSpec = renderMoreToolbarCommon(toolbarSpec);
  22169. return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), {
  22170. components: [
  22171. primary,
  22172. overflow
  22173. ],
  22174. markers: {
  22175. openClass: 'tox-toolbar__overflow--open',
  22176. closedClass: 'tox-toolbar__overflow--closed',
  22177. growingClass: 'tox-toolbar__overflow--growing',
  22178. shrinkingClass: 'tox-toolbar__overflow--shrinking',
  22179. overflowToggledClass: 'tox-tbtn--enabled'
  22180. },
  22181. onOpened: function (comp) {
  22182. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' });
  22183. },
  22184. onClosed: function (comp) {
  22185. comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' });
  22186. }
  22187. }));
  22188. };
  22189. var renderToolbar = function (toolbarSpec) {
  22190. var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic';
  22191. return Toolbar.sketch({
  22192. uid: toolbarSpec.uid,
  22193. dom: {
  22194. tag: 'div',
  22195. classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : [])
  22196. },
  22197. components: [Toolbar.parts().groups({})],
  22198. toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName)
  22199. });
  22200. };
  22201. var baseToolbarButtonFields = [
  22202. defaultedBoolean('disabled', false),
  22203. optionString('tooltip'),
  22204. optionString('icon'),
  22205. optionString('text'),
  22206. defaultedFunction('onSetup', function () {
  22207. return noop;
  22208. })
  22209. ];
  22210. var toolbarButtonSchema = objOf([
  22211. strictString('type'),
  22212. strictFunction('onAction')
  22213. ].concat(baseToolbarButtonFields));
  22214. var createToolbarButton = function (spec) {
  22215. return asRaw('toolbarbutton', toolbarButtonSchema, spec);
  22216. };
  22217. var baseMenuButtonFields = [
  22218. optionString('text'),
  22219. optionString('tooltip'),
  22220. optionString('icon'),
  22221. strictFunction('fetch'),
  22222. defaultedFunction('onSetup', function () {
  22223. return noop;
  22224. })
  22225. ];
  22226. var MenuButtonSchema = objOf(__spreadArrays([strictString('type')], baseMenuButtonFields));
  22227. var createMenuButton = function (spec) {
  22228. return asRaw('menubutton', MenuButtonSchema, spec);
  22229. };
  22230. var splitButtonSchema = objOf([
  22231. strictString('type'),
  22232. optionString('tooltip'),
  22233. optionString('icon'),
  22234. optionString('text'),
  22235. optionFunction('select'),
  22236. strictFunction('fetch'),
  22237. defaultedFunction('onSetup', function () {
  22238. return noop;
  22239. }),
  22240. defaultedStringEnum('presets', 'normal', [
  22241. 'normal',
  22242. 'color',
  22243. 'listpreview'
  22244. ]),
  22245. defaulted$1('columns', 1),
  22246. strictFunction('onAction'),
  22247. strictFunction('onItemAction')
  22248. ]);
  22249. var createSplitButton = function (spec) {
  22250. return asRaw('SplitButton', splitButtonSchema, spec);
  22251. };
  22252. var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields);
  22253. var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([
  22254. strictString('type'),
  22255. strictFunction('onAction')
  22256. ]));
  22257. var createToggleButton = function (spec) {
  22258. return asRaw('ToggleButton', toggleButtonSchema, spec);
  22259. };
  22260. var groupToolbarButtonSchema = objOf([
  22261. strictString('type'),
  22262. strictOf('items', oneOf([
  22263. arrOfObj$1([
  22264. strictString('name'),
  22265. strictArrayOf('items', string)
  22266. ]),
  22267. string
  22268. ]))
  22269. ].concat(baseToolbarButtonFields));
  22270. var createGroupToolbarButton = function (spec) {
  22271. return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec);
  22272. };
  22273. var contextBarFields = [
  22274. defaultedFunction('predicate', function () {
  22275. return false;
  22276. }),
  22277. defaultedStringEnum('scope', 'node', [
  22278. 'node',
  22279. 'editor'
  22280. ]),
  22281. defaultedStringEnum('position', 'selection', [
  22282. 'node',
  22283. 'selection',
  22284. 'line'
  22285. ])
  22286. ];
  22287. var contextButtonFields = baseToolbarButtonFields.concat([
  22288. defaulted$1('type', 'contextformbutton'),
  22289. defaulted$1('primary', false),
  22290. strictFunction('onAction'),
  22291. state$1('original', identity)
  22292. ]);
  22293. var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([
  22294. defaulted$1('type', 'contextformbutton'),
  22295. defaulted$1('primary', false),
  22296. strictFunction('onAction'),
  22297. state$1('original', identity)
  22298. ]);
  22299. var launchButtonFields = baseToolbarButtonFields.concat([defaulted$1('type', 'contextformbutton')]);
  22300. var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted$1('type', 'contextformtogglebutton')]);
  22301. var toggleOrNormal = choose$1('type', {
  22302. contextformbutton: contextButtonFields,
  22303. contextformtogglebutton: contextToggleButtonFields
  22304. });
  22305. var contextFormSchema = objOf([
  22306. defaulted$1('type', 'contextform'),
  22307. defaultedFunction('initValue', function () {
  22308. return '';
  22309. }),
  22310. optionString('label'),
  22311. strictArrayOf('commands', toggleOrNormal),
  22312. optionOf('launch', choose$1('type', {
  22313. contextformbutton: launchButtonFields,
  22314. contextformtogglebutton: launchToggleButtonFields
  22315. }))
  22316. ].concat(contextBarFields));
  22317. var contextToolbarSchema = objOf([
  22318. defaulted$1('type', 'contexttoolbar'),
  22319. strictString('items')
  22320. ].concat(contextBarFields));
  22321. var createContextToolbar = function (spec) {
  22322. return asRaw('ContextToolbar', contextToolbarSchema, spec);
  22323. };
  22324. var createContextForm = function (spec) {
  22325. return asRaw('ContextForm', contextFormSchema, spec);
  22326. };
  22327. var getState$2 = function (component, replaceConfig, reflectState) {
  22328. return reflectState;
  22329. };
  22330. var ReflectingApis = /*#__PURE__*/Object.freeze({
  22331. __proto__: null,
  22332. getState: getState$2
  22333. });
  22334. var events$e = function (reflectingConfig, reflectingState) {
  22335. var update = function (component, data) {
  22336. reflectingConfig.updateState.each(function (updateState) {
  22337. var newState = updateState(component, data);
  22338. reflectingState.set(newState);
  22339. });
  22340. reflectingConfig.renderComponents.each(function (renderComponents) {
  22341. var newComponents = renderComponents(data, reflectingState.get());
  22342. var newChildren = map(newComponents, component.getSystem().build);
  22343. replaceChildren(component, newChildren);
  22344. });
  22345. };
  22346. return derive([
  22347. run(receive(), function (component, message) {
  22348. var receivingData = message;
  22349. var channel = reflectingConfig.channel;
  22350. if (contains(receivingData.channels(), channel)) {
  22351. update(component, receivingData.data());
  22352. }
  22353. }),
  22354. runOnAttached(function (comp, _se) {
  22355. reflectingConfig.initialData.each(function (rawData) {
  22356. update(comp, rawData);
  22357. });
  22358. })
  22359. ]);
  22360. };
  22361. var ActiveReflecting = /*#__PURE__*/Object.freeze({
  22362. __proto__: null,
  22363. events: events$e
  22364. });
  22365. var init$a = function () {
  22366. var cell = Cell(Option.none());
  22367. var set = function (optS) {
  22368. return cell.set(optS);
  22369. };
  22370. var clear = function () {
  22371. return cell.set(Option.none());
  22372. };
  22373. var get = function () {
  22374. return cell.get();
  22375. };
  22376. var readState = function () {
  22377. return cell.get().fold(function () {
  22378. return 'none';
  22379. }, function (x) {
  22380. return x;
  22381. });
  22382. };
  22383. return {
  22384. readState: readState,
  22385. get: get,
  22386. set: set,
  22387. clear: clear
  22388. };
  22389. };
  22390. var ReflectingState = /*#__PURE__*/Object.freeze({
  22391. __proto__: null,
  22392. init: init$a
  22393. });
  22394. var ReflectingSchema = [
  22395. strict$1('channel'),
  22396. option('renderComponents'),
  22397. option('updateState'),
  22398. option('initialData')
  22399. ];
  22400. var Reflecting = create$1({
  22401. fields: ReflectingSchema,
  22402. name: 'reflecting',
  22403. active: ActiveReflecting,
  22404. apis: ReflectingApis,
  22405. state: ReflectingState
  22406. });
  22407. var schema$q = constant([
  22408. strict$1('toggleClass'),
  22409. strict$1('fetch'),
  22410. onStrictHandler('onExecute'),
  22411. defaulted$1('getHotspot', Option.some),
  22412. defaulted$1('getAnchorOverrides', constant({})),
  22413. schema$1(),
  22414. onStrictHandler('onItemExecute'),
  22415. option('lazySink'),
  22416. strict$1('dom'),
  22417. onHandler('onOpen'),
  22418. field$1('splitDropdownBehaviours', [
  22419. Coupling,
  22420. Keying,
  22421. Focusing
  22422. ]),
  22423. defaulted$1('matchWidth', false),
  22424. defaulted$1('useMinWidth', false),
  22425. defaulted$1('eventOrder', {}),
  22426. option('role')
  22427. ].concat(sandboxFields()));
  22428. var arrowPart = required({
  22429. factory: Button,
  22430. schema: [strict$1('dom')],
  22431. name: 'arrow',
  22432. defaults: function () {
  22433. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22434. },
  22435. overrides: function (detail) {
  22436. return {
  22437. dom: {
  22438. tag: 'span',
  22439. attributes: { role: 'presentation' }
  22440. },
  22441. action: function (arrow) {
  22442. arrow.getSystem().getByUid(detail.uid).each(emitExecute);
  22443. },
  22444. buttonBehaviours: derive$1([Toggling.config({
  22445. toggleOnExecute: false,
  22446. toggleClass: detail.toggleClass
  22447. })])
  22448. };
  22449. }
  22450. });
  22451. var buttonPart = required({
  22452. factory: Button,
  22453. schema: [strict$1('dom')],
  22454. name: 'button',
  22455. defaults: function () {
  22456. return { buttonBehaviours: derive$1([Focusing.revoke()]) };
  22457. },
  22458. overrides: function (detail) {
  22459. return {
  22460. dom: {
  22461. tag: 'span',
  22462. attributes: { role: 'presentation' }
  22463. },
  22464. action: function (btn) {
  22465. btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22466. detail.onExecute(splitDropdown, btn);
  22467. });
  22468. }
  22469. };
  22470. }
  22471. });
  22472. var parts$c = constant([
  22473. arrowPart,
  22474. buttonPart,
  22475. optional({
  22476. factory: {
  22477. sketch: function (spec) {
  22478. return {
  22479. uid: spec.uid,
  22480. dom: {
  22481. tag: 'span',
  22482. styles: { display: 'none' },
  22483. attributes: { 'aria-hidden': 'true' },
  22484. innerHtml: spec.text
  22485. }
  22486. };
  22487. }
  22488. },
  22489. schema: [strict$1('text')],
  22490. name: 'aria-descriptor'
  22491. }),
  22492. external$1({
  22493. schema: [tieredMenuMarkers()],
  22494. name: 'menu',
  22495. defaults: function (detail) {
  22496. return {
  22497. onExecute: function (tmenu, item) {
  22498. tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) {
  22499. detail.onItemExecute(splitDropdown, tmenu, item);
  22500. });
  22501. }
  22502. };
  22503. }
  22504. }),
  22505. partType()
  22506. ]);
  22507. var factory$e = function (detail, components, spec, externals) {
  22508. var switchToMenu = function (sandbox) {
  22509. Composing.getCurrent(sandbox).each(function (current) {
  22510. Highlighting.highlightFirst(current);
  22511. Keying.focusIn(current);
  22512. });
  22513. };
  22514. var action = function (component) {
  22515. var onOpenSync = switchToMenu;
  22516. togglePopup(detail, function (x) {
  22517. return x;
  22518. }, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop);
  22519. };
  22520. var openMenu = function (comp) {
  22521. action(comp);
  22522. return Option.some(true);
  22523. };
  22524. var executeOnButton = function (comp) {
  22525. var button = getPartOrDie(comp, detail, 'button');
  22526. emitExecute(button);
  22527. return Option.some(true);
  22528. };
  22529. var buttonEvents = __assign(__assign({}, derive([runOnAttached(function (component, _simulatedEvent) {
  22530. var ariaDescriptor = getPart(component, detail, 'aria-descriptor');
  22531. ariaDescriptor.each(function (descriptor) {
  22532. var descriptorId = generate$1('aria');
  22533. set$1(descriptor.element(), 'id', descriptorId);
  22534. set$1(component.element(), 'aria-describedby', descriptorId);
  22535. });
  22536. })])), events$7(Option.some(action)));
  22537. var apis = {
  22538. repositionMenus: function (comp) {
  22539. if (Toggling.isOn(comp)) {
  22540. repositionMenus(comp);
  22541. }
  22542. }
  22543. };
  22544. return {
  22545. uid: detail.uid,
  22546. dom: detail.dom,
  22547. components: components,
  22548. apis: apis,
  22549. eventOrder: __assign(__assign({}, detail.eventOrder), {
  22550. 'alloy.execute': [
  22551. 'disabling',
  22552. 'toggling',
  22553. 'alloy.base.behaviour'
  22554. ]
  22555. }),
  22556. events: buttonEvents,
  22557. behaviours: augment(detail.splitDropdownBehaviours, [
  22558. Coupling.config({
  22559. others: {
  22560. sandbox: function (hotspot) {
  22561. var arrow = getPartOrDie(hotspot, detail, 'arrow');
  22562. var extras = {
  22563. onOpen: function () {
  22564. Toggling.on(arrow);
  22565. Toggling.on(hotspot);
  22566. },
  22567. onClose: function () {
  22568. Toggling.off(arrow);
  22569. Toggling.off(hotspot);
  22570. }
  22571. };
  22572. return makeSandbox(detail, hotspot, extras);
  22573. }
  22574. }
  22575. }),
  22576. Keying.config({
  22577. mode: 'special',
  22578. onSpace: executeOnButton,
  22579. onEnter: executeOnButton,
  22580. onDown: openMenu
  22581. }),
  22582. Focusing.config({}),
  22583. Toggling.config({
  22584. toggleOnExecute: false,
  22585. aria: { mode: 'expanded' }
  22586. })
  22587. ]),
  22588. domModification: {
  22589. attributes: {
  22590. 'role': detail.role.getOr('button'),
  22591. 'aria-haspopup': true
  22592. }
  22593. }
  22594. };
  22595. };
  22596. var SplitDropdown = composite$1({
  22597. name: 'SplitDropdown',
  22598. configFields: schema$q(),
  22599. partFields: parts$c(),
  22600. factory: factory$e,
  22601. apis: {
  22602. repositionMenus: function (apis, comp) {
  22603. return apis.repositionMenus(comp);
  22604. }
  22605. }
  22606. });
  22607. var getButtonApi = function (component) {
  22608. return {
  22609. isDisabled: function () {
  22610. return Disabling.isDisabled(component);
  22611. },
  22612. setDisabled: function (state) {
  22613. return Disabling.set(component, state);
  22614. }
  22615. };
  22616. };
  22617. var getToggleApi = function (component) {
  22618. return {
  22619. setActive: function (state) {
  22620. Toggling.set(component, state);
  22621. },
  22622. isActive: function () {
  22623. return Toggling.isOn(component);
  22624. },
  22625. isDisabled: function () {
  22626. return Disabling.isDisabled(component);
  22627. },
  22628. setDisabled: function (state) {
  22629. return Disabling.set(component, state);
  22630. }
  22631. };
  22632. };
  22633. var getTooltipAttributes = function (tooltip, providersBackstage) {
  22634. return tooltip.map(function (tooltip) {
  22635. return {
  22636. 'aria-label': providersBackstage.translate(tooltip),
  22637. 'title': providersBackstage.translate(tooltip)
  22638. };
  22639. }).getOr({});
  22640. };
  22641. var focusButtonEvent = generate$1('focus-button');
  22642. var rtlIcon$1 = [
  22643. 'checklist',
  22644. 'ordered-list'
  22645. ];
  22646. var rtlTransform$1 = [
  22647. 'indent',
  22648. 'outdent',
  22649. 'table-insert-column-after',
  22650. 'table-insert-column-before',
  22651. 'unordered-list'
  22652. ];
  22653. var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) {
  22654. var _d;
  22655. var getIconName = function (iconName) {
  22656. return global$5.isRtl() && contains(rtlIcon$1, iconName) ? iconName + '-rtl' : iconName;
  22657. };
  22658. var needsRtlClass = global$5.isRtl() && icon.exists(function (name) {
  22659. return contains(rtlTransform$1, name);
  22660. });
  22661. return {
  22662. dom: {
  22663. tag: 'button',
  22664. classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []).concat(needsRtlClass ? ['tox-tbtn__icon-rtl'] : []),
  22665. attributes: getTooltipAttributes(tooltip, providersBackstage)
  22666. },
  22667. components: componentRenderPipeline([
  22668. icon.map(function (iconName) {
  22669. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22670. }),
  22671. text.map(function (text) {
  22672. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22673. })
  22674. ]),
  22675. eventOrder: (_d = {}, _d[mousedown()] = [
  22676. 'focusing',
  22677. 'alloy.base.behaviour',
  22678. 'common-button-display-events'
  22679. ], _d),
  22680. buttonBehaviours: derive$1([
  22681. DisablingConfigs.toolbarButton(providersBackstage.isReadOnly),
  22682. receivingConfig(),
  22683. config('common-button-display-events', [run(mousedown(), function (button, se) {
  22684. se.event().prevent();
  22685. emit(button, focusButtonEvent);
  22686. })])
  22687. ].concat(receiver.map(function (r) {
  22688. return Reflecting.config({
  22689. channel: r,
  22690. initialData: {
  22691. icon: icon,
  22692. text: text
  22693. },
  22694. renderComponents: function (data, _state) {
  22695. return componentRenderPipeline([
  22696. data.icon.map(function (iconName) {
  22697. return renderIconFromPack(getIconName(iconName), providersBackstage.icons);
  22698. }),
  22699. data.text.map(function (text) {
  22700. return renderLabel$1(text, 'tox-tbtn', providersBackstage);
  22701. })
  22702. ]);
  22703. }
  22704. });
  22705. }).toArray()).concat(behaviours.getOr([])))
  22706. };
  22707. };
  22708. var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) {
  22709. var sharedBackstage = backstage.shared;
  22710. return FloatingToolbarButton.sketch({
  22711. lazySink: sharedBackstage.getSink,
  22712. fetch: function () {
  22713. return Future.nu(function (resolve) {
  22714. resolve(map(identifyButtons(spec.items), renderToolbarGroup));
  22715. });
  22716. },
  22717. markers: { toggledClass: 'tox-tbtn--enabled' },
  22718. parts: {
  22719. button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Option.none(), Option.none(), sharedBackstage.providers),
  22720. toolbar: {
  22721. dom: {
  22722. tag: 'div',
  22723. classes: ['tox-toolbar__overflow'],
  22724. attributes: attributes
  22725. }
  22726. }
  22727. }
  22728. });
  22729. };
  22730. var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) {
  22731. var editorOffCell = Cell(noop);
  22732. var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Option.none(), Option.none(), providersBackstage);
  22733. return Button.sketch({
  22734. dom: structure.dom,
  22735. components: structure.components,
  22736. eventOrder: toolbarButtonEventOrder,
  22737. buttonBehaviours: derive$1([
  22738. config('toolbar-button-events', [
  22739. onToolbarButtonExecute({
  22740. onAction: spec.onAction,
  22741. getApi: specialisation.getApi
  22742. }),
  22743. onControlAttached(specialisation, editorOffCell),
  22744. onControlDetached(specialisation, editorOffCell)
  22745. ]),
  22746. DisablingConfigs.toolbarButton(function () {
  22747. return spec.disabled || providersBackstage.isReadOnly();
  22748. }),
  22749. receivingConfig()
  22750. ].concat(specialisation.toolbarButtonBehaviours))
  22751. });
  22752. };
  22753. var renderToolbarButton = function (spec, providersBackstage) {
  22754. return renderToolbarButtonWith(spec, providersBackstage, []);
  22755. };
  22756. var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) {
  22757. return renderCommonToolbarButton(spec, {
  22758. toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []),
  22759. getApi: getButtonApi,
  22760. onSetup: spec.onSetup
  22761. }, providersBackstage);
  22762. };
  22763. var renderToolbarToggleButton = function (spec, providersBackstage) {
  22764. return renderToolbarToggleButtonWith(spec, providersBackstage, []);
  22765. };
  22766. var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) {
  22767. return deepMerge(renderCommonToolbarButton(spec, {
  22768. toolbarButtonBehaviours: [
  22769. Replacing.config({}),
  22770. Toggling.config({
  22771. toggleClass: 'tox-tbtn--enabled',
  22772. aria: { mode: 'pressed' },
  22773. toggleOnExecute: false
  22774. })
  22775. ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []),
  22776. getApi: getToggleApi,
  22777. onSetup: spec.onSetup
  22778. }, providersBackstage));
  22779. };
  22780. var fetchChoices = function (getApi, spec, providersBackstage) {
  22781. return function (comp) {
  22782. return Future.nu(function (callback) {
  22783. return spec.fetch(callback);
  22784. }).map(function (items) {
  22785. return Option.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$1('menu-value'), items, function (value) {
  22786. spec.onItemAction(getApi(comp), value);
  22787. }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(function () {
  22788. return false;
  22789. }), providersBackstage), {
  22790. movement: deriveMenuMovement(spec.columns, spec.presets),
  22791. menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) {
  22792. detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) {
  22793. var numRows = _d.numRows, numColumns = _d.numColumns;
  22794. Keying.setGridSize(comp, numRows, numColumns);
  22795. });
  22796. })])
  22797. })));
  22798. });
  22799. };
  22800. };
  22801. var renderSplitButton = function (spec, sharedBackstage) {
  22802. var _d;
  22803. var displayChannel = generate$1('channel-update-split-dropdown-display');
  22804. var getApi = function (comp) {
  22805. return {
  22806. isDisabled: function () {
  22807. return Disabling.isDisabled(comp);
  22808. },
  22809. setDisabled: function (state) {
  22810. return Disabling.set(comp, state);
  22811. },
  22812. setIconFill: function (id, value) {
  22813. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22814. set$1(underlinePath, 'fill', value);
  22815. });
  22816. },
  22817. setIconStroke: function (id, value) {
  22818. descendant$1(comp.element(), 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) {
  22819. set$1(underlinePath, 'stroke', value);
  22820. });
  22821. },
  22822. setActive: function (state) {
  22823. set$1(comp.element(), 'aria-pressed', state);
  22824. descendant$1(comp.element(), 'span').each(function (button) {
  22825. comp.getSystem().getByDom(button).each(function (buttonComp) {
  22826. return Toggling.set(buttonComp, state);
  22827. });
  22828. });
  22829. },
  22830. isActive: function () {
  22831. return descendant$1(comp.element(), 'span').exists(function (button) {
  22832. return comp.getSystem().getByDom(button).exists(Toggling.isOn);
  22833. });
  22834. }
  22835. };
  22836. };
  22837. var editorOffCell = Cell(noop);
  22838. var specialisation = {
  22839. getApi: getApi,
  22840. onSetup: spec.onSetup
  22841. };
  22842. return SplitDropdown.sketch({
  22843. dom: {
  22844. tag: 'div',
  22845. classes: ['tox-split-button'],
  22846. attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers))
  22847. },
  22848. onExecute: function (button) {
  22849. spec.onAction(getApi(button));
  22850. },
  22851. onItemExecute: function (_a, _b, _c) {
  22852. },
  22853. splitDropdownBehaviours: derive$1([
  22854. DisablingConfigs.splitButton(sharedBackstage.providers.isReadOnly),
  22855. receivingConfig(),
  22856. config('split-dropdown-events', [
  22857. run(focusButtonEvent, Focusing.focus),
  22858. onControlAttached(specialisation, editorOffCell),
  22859. onControlDetached(specialisation, editorOffCell)
  22860. ]),
  22861. Unselecting.config({})
  22862. ]),
  22863. eventOrder: (_d = {}, _d[attachedToDom()] = [
  22864. 'alloy.base.behaviour',
  22865. 'split-dropdown-events'
  22866. ], _d),
  22867. toggleClass: 'tox-tbtn--enabled',
  22868. lazySink: sharedBackstage.getSink,
  22869. fetch: fetchChoices(getApi, spec, sharedBackstage.providers),
  22870. parts: { menu: part(false, spec.columns, spec.presets) },
  22871. components: [
  22872. SplitDropdown.parts().button(renderCommonStructure(spec.icon, spec.text, Option.none(), Option.some(displayChannel), Option.some([Toggling.config({
  22873. toggleClass: 'tox-tbtn--enabled',
  22874. toggleOnExecute: false
  22875. })]), sharedBackstage.providers)),
  22876. SplitDropdown.parts().arrow({
  22877. dom: {
  22878. tag: 'button',
  22879. classes: [
  22880. 'tox-tbtn',
  22881. 'tox-split-button__chevron'
  22882. ],
  22883. innerHtml: get$d('chevron-down', sharedBackstage.providers.icons)
  22884. },
  22885. buttonBehaviours: derive$1([
  22886. DisablingConfigs.splitButton(sharedBackstage.providers.isReadOnly),
  22887. receivingConfig()
  22888. ])
  22889. }),
  22890. SplitDropdown.parts()['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') })
  22891. ]
  22892. });
  22893. };
  22894. var getFormApi = function (input) {
  22895. return {
  22896. hide: function () {
  22897. return emit(input, sandboxClose());
  22898. },
  22899. getValue: function () {
  22900. return Representing.getValue(input);
  22901. }
  22902. };
  22903. };
  22904. var runOnExecute$1 = function (memInput, original) {
  22905. return run(internalToolbarButtonExecute, function (comp, se) {
  22906. var input = memInput.get(comp);
  22907. var formApi = getFormApi(input);
  22908. original.onAction(formApi, se.event().buttonApi());
  22909. });
  22910. };
  22911. var renderContextButton = function (memInput, button, extras) {
  22912. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22913. var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), {
  22914. type: 'button',
  22915. onAction: function () {
  22916. }
  22917. })));
  22918. return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22919. };
  22920. var renderContextToggleButton = function (memInput, button, extras) {
  22921. var _a = button.original, primary = _a.primary, rest = __rest(_a, ['primary']);
  22922. var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), {
  22923. type: 'togglebutton',
  22924. onAction: function () {
  22925. }
  22926. })));
  22927. return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute$1(memInput, button)]);
  22928. };
  22929. var generateOne$1 = function (memInput, button, providersBackstage) {
  22930. var extras = { backstage: { shared: { providers: providersBackstage } } };
  22931. if (button.type === 'contextformtogglebutton') {
  22932. return renderContextToggleButton(memInput, button, extras);
  22933. } else {
  22934. return renderContextButton(memInput, button, extras);
  22935. }
  22936. };
  22937. var generate$7 = function (memInput, buttons, providersBackstage) {
  22938. var mementos = map(buttons, function (button) {
  22939. return record(generateOne$1(memInput, button, providersBackstage));
  22940. });
  22941. var asSpecs = function () {
  22942. return map(mementos, function (mem) {
  22943. return mem.asSpec();
  22944. });
  22945. };
  22946. var findPrimary = function (compInSystem) {
  22947. return findMap(buttons, function (button, i) {
  22948. if (button.primary) {
  22949. return Option.from(mementos[i]).bind(function (mem) {
  22950. return mem.getOpt(compInSystem);
  22951. }).filter(not(Disabling.isDisabled));
  22952. } else {
  22953. return Option.none();
  22954. }
  22955. });
  22956. };
  22957. return {
  22958. asSpecs: asSpecs,
  22959. findPrimary: findPrimary
  22960. };
  22961. };
  22962. var buildInitGroups = function (ctx, providers) {
  22963. var inputAttributes = ctx.label.fold(function () {
  22964. return {};
  22965. }, function (label) {
  22966. return { 'aria-label': label };
  22967. });
  22968. var memInput = record(Input.sketch({
  22969. inputClasses: [
  22970. 'tox-toolbar-textfield',
  22971. 'tox-toolbar-nav-js'
  22972. ],
  22973. data: ctx.initValue(),
  22974. inputAttributes: inputAttributes,
  22975. selectOnFocus: true,
  22976. inputBehaviours: derive$1([Keying.config({
  22977. mode: 'special',
  22978. onEnter: function (input) {
  22979. return commands.findPrimary(input).map(function (primary) {
  22980. emitExecute(primary);
  22981. return true;
  22982. });
  22983. },
  22984. onLeft: function (comp, se) {
  22985. se.cut();
  22986. return Option.none();
  22987. },
  22988. onRight: function (comp, se) {
  22989. se.cut();
  22990. return Option.none();
  22991. }
  22992. })])
  22993. }));
  22994. var commands = generate$7(memInput, ctx.commands, providers);
  22995. return [
  22996. {
  22997. title: Option.none(),
  22998. items: [memInput.asSpec()]
  22999. },
  23000. {
  23001. title: Option.none(),
  23002. items: commands.asSpecs()
  23003. }
  23004. ];
  23005. };
  23006. var renderContextForm = function (toolbarType, ctx, providers) {
  23007. return renderToolbar({
  23008. type: toolbarType,
  23009. uid: generate$1('context-toolbar'),
  23010. initGroups: buildInitGroups(ctx, providers),
  23011. onEscape: Option.none,
  23012. cyclicKeying: true,
  23013. providers: providers
  23014. });
  23015. };
  23016. var ContextForm = {
  23017. renderContextForm: renderContextForm,
  23018. buildInitGroups: buildInitGroups
  23019. };
  23020. var getHorizontalBounds = function (contentAreaBox, viewportBounds) {
  23021. var x = Math.max(viewportBounds.x, contentAreaBox.x);
  23022. var contentBoxWidth = contentAreaBox.right - x;
  23023. var maxViewportWidth = viewportBounds.width - (x - viewportBounds.x);
  23024. var width = Math.min(contentBoxWidth, maxViewportWidth);
  23025. return {
  23026. x: x,
  23027. width: width
  23028. };
  23029. };
  23030. var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop) {
  23031. var container = Element.fromDom(editor.getContainer());
  23032. var header = descendant$1(container, '.tox-editor-header').getOr(container);
  23033. var headerBox = box(header);
  23034. var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom;
  23035. var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea;
  23036. if (editor.inline && isToolbarAbove) {
  23037. return {
  23038. y: Math.max(headerBox.bottom, viewportBounds.y),
  23039. bottom: viewportBounds.bottom
  23040. };
  23041. }
  23042. if (editor.inline && !isToolbarAbove) {
  23043. return {
  23044. y: viewportBounds.y,
  23045. bottom: Math.min(headerBox.y, viewportBounds.bottom)
  23046. };
  23047. }
  23048. var containerBounds = box(container);
  23049. if (isToolbarAbove) {
  23050. return {
  23051. y: Math.max(headerBox.bottom, viewportBounds.y),
  23052. bottom: Math.min(containerBounds.bottom, viewportBounds.bottom)
  23053. };
  23054. }
  23055. return {
  23056. y: Math.max(containerBounds.y, viewportBounds.y),
  23057. bottom: Math.min(headerBox.y, viewportBounds.bottom)
  23058. };
  23059. };
  23060. var getContextToolbarBounds = function (editor, sharedBackstage) {
  23061. var viewportBounds = getBounds(domGlobals.window);
  23062. var contentAreaBox = box(Element.fromDom(editor.getContentAreaContainer()));
  23063. var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor);
  23064. var _a = getHorizontalBounds(contentAreaBox, viewportBounds), x = _a.x, width = _a.width;
  23065. if (editor.inline && !toolbarOrMenubarEnabled) {
  23066. return bounds$1(x, viewportBounds.y, width, viewportBounds.height);
  23067. } else {
  23068. var isToolbarTop = sharedBackstage.header.isPositionedAtTop();
  23069. var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop), y = _b.y, bottom = _b.bottom;
  23070. return bounds$1(x, y, width, bottom - y);
  23071. }
  23072. };
  23073. var matchTargetWith = function (elem, candidates) {
  23074. var ctxs = filter(candidates, function (toolbarApi) {
  23075. return toolbarApi.predicate(elem.dom());
  23076. });
  23077. var _a = partition(ctxs, function (t) {
  23078. return t.type === 'contexttoolbar';
  23079. }), pass = _a.pass, fail = _a.fail;
  23080. return {
  23081. contextToolbars: pass,
  23082. contextForms: fail
  23083. };
  23084. };
  23085. var filterByPositionForStartNode = function (toolbars) {
  23086. if (toolbars.length <= 1) {
  23087. return toolbars;
  23088. } else {
  23089. var doesPositionExist = function (value) {
  23090. return exists(toolbars, function (t) {
  23091. return t.position === value;
  23092. });
  23093. };
  23094. var filterToolbarsByPosition = function (value) {
  23095. return filter(toolbars, function (t) {
  23096. return t.position === value;
  23097. });
  23098. };
  23099. var hasSelectionToolbars = doesPositionExist('selection');
  23100. var hasNodeToolbars = doesPositionExist('node');
  23101. if (hasSelectionToolbars || hasNodeToolbars) {
  23102. if (hasNodeToolbars && hasSelectionToolbars) {
  23103. var nodeToolbars = filterToolbarsByPosition('node');
  23104. var selectionToolbars = map(filterToolbarsByPosition('selection'), function (t) {
  23105. return __assign(__assign({}, t), { position: 'node' });
  23106. });
  23107. return nodeToolbars.concat(selectionToolbars);
  23108. } else {
  23109. return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node');
  23110. }
  23111. } else {
  23112. return filterToolbarsByPosition('line');
  23113. }
  23114. }
  23115. };
  23116. var filterByPositionForAncestorNode = function (toolbars) {
  23117. if (toolbars.length <= 1) {
  23118. return toolbars;
  23119. } else {
  23120. var findPosition_1 = function (value) {
  23121. return find(toolbars, function (t) {
  23122. return t.position === value;
  23123. });
  23124. };
  23125. var basePosition = findPosition_1('selection').orThunk(function () {
  23126. return findPosition_1('node');
  23127. }).orThunk(function () {
  23128. return findPosition_1('line');
  23129. }).map(function (t) {
  23130. return t.position;
  23131. });
  23132. return basePosition.fold(function () {
  23133. return [];
  23134. }, function (pos) {
  23135. return filter(toolbars, function (t) {
  23136. return t.position === pos;
  23137. });
  23138. });
  23139. }
  23140. };
  23141. var matchStartNode = function (elem, nodeCandidates, editorCandidates) {
  23142. var nodeMatches = matchTargetWith(elem, nodeCandidates);
  23143. if (nodeMatches.contextForms.length > 0) {
  23144. return Option.some({
  23145. elem: elem,
  23146. toolbars: [nodeMatches.contextForms[0]]
  23147. });
  23148. } else {
  23149. var editorMatches = matchTargetWith(elem, editorCandidates);
  23150. if (editorMatches.contextForms.length > 0) {
  23151. return Option.some({
  23152. elem: elem,
  23153. toolbars: [editorMatches.contextForms[0]]
  23154. });
  23155. } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) {
  23156. var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars));
  23157. return Option.some({
  23158. elem: elem,
  23159. toolbars: toolbars
  23160. });
  23161. } else {
  23162. return Option.none();
  23163. }
  23164. }
  23165. };
  23166. var matchAncestor = function (isRoot, startNode, scopes) {
  23167. if (isRoot(startNode)) {
  23168. return Option.none();
  23169. } else {
  23170. return ancestor(startNode, function (ancestorElem) {
  23171. var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms;
  23172. var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars);
  23173. return toolbars.length > 0 ? Option.some({
  23174. elem: ancestorElem,
  23175. toolbars: toolbars
  23176. }) : Option.none();
  23177. }, isRoot);
  23178. }
  23179. };
  23180. var lookup$1 = function (scopes, editor) {
  23181. var rootElem = Element.fromDom(editor.getBody());
  23182. var isRoot = function (elem) {
  23183. return eq$1(elem, rootElem);
  23184. };
  23185. var isOutsideRoot = function (startNode) {
  23186. return !isRoot(startNode) && !contains$2(rootElem, startNode);
  23187. };
  23188. var startNode = Element.fromDom(editor.selection.getNode());
  23189. if (isOutsideRoot(startNode)) {
  23190. return Option.none();
  23191. }
  23192. return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () {
  23193. return matchAncestor(isRoot, startNode, scopes);
  23194. });
  23195. };
  23196. var categorise = function (contextToolbars, navigate) {
  23197. var forms = {};
  23198. var inNodeScope = [];
  23199. var inEditorScope = [];
  23200. var formNavigators = {};
  23201. var lookupTable = {};
  23202. var registerForm = function (key, toolbarApi) {
  23203. var contextForm = getOrDie(createContextForm(toolbarApi));
  23204. forms[key] = contextForm;
  23205. contextForm.launch.map(function (launch) {
  23206. formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarApi.launch), {
  23207. type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button',
  23208. onAction: function () {
  23209. navigate(contextForm);
  23210. }
  23211. });
  23212. });
  23213. if (contextForm.scope === 'editor') {
  23214. inEditorScope.push(contextForm);
  23215. } else {
  23216. inNodeScope.push(contextForm);
  23217. }
  23218. lookupTable[key] = contextForm;
  23219. };
  23220. var registerToolbar = function (key, toolbarApi) {
  23221. createContextToolbar(toolbarApi).each(function (contextToolbar) {
  23222. if (toolbarApi.scope === 'editor') {
  23223. inEditorScope.push(contextToolbar);
  23224. } else {
  23225. inNodeScope.push(contextToolbar);
  23226. }
  23227. lookupTable[key] = contextToolbar;
  23228. });
  23229. };
  23230. var keys$1 = keys(contextToolbars);
  23231. each(keys$1, function (key) {
  23232. var toolbarApi = contextToolbars[key];
  23233. if (toolbarApi.type === 'contextform') {
  23234. registerForm(key, toolbarApi);
  23235. } else if (toolbarApi.type === 'contexttoolbar') {
  23236. registerToolbar(key, toolbarApi);
  23237. }
  23238. });
  23239. return {
  23240. forms: forms,
  23241. inNodeScope: inNodeScope,
  23242. inEditorScope: inEditorScope,
  23243. lookupTable: lookupTable,
  23244. formNavigators: formNavigators
  23245. };
  23246. };
  23247. var forwardSlideEvent = generate$1('forward-slide');
  23248. var backSlideEvent = generate$1('backward-slide');
  23249. var changeSlideEvent = generate$1('change-slide-event');
  23250. var resizingClass = 'tox-pop--resizing';
  23251. var renderContextToolbar = function (spec) {
  23252. var stack = Cell([]);
  23253. return InlineView.sketch({
  23254. dom: {
  23255. tag: 'div',
  23256. classes: ['tox-pop']
  23257. },
  23258. fireDismissalEventInstead: { event: 'doNotDismissYet' },
  23259. onShow: function (comp) {
  23260. stack.set([]);
  23261. InlineView.getContent(comp).each(function (c) {
  23262. remove$6(c.element(), 'visibility');
  23263. });
  23264. remove$4(comp.element(), resizingClass);
  23265. remove$6(comp.element(), 'width');
  23266. },
  23267. inlineBehaviours: derive$1([
  23268. config('context-toolbar-events', [
  23269. runOnSource(transitionend(), function (comp, _se) {
  23270. remove$4(comp.element(), resizingClass);
  23271. remove$6(comp.element(), 'width');
  23272. }),
  23273. run(changeSlideEvent, function (comp, se) {
  23274. remove$6(comp.element(), 'width');
  23275. var currentWidth = get$7(comp.element());
  23276. InlineView.setContent(comp, se.event().contents());
  23277. add$2(comp.element(), resizingClass);
  23278. var newWidth = get$7(comp.element());
  23279. set$2(comp.element(), 'width', currentWidth + 'px');
  23280. InlineView.getContent(comp).each(function (newContents) {
  23281. se.event().focus().bind(function (f) {
  23282. focus$1(f);
  23283. return search(comp.element());
  23284. }).orThunk(function () {
  23285. Keying.focusIn(newContents);
  23286. return active();
  23287. });
  23288. });
  23289. global$2.setTimeout(function () {
  23290. set$2(comp.element(), 'width', newWidth + 'px');
  23291. }, 0);
  23292. }),
  23293. run(forwardSlideEvent, function (comp, se) {
  23294. InlineView.getContent(comp).each(function (oldContents) {
  23295. stack.set(stack.get().concat([{
  23296. bar: oldContents,
  23297. focus: active()
  23298. }]));
  23299. });
  23300. emitWith(comp, changeSlideEvent, {
  23301. contents: se.event().forwardContents(),
  23302. focus: Option.none()
  23303. });
  23304. }),
  23305. run(backSlideEvent, function (comp, _se) {
  23306. last(stack.get()).each(function (last) {
  23307. stack.set(stack.get().slice(0, stack.get().length - 1));
  23308. emitWith(comp, changeSlideEvent, {
  23309. contents: premade$1(last.bar),
  23310. focus: last.focus
  23311. });
  23312. });
  23313. })
  23314. ]),
  23315. Keying.config({
  23316. mode: 'special',
  23317. onEscape: function (comp) {
  23318. return last(stack.get()).fold(function () {
  23319. return spec.onEscape();
  23320. }, function (_) {
  23321. emit(comp, backSlideEvent);
  23322. return Option.some(true);
  23323. });
  23324. }
  23325. })
  23326. ]),
  23327. lazySink: function () {
  23328. return Result.value(spec.sink);
  23329. }
  23330. });
  23331. };
  23332. var generateSelectItems = function (_editor, backstage, spec) {
  23333. var generateItem = function (rawItem, response, disabled, value) {
  23334. var translatedText = backstage.shared.providers.translate(rawItem.title);
  23335. if (rawItem.type === 'separator') {
  23336. return Option.some({
  23337. type: 'separator',
  23338. text: translatedText
  23339. });
  23340. } else if (rawItem.type === 'submenu') {
  23341. var items = bind(rawItem.getStyleItems(), function (si) {
  23342. return validate(si, response, value);
  23343. });
  23344. if (response === 0 && items.length <= 0) {
  23345. return Option.none();
  23346. } else {
  23347. return Option.some({
  23348. type: 'nestedmenuitem',
  23349. text: translatedText,
  23350. disabled: items.length <= 0,
  23351. getSubmenuItems: function () {
  23352. return bind(rawItem.getStyleItems(), function (si) {
  23353. return validate(si, response, value);
  23354. });
  23355. }
  23356. });
  23357. }
  23358. } else {
  23359. return Option.some(__assign({
  23360. type: 'togglemenuitem',
  23361. text: translatedText,
  23362. icon: rawItem.icon,
  23363. active: rawItem.isSelected(value),
  23364. disabled: disabled,
  23365. onAction: spec.onAction(rawItem)
  23366. }, rawItem.getStylePreview().fold(function () {
  23367. return {};
  23368. }, function (preview) {
  23369. return { meta: { style: preview } };
  23370. })));
  23371. }
  23372. };
  23373. var validate = function (item, response, value) {
  23374. var invalid = item.type === 'formatter' && spec.isInvalid(item);
  23375. if (response === 0) {
  23376. return invalid ? [] : generateItem(item, response, false, value).toArray();
  23377. } else {
  23378. return generateItem(item, response, invalid, value).toArray();
  23379. }
  23380. };
  23381. var validateItems = function (preItems) {
  23382. var value = spec.getCurrentValue();
  23383. var response = spec.shouldHide ? 0 : 1;
  23384. return bind(preItems, function (item) {
  23385. return validate(item, response, value);
  23386. });
  23387. };
  23388. var getFetch = function (backstage, getStyleItems) {
  23389. return function (callback) {
  23390. var preItems = getStyleItems();
  23391. var items = validateItems(preItems);
  23392. var menu = build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false);
  23393. callback(menu);
  23394. };
  23395. };
  23396. return {
  23397. validateItems: validateItems,
  23398. getFetch: getFetch
  23399. };
  23400. };
  23401. var createMenuItems = function (editor, backstage, spec) {
  23402. var dataset = spec.dataset;
  23403. var getStyleItems = dataset.type === 'basic' ? function () {
  23404. return map(dataset.data, function (d) {
  23405. return processBasic(d, spec.isSelectedFor, spec.getPreviewFor);
  23406. });
  23407. } : dataset.getData;
  23408. return {
  23409. items: generateSelectItems(editor, backstage, spec),
  23410. getStyleItems: getStyleItems
  23411. };
  23412. };
  23413. var createSelectButton = function (editor, backstage, spec) {
  23414. var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems;
  23415. var getApi = function (comp) {
  23416. return {
  23417. getComponent: function () {
  23418. return comp;
  23419. }
  23420. };
  23421. };
  23422. var onSetup = function (api) {
  23423. spec.setInitialValue.each(function (f) {
  23424. return f(api.getComponent());
  23425. });
  23426. return spec.nodeChangeHandler.map(function (f) {
  23427. var handler = f(api.getComponent());
  23428. editor.on('NodeChange', handler);
  23429. return function () {
  23430. editor.off('NodeChange', handler);
  23431. };
  23432. }).getOr(noop);
  23433. };
  23434. return renderCommonDropdown({
  23435. text: spec.icon.isSome() ? Option.none() : Option.some(''),
  23436. icon: spec.icon,
  23437. tooltip: Option.from(spec.tooltip),
  23438. role: Option.none(),
  23439. fetch: items.getFetch(backstage, getStyleItems),
  23440. onSetup: onSetup,
  23441. getApi: getApi,
  23442. columns: 1,
  23443. presets: 'normal',
  23444. classes: spec.icon.isSome() ? [] : ['bespoke'],
  23445. dropdownBehaviours: []
  23446. }, 'tox-tbtn', backstage.shared);
  23447. };
  23448. var process = function (rawFormats) {
  23449. return map(rawFormats, function (item) {
  23450. var title = item, format = item;
  23451. var values = item.split('=');
  23452. if (values.length > 1) {
  23453. title = values[0];
  23454. format = values[1];
  23455. }
  23456. return {
  23457. title: title,
  23458. format: format
  23459. };
  23460. });
  23461. };
  23462. var buildBasicStaticDataset = function (data) {
  23463. return {
  23464. type: 'basic',
  23465. data: data
  23466. };
  23467. };
  23468. var Delimiter;
  23469. (function (Delimiter) {
  23470. Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon';
  23471. Delimiter[Delimiter['Space'] = 1] = 'Space';
  23472. }(Delimiter || (Delimiter = {})));
  23473. var split = function (rawFormats, delimiter) {
  23474. if (delimiter === Delimiter.SemiColon) {
  23475. return rawFormats.replace(/;$/, '').split(';');
  23476. } else {
  23477. return rawFormats.split(' ');
  23478. }
  23479. };
  23480. var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) {
  23481. var rawFormats = get(editor.settings, settingName).getOr(defaults);
  23482. var data = process(split(rawFormats, delimiter));
  23483. return {
  23484. type: 'basic',
  23485. data: data
  23486. };
  23487. };
  23488. var alignMenuItems = [
  23489. {
  23490. title: 'Left',
  23491. icon: 'align-left',
  23492. format: 'alignleft',
  23493. command: 'JustifyLeft'
  23494. },
  23495. {
  23496. title: 'Center',
  23497. icon: 'align-center',
  23498. format: 'aligncenter',
  23499. command: 'JustifyCenter'
  23500. },
  23501. {
  23502. title: 'Right',
  23503. icon: 'align-right',
  23504. format: 'alignright',
  23505. command: 'JustifyRight'
  23506. },
  23507. {
  23508. title: 'Justify',
  23509. icon: 'align-justify',
  23510. format: 'alignjustify',
  23511. command: 'JustifyFull'
  23512. }
  23513. ];
  23514. var getSpec = function (editor) {
  23515. var getMatchingValue = function () {
  23516. return find(alignMenuItems, function (item) {
  23517. return editor.formatter.match(item.format);
  23518. });
  23519. };
  23520. var isSelectedFor = function (format) {
  23521. return function () {
  23522. return editor.formatter.match(format);
  23523. };
  23524. };
  23525. var getPreviewFor = function (_format) {
  23526. return function () {
  23527. return Option.none();
  23528. };
  23529. };
  23530. var updateSelectMenuIcon = function (comp) {
  23531. var match = getMatchingValue();
  23532. var alignment = match.fold(function () {
  23533. return 'left';
  23534. }, function (item) {
  23535. return item.title.toLowerCase();
  23536. });
  23537. emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment });
  23538. };
  23539. var nodeChangeHandler = Option.some(function (comp) {
  23540. return function () {
  23541. return updateSelectMenuIcon(comp);
  23542. };
  23543. });
  23544. var setInitialValue = Option.some(function (comp) {
  23545. return updateSelectMenuIcon(comp);
  23546. });
  23547. var dataset = buildBasicStaticDataset(alignMenuItems);
  23548. var onAction = function (rawItem) {
  23549. return function () {
  23550. return find(alignMenuItems, function (item) {
  23551. return item.format === rawItem.format;
  23552. }).each(function (item) {
  23553. return editor.execCommand(item.command);
  23554. });
  23555. };
  23556. };
  23557. return {
  23558. tooltip: 'Align',
  23559. icon: Option.some('align-left'),
  23560. isSelectedFor: isSelectedFor,
  23561. getCurrentValue: constant(Option.none()),
  23562. getPreviewFor: getPreviewFor,
  23563. onAction: onAction,
  23564. setInitialValue: setInitialValue,
  23565. nodeChangeHandler: nodeChangeHandler,
  23566. dataset: dataset,
  23567. shouldHide: false,
  23568. isInvalid: function (item) {
  23569. return !editor.formatter.canApply(item.format);
  23570. }
  23571. };
  23572. };
  23573. var createAlignSelect = function (editor, backstage) {
  23574. return createSelectButton(editor, backstage, getSpec(editor));
  23575. };
  23576. var alignSelectMenu = function (editor, backstage) {
  23577. var menuItems = createMenuItems(editor, backstage, getSpec(editor));
  23578. editor.ui.registry.addNestedMenuItem('align', {
  23579. text: backstage.shared.providers.translate('Align'),
  23580. getSubmenuItems: function () {
  23581. return menuItems.items.validateItems(menuItems.getStyleItems());
  23582. }
  23583. });
  23584. };
  23585. 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';
  23586. var systemStackFonts = [
  23587. '-apple-system',
  23588. 'Segoe UI',
  23589. 'Roboto',
  23590. 'Helvetica Neue',
  23591. 'sans-serif'
  23592. ];
  23593. var splitFonts = function (fontFamily) {
  23594. var fonts = fontFamily.split(/\s*,\s*/);
  23595. return map(fonts, function (font) {
  23596. return font.replace(/^['"]+|['"]+$/g, '');
  23597. });
  23598. };
  23599. var isSystemFontStack = function (fontFamily) {
  23600. var matchesSystemStack = function () {
  23601. var fonts = splitFonts(fontFamily.toLowerCase());
  23602. return forall(systemStackFonts, function (font) {
  23603. return fonts.indexOf(font.toLowerCase()) > -1;
  23604. });
  23605. };
  23606. return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack();
  23607. };
  23608. var getSpec$1 = function (editor) {
  23609. var getMatchingValue = function () {
  23610. var getFirstFont = function (fontFamily) {
  23611. return fontFamily ? splitFonts(fontFamily)[0] : '';
  23612. };
  23613. var fontFamily = editor.queryCommandValue('FontName');
  23614. var items = dataset.data;
  23615. var font = fontFamily ? fontFamily.toLowerCase() : '';
  23616. var matchOpt = find(items, function (item) {
  23617. var format = item.format;
  23618. return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase();
  23619. }).orThunk(function () {
  23620. if (isSystemFontStack(font)) {
  23621. return Option.from({
  23622. title: 'System Font',
  23623. format: font
  23624. });
  23625. } else {
  23626. return Option.none();
  23627. }
  23628. });
  23629. return {
  23630. matchOpt: matchOpt,
  23631. font: fontFamily
  23632. };
  23633. };
  23634. var isSelectedFor = function (item) {
  23635. return function (valueOpt) {
  23636. return valueOpt.exists(function (value) {
  23637. return value.format === item;
  23638. });
  23639. };
  23640. };
  23641. var getCurrentValue = function () {
  23642. var matchOpt = getMatchingValue().matchOpt;
  23643. return matchOpt;
  23644. };
  23645. var getPreviewFor = function (item) {
  23646. return function () {
  23647. return Option.some({
  23648. tag: 'div',
  23649. styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {}
  23650. });
  23651. };
  23652. };
  23653. var onAction = function (rawItem) {
  23654. return function () {
  23655. editor.undoManager.transact(function () {
  23656. editor.focus();
  23657. editor.execCommand('FontName', false, rawItem.format);
  23658. });
  23659. };
  23660. };
  23661. var updateSelectMenuText = function (comp) {
  23662. var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font;
  23663. var text = matchOpt.fold(function () {
  23664. return font;
  23665. }, function (item) {
  23666. return item.title;
  23667. });
  23668. emitWith(comp, updateMenuText, { text: text });
  23669. };
  23670. var nodeChangeHandler = Option.some(function (comp) {
  23671. return function () {
  23672. return updateSelectMenuText(comp);
  23673. };
  23674. });
  23675. var setInitialValue = Option.some(function (comp) {
  23676. return updateSelectMenuText(comp);
  23677. });
  23678. var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon);
  23679. return {
  23680. tooltip: 'Fonts',
  23681. icon: Option.none(),
  23682. isSelectedFor: isSelectedFor,
  23683. getCurrentValue: getCurrentValue,
  23684. getPreviewFor: getPreviewFor,
  23685. onAction: onAction,
  23686. setInitialValue: setInitialValue,
  23687. nodeChangeHandler: nodeChangeHandler,
  23688. dataset: dataset,
  23689. shouldHide: false,
  23690. isInvalid: function () {
  23691. return false;
  23692. }
  23693. };
  23694. };
  23695. var createFontSelect = function (editor, backstage) {
  23696. return createSelectButton(editor, backstage, getSpec$1(editor));
  23697. };
  23698. var fontSelectMenu = function (editor, backstage) {
  23699. var menuItems = createMenuItems(editor, backstage, getSpec$1(editor));
  23700. editor.ui.registry.addNestedMenuItem('fontformats', {
  23701. text: backstage.shared.providers.translate('Fonts'),
  23702. getSubmenuItems: function () {
  23703. return menuItems.items.validateItems(menuItems.getStyleItems());
  23704. }
  23705. });
  23706. };
  23707. var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  23708. var legacyFontSizes = {
  23709. '8pt': '1',
  23710. '10pt': '2',
  23711. '12pt': '3',
  23712. '14pt': '4',
  23713. '18pt': '5',
  23714. '24pt': '6',
  23715. '36pt': '7'
  23716. };
  23717. var round$1 = function (number, precision) {
  23718. var factor = Math.pow(10, precision);
  23719. return Math.round(number * factor) / factor;
  23720. };
  23721. var toPt = function (fontSize, precision) {
  23722. if (/[0-9.]+px$/.test(fontSize)) {
  23723. return round$1(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt';
  23724. }
  23725. return fontSize;
  23726. };
  23727. var toLegacy = function (fontSize) {
  23728. return get(legacyFontSizes, fontSize).getOr('');
  23729. };
  23730. var getSpec$2 = function (editor) {
  23731. var getMatchingValue = function () {
  23732. var matchOpt = Option.none();
  23733. var items = dataset.data;
  23734. var fontSize = editor.queryCommandValue('FontSize');
  23735. if (fontSize) {
  23736. var _loop_1 = function (precision) {
  23737. var pt = toPt(fontSize, precision);
  23738. var legacy = toLegacy(pt);
  23739. matchOpt = find(items, function (item) {
  23740. return item.format === fontSize || item.format === pt || item.format === legacy;
  23741. });
  23742. };
  23743. for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) {
  23744. _loop_1(precision);
  23745. }
  23746. }
  23747. return {
  23748. matchOpt: matchOpt,
  23749. size: fontSize
  23750. };
  23751. };
  23752. var isSelectedFor = function (item) {
  23753. return function (valueOpt) {
  23754. return valueOpt.exists(function (value) {
  23755. return value.format === item;
  23756. });
  23757. };
  23758. };
  23759. var getCurrentValue = function () {
  23760. var matchOpt = getMatchingValue().matchOpt;
  23761. return matchOpt;
  23762. };
  23763. var getPreviewFor = constant(constant(Option.none()));
  23764. var onAction = function (rawItem) {
  23765. return function () {
  23766. editor.undoManager.transact(function () {
  23767. editor.focus();
  23768. editor.execCommand('FontSize', false, rawItem.format);
  23769. });
  23770. };
  23771. };
  23772. var updateSelectMenuText = function (comp) {
  23773. var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size;
  23774. var text = matchOpt.fold(function () {
  23775. return size;
  23776. }, function (match) {
  23777. return match.title;
  23778. });
  23779. emitWith(comp, updateMenuText, { text: text });
  23780. };
  23781. var nodeChangeHandler = Option.some(function (comp) {
  23782. return function () {
  23783. return updateSelectMenuText(comp);
  23784. };
  23785. });
  23786. var setInitialValue = Option.some(function (comp) {
  23787. return updateSelectMenuText(comp);
  23788. });
  23789. var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space);
  23790. return {
  23791. tooltip: 'Font sizes',
  23792. icon: Option.none(),
  23793. isSelectedFor: isSelectedFor,
  23794. getPreviewFor: getPreviewFor,
  23795. getCurrentValue: getCurrentValue,
  23796. onAction: onAction,
  23797. setInitialValue: setInitialValue,
  23798. nodeChangeHandler: nodeChangeHandler,
  23799. dataset: dataset,
  23800. shouldHide: false,
  23801. isInvalid: function () {
  23802. return false;
  23803. }
  23804. };
  23805. };
  23806. var createFontsizeSelect = function (editor, backstage) {
  23807. return createSelectButton(editor, backstage, getSpec$2(editor));
  23808. };
  23809. var fontsizeSelectMenu = function (editor, backstage) {
  23810. var menuItems = createMenuItems(editor, backstage, getSpec$2(editor));
  23811. editor.ui.registry.addNestedMenuItem('fontsizes', {
  23812. text: 'Font sizes',
  23813. getSubmenuItems: function () {
  23814. return menuItems.items.validateItems(menuItems.getStyleItems());
  23815. }
  23816. });
  23817. };
  23818. var findNearest = function (editor, getStyles, parents) {
  23819. var styles = getStyles();
  23820. return findMap(parents, function (parent) {
  23821. return find(styles, function (fmt) {
  23822. return editor.formatter.matchNode(parent, fmt.format);
  23823. });
  23824. }).orThunk(function () {
  23825. if (editor.formatter.match('p')) {
  23826. return Option.some({
  23827. title: 'Paragraph',
  23828. format: 'p'
  23829. });
  23830. }
  23831. return Option.none();
  23832. });
  23833. };
  23834. var getCurrentSelectionParents = function (editor) {
  23835. var currentNode = editor.selection.getStart(true) || editor.getBody();
  23836. return editor.dom.getParents(currentNode, function () {
  23837. return true;
  23838. }, editor.getBody());
  23839. };
  23840. var onSetupFormatToggle = function (editor, name) {
  23841. return function (api) {
  23842. var unbindCell = Cell(Option.none());
  23843. var init = function () {
  23844. api.setActive(editor.formatter.match(name));
  23845. var unbind = editor.formatter.formatChanged(name, api.setActive).unbind;
  23846. unbindCell.set(Option.some(unbind));
  23847. };
  23848. editor.initialized ? init() : editor.on('init', init);
  23849. return function () {
  23850. return unbindCell.get().each(function (unbind) {
  23851. return unbind();
  23852. });
  23853. };
  23854. };
  23855. };
  23856. var onActionToggleFormat = function (editor) {
  23857. return function (rawItem) {
  23858. return function () {
  23859. editor.undoManager.transact(function () {
  23860. editor.focus();
  23861. editor.execCommand('mceToggleFormat', false, rawItem.format);
  23862. });
  23863. };
  23864. };
  23865. };
  23866. var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre';
  23867. var getSpec$3 = function (editor) {
  23868. var getMatchingValue = function (nodeChangeEvent) {
  23869. return findNearest(editor, function () {
  23870. return dataset.data;
  23871. }, nodeChangeEvent);
  23872. };
  23873. var isSelectedFor = function (format) {
  23874. return function () {
  23875. return editor.formatter.match(format);
  23876. };
  23877. };
  23878. var getPreviewFor = function (format) {
  23879. return function () {
  23880. var fmt = editor.formatter.get(format);
  23881. return Option.some({
  23882. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23883. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  23884. });
  23885. };
  23886. };
  23887. var updateSelectMenuText = function (parents, comp) {
  23888. var detectedFormat = getMatchingValue(parents);
  23889. var text = detectedFormat.fold(function () {
  23890. return 'Paragraph';
  23891. }, function (fmt) {
  23892. return fmt.title;
  23893. });
  23894. emitWith(comp, updateMenuText, { text: text });
  23895. };
  23896. var nodeChangeHandler = Option.some(function (comp) {
  23897. return function (e) {
  23898. return updateSelectMenuText(e.parents, comp);
  23899. };
  23900. });
  23901. var setInitialValue = Option.some(function (comp) {
  23902. var parents = getCurrentSelectionParents(editor);
  23903. updateSelectMenuText(parents, comp);
  23904. });
  23905. var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon);
  23906. return {
  23907. tooltip: 'Blocks',
  23908. icon: Option.none(),
  23909. isSelectedFor: isSelectedFor,
  23910. getCurrentValue: constant(Option.none()),
  23911. getPreviewFor: getPreviewFor,
  23912. onAction: onActionToggleFormat(editor),
  23913. setInitialValue: setInitialValue,
  23914. nodeChangeHandler: nodeChangeHandler,
  23915. dataset: dataset,
  23916. shouldHide: false,
  23917. isInvalid: function (item) {
  23918. return !editor.formatter.canApply(item.format);
  23919. }
  23920. };
  23921. };
  23922. var createFormatSelect = function (editor, backstage) {
  23923. return createSelectButton(editor, backstage, getSpec$3(editor));
  23924. };
  23925. var formatSelectMenu = function (editor, backstage) {
  23926. var menuItems = createMenuItems(editor, backstage, getSpec$3(editor));
  23927. editor.ui.registry.addNestedMenuItem('blockformats', {
  23928. text: 'Blocks',
  23929. getSubmenuItems: function () {
  23930. return menuItems.items.validateItems(menuItems.getStyleItems());
  23931. }
  23932. });
  23933. };
  23934. var getSpec$4 = function (editor, dataset) {
  23935. var isSelectedFor = function (format) {
  23936. return function () {
  23937. return editor.formatter.match(format);
  23938. };
  23939. };
  23940. var getPreviewFor = function (format) {
  23941. return function () {
  23942. var fmt = editor.formatter.get(format);
  23943. return fmt !== undefined ? Option.some({
  23944. tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div',
  23945. styles: editor.dom.parseStyle(editor.formatter.getCssText(format))
  23946. }) : Option.none();
  23947. };
  23948. };
  23949. var updateSelectMenuText = function (parents, comp) {
  23950. var getFormatItems = function (fmt) {
  23951. var subs = fmt.items;
  23952. return subs !== undefined && subs.length > 0 ? bind(subs, getFormatItems) : [{
  23953. title: fmt.title,
  23954. format: fmt.format
  23955. }];
  23956. };
  23957. var flattenedItems = bind(getStyleFormats(editor), getFormatItems);
  23958. var detectedFormat = findNearest(editor, function () {
  23959. return flattenedItems;
  23960. }, parents);
  23961. var text = detectedFormat.fold(function () {
  23962. return 'Paragraph';
  23963. }, function (fmt) {
  23964. return fmt.title;
  23965. });
  23966. emitWith(comp, updateMenuText, { text: text });
  23967. };
  23968. var nodeChangeHandler = Option.some(function (comp) {
  23969. return function (e) {
  23970. return updateSelectMenuText(e.parents, comp);
  23971. };
  23972. });
  23973. var setInitialValue = Option.some(function (comp) {
  23974. var parents = getCurrentSelectionParents(editor);
  23975. updateSelectMenuText(parents, comp);
  23976. });
  23977. return {
  23978. tooltip: 'Formats',
  23979. icon: Option.none(),
  23980. isSelectedFor: isSelectedFor,
  23981. getCurrentValue: constant(Option.none()),
  23982. getPreviewFor: getPreviewFor,
  23983. onAction: onActionToggleFormat(editor),
  23984. setInitialValue: setInitialValue,
  23985. nodeChangeHandler: nodeChangeHandler,
  23986. shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'),
  23987. isInvalid: function (item) {
  23988. return !editor.formatter.canApply(item.format);
  23989. },
  23990. dataset: dataset
  23991. };
  23992. };
  23993. var createStyleSelect = function (editor, backstage) {
  23994. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23995. return createSelectButton(editor, backstage, getSpec$4(editor, dataset));
  23996. };
  23997. var styleSelectMenu = function (editor, backstage) {
  23998. var dataset = __assign({ type: 'advanced' }, backstage.styleselect);
  23999. var menuItems = createMenuItems(editor, backstage, getSpec$4(editor, dataset));
  24000. editor.ui.registry.addNestedMenuItem('formats', {
  24001. text: 'Formats',
  24002. getSubmenuItems: function () {
  24003. return menuItems.items.validateItems(menuItems.getStyleItems());
  24004. }
  24005. });
  24006. };
  24007. var defaultToolbar = [
  24008. {
  24009. name: 'history',
  24010. items: [
  24011. 'undo',
  24012. 'redo'
  24013. ]
  24014. },
  24015. {
  24016. name: 'styles',
  24017. items: ['styleselect']
  24018. },
  24019. {
  24020. name: 'formatting',
  24021. items: [
  24022. 'bold',
  24023. 'italic'
  24024. ]
  24025. },
  24026. {
  24027. name: 'alignment',
  24028. items: [
  24029. 'alignleft',
  24030. 'aligncenter',
  24031. 'alignright',
  24032. 'alignjustify'
  24033. ]
  24034. },
  24035. {
  24036. name: 'indentation',
  24037. items: [
  24038. 'outdent',
  24039. 'indent'
  24040. ]
  24041. },
  24042. {
  24043. name: 'permanent pen',
  24044. items: ['permanentpen']
  24045. },
  24046. {
  24047. name: 'comments',
  24048. items: ['addcomment']
  24049. }
  24050. ];
  24051. var renderFromBridge = function (bridgeBuilder, render) {
  24052. return function (spec, extras, editor) {
  24053. var internal = bridgeBuilder(spec).mapError(function (errInfo) {
  24054. return formatError(errInfo);
  24055. }).getOrDie();
  24056. return render(internal, extras, editor);
  24057. };
  24058. };
  24059. var types = {
  24060. button: renderFromBridge(createToolbarButton, function (s, extras) {
  24061. return renderToolbarButton(s, extras.backstage.shared.providers);
  24062. }),
  24063. togglebutton: renderFromBridge(createToggleButton, function (s, extras) {
  24064. return renderToolbarToggleButton(s, extras.backstage.shared.providers);
  24065. }),
  24066. menubutton: renderFromBridge(createMenuButton, function (s, extras) {
  24067. return renderMenuButton(s, 'tox-tbtn', extras.backstage, Option.none());
  24068. }),
  24069. splitbutton: renderFromBridge(createSplitButton, function (s, extras) {
  24070. return renderSplitButton(s, extras.backstage.shared);
  24071. }),
  24072. grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) {
  24073. var _a;
  24074. var buttons = editor.ui.registry.getAll().buttons;
  24075. var identify = function (toolbar) {
  24076. return identifyButtons(editor, {
  24077. buttons: buttons,
  24078. toolbar: toolbar,
  24079. allowToolbarGroups: false
  24080. }, extras, Option.none());
  24081. };
  24082. var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a);
  24083. switch (getToolbarMode(editor)) {
  24084. case ToolbarMode.floating:
  24085. return renderFloatingToolbarButton(s, extras.backstage, identify, attributes);
  24086. default:
  24087. throw new Error('Toolbar groups are only supported when using floating toolbar mode');
  24088. }
  24089. }),
  24090. styleSelectButton: function (editor, extras) {
  24091. return createStyleSelect(editor, extras.backstage);
  24092. },
  24093. fontsizeSelectButton: function (editor, extras) {
  24094. return createFontsizeSelect(editor, extras.backstage);
  24095. },
  24096. fontSelectButton: function (editor, extras) {
  24097. return createFontSelect(editor, extras.backstage);
  24098. },
  24099. formatButton: function (editor, extras) {
  24100. return createFormatSelect(editor, extras.backstage);
  24101. },
  24102. alignMenuButton: function (editor, extras) {
  24103. return createAlignSelect(editor, extras.backstage);
  24104. }
  24105. };
  24106. var extractFrom = function (spec, extras, editor) {
  24107. return get(types, spec.type).fold(function () {
  24108. domGlobals.console.error('skipping button defined by', spec);
  24109. return Option.none();
  24110. }, function (render) {
  24111. return Option.some(render(spec, extras, editor));
  24112. });
  24113. };
  24114. var bespokeButtons = {
  24115. styleselect: types.styleSelectButton,
  24116. fontsizeselect: types.fontsizeSelectButton,
  24117. fontselect: types.fontSelectButton,
  24118. formatselect: types.formatButton,
  24119. align: types.alignMenuButton
  24120. };
  24121. var removeUnusedDefaults = function (buttons) {
  24122. var filteredItemGroups = map(defaultToolbar, function (group) {
  24123. var items = filter(group.items, function (subItem) {
  24124. return has(buttons, subItem) || has(bespokeButtons, subItem);
  24125. });
  24126. return {
  24127. name: group.name,
  24128. items: items
  24129. };
  24130. });
  24131. return filter(filteredItemGroups, function (group) {
  24132. return group.items.length > 0;
  24133. });
  24134. };
  24135. var convertStringToolbar = function (strToolbar) {
  24136. var groupsStrings = strToolbar.split('|');
  24137. return map(groupsStrings, function (g) {
  24138. return { items: g.trim().split(' ') };
  24139. });
  24140. };
  24141. var isToolbarGroupSettingArray = function (toolbar) {
  24142. return isArrayOf(toolbar, function (t) {
  24143. return has(t, 'name') && has(t, 'items');
  24144. });
  24145. };
  24146. var createToolbar = function (toolbarConfig) {
  24147. var toolbar = toolbarConfig.toolbar;
  24148. var buttons = toolbarConfig.buttons;
  24149. if (toolbar === false) {
  24150. return [];
  24151. } else if (toolbar === undefined || toolbar === true) {
  24152. return removeUnusedDefaults(buttons);
  24153. } else if (isString(toolbar)) {
  24154. return convertStringToolbar(toolbar);
  24155. } else if (isToolbarGroupSettingArray(toolbar)) {
  24156. return toolbar;
  24157. } else {
  24158. domGlobals.console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]');
  24159. return [];
  24160. }
  24161. };
  24162. var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) {
  24163. return get(buttons, toolbarItem.toLowerCase()).orThunk(function () {
  24164. return prefixes.bind(function (ps) {
  24165. return findMap(ps, function (prefix) {
  24166. return get(buttons, prefix + toolbarItem.toLowerCase());
  24167. });
  24168. });
  24169. }).fold(function () {
  24170. return get(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) {
  24171. return r(editor, extras);
  24172. }).orThunk(function () {
  24173. return Option.none();
  24174. });
  24175. }, function (spec) {
  24176. if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) {
  24177. domGlobals.console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.');
  24178. return Option.none();
  24179. } else {
  24180. return extractFrom(spec, extras, editor);
  24181. }
  24182. });
  24183. };
  24184. var identifyButtons = function (editor, toolbarConfig, extras, prefixes) {
  24185. var toolbarGroups = createToolbar(toolbarConfig);
  24186. var groups = map(toolbarGroups, function (group) {
  24187. var items = bind(group.items, function (toolbarItem) {
  24188. return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray();
  24189. });
  24190. return {
  24191. title: Option.from(editor.translate(group.name)),
  24192. items: items
  24193. };
  24194. });
  24195. return filter(groups, function (group) {
  24196. return group.items.length > 0;
  24197. });
  24198. };
  24199. var bubbleSize = 12;
  24200. var bubbleAlignments$1 = {
  24201. valignCentre: [],
  24202. alignCentre: [],
  24203. alignLeft: ['tox-pop--align-left'],
  24204. alignRight: ['tox-pop--align-right'],
  24205. right: ['tox-pop--right'],
  24206. left: ['tox-pop--left'],
  24207. bottom: ['tox-pop--bottom'],
  24208. top: ['tox-pop--top']
  24209. };
  24210. var anchorOverrides = {
  24211. maxHeightFunction: expandable(),
  24212. maxWidthFunction: expandable$1()
  24213. };
  24214. var desktopAnchorSpecLayouts = {
  24215. onLtr: function () {
  24216. return [
  24217. north$1,
  24218. south$1,
  24219. northeast$1,
  24220. southeast$1,
  24221. northwest$1,
  24222. southwest$1,
  24223. north$3,
  24224. south$3,
  24225. northeast$3,
  24226. southeast$3,
  24227. northwest$3,
  24228. southwest$3
  24229. ];
  24230. },
  24231. onRtl: function () {
  24232. return [
  24233. north$1,
  24234. south$1,
  24235. northwest$1,
  24236. southwest$1,
  24237. northeast$1,
  24238. southeast$1,
  24239. north$3,
  24240. south$3,
  24241. northwest$3,
  24242. southwest$3,
  24243. northeast$3,
  24244. southeast$3
  24245. ];
  24246. }
  24247. };
  24248. var mobileAnchorSpecLayouts = {
  24249. onLtr: function () {
  24250. return [
  24251. south$1,
  24252. southeast$1,
  24253. southwest$1,
  24254. northeast$1,
  24255. northwest$1,
  24256. north$1,
  24257. north$3,
  24258. south$3,
  24259. northeast$3,
  24260. southeast$3,
  24261. northwest$3,
  24262. southwest$3
  24263. ];
  24264. },
  24265. onRtl: function () {
  24266. return [
  24267. south$1,
  24268. southwest$1,
  24269. southeast$1,
  24270. northwest$1,
  24271. northeast$1,
  24272. north$1,
  24273. north$3,
  24274. south$3,
  24275. northwest$3,
  24276. southwest$3,
  24277. northeast$3,
  24278. southeast$3
  24279. ];
  24280. }
  24281. };
  24282. var getAnchorLayout = function (position, isTouch) {
  24283. if (position === 'line') {
  24284. return {
  24285. bubble: nu$8(bubbleSize, 0, bubbleAlignments$1),
  24286. layouts: {
  24287. onLtr: function () {
  24288. return [east$1];
  24289. },
  24290. onRtl: function () {
  24291. return [west$1];
  24292. }
  24293. },
  24294. overrides: anchorOverrides
  24295. };
  24296. } else {
  24297. return {
  24298. bubble: nu$8(0, bubbleSize, bubbleAlignments$1),
  24299. layouts: isTouch ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts,
  24300. overrides: anchorOverrides
  24301. };
  24302. }
  24303. };
  24304. var register$4 = function (editor, registryContextToolbars, sink, extras) {
  24305. var isTouch = detect$3().deviceType.isTouch;
  24306. var contextbar = build$1(renderContextToolbar({
  24307. sink: sink,
  24308. onEscape: function () {
  24309. editor.focus();
  24310. return Option.some(true);
  24311. }
  24312. }));
  24313. var getBounds = function () {
  24314. return getContextToolbarBounds(editor, extras.backstage.shared);
  24315. };
  24316. var isRangeOverlapping = function (aTop, aBottom, bTop, bBottom) {
  24317. return Math.max(aTop, bTop) <= Math.min(aBottom, bBottom);
  24318. };
  24319. var getLastElementVerticalBound = function () {
  24320. var nodeBounds = lastElement.get().map(function (ele) {
  24321. return ele.getBoundingClientRect();
  24322. }).getOrThunk(function () {
  24323. return editor.selection.getRng().getBoundingClientRect();
  24324. });
  24325. var diffTop = editor.inline ? get$8().top() : absolute$1(Element.fromDom(editor.getBody())).y;
  24326. return {
  24327. y: nodeBounds.top + diffTop,
  24328. bottom: nodeBounds.bottom + diffTop
  24329. };
  24330. };
  24331. var shouldContextToolbarHide = function () {
  24332. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24333. return true;
  24334. }
  24335. var lastElementBounds = getLastElementVerticalBound();
  24336. var contextToolbarBounds = getBounds();
  24337. return !isRangeOverlapping(lastElementBounds.y, lastElementBounds.bottom, contextToolbarBounds.y, contextToolbarBounds.bottom);
  24338. };
  24339. var forceHide = function () {
  24340. InlineView.hide(contextbar);
  24341. };
  24342. var hideOrRepositionIfNecessary = function () {
  24343. lastAnchor.get().each(function (anchor) {
  24344. var contextBarEle = contextbar.element();
  24345. remove$6(contextBarEle, 'display');
  24346. if (shouldContextToolbarHide()) {
  24347. set$2(contextBarEle, 'display', 'none');
  24348. } else {
  24349. Positioning.positionWithinBounds(sink, anchor, contextbar, Option.some(getBounds()));
  24350. }
  24351. });
  24352. };
  24353. var lastAnchor = Cell(Option.none());
  24354. var lastElement = Cell(Option.none());
  24355. var timer = Cell(null);
  24356. var wrapInPopDialog = function (toolbarSpec) {
  24357. return {
  24358. dom: {
  24359. tag: 'div',
  24360. classes: ['tox-pop__dialog']
  24361. },
  24362. components: [toolbarSpec],
  24363. behaviours: derive$1([
  24364. Keying.config({ mode: 'acyclic' }),
  24365. config('pop-dialog-wrap-events', [
  24366. runOnAttached(function (comp) {
  24367. editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () {
  24368. return Keying.focusIn(comp);
  24369. });
  24370. }),
  24371. runOnDetached(function (_comp) {
  24372. editor.shortcuts.remove('ctrl+F9');
  24373. })
  24374. ])
  24375. ])
  24376. };
  24377. };
  24378. var getScopes = cached(function () {
  24379. return categorise(registryContextToolbars, function (toolbarApi) {
  24380. var alloySpec = buildToolbar([toolbarApi]);
  24381. emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) });
  24382. });
  24383. });
  24384. var buildContextToolbarGroups = function (allButtons, ctx) {
  24385. return identifyButtons(editor, {
  24386. buttons: allButtons,
  24387. toolbar: ctx.items,
  24388. allowToolbarGroups: false
  24389. }, extras, Option.some(['form:']));
  24390. };
  24391. var buildContextMenuGroups = function (ctx, providers) {
  24392. return ContextForm.buildInitGroups(ctx, providers);
  24393. };
  24394. var buildToolbar = function (toolbars) {
  24395. var buttons = editor.ui.registry.getAll().buttons;
  24396. var scopes = getScopes();
  24397. var allButtons = __assign(__assign({}, buttons), scopes.formNavigators);
  24398. var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default;
  24399. var initGroups = flatten(map(toolbars, function (ctx) {
  24400. return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextMenuGroups(ctx, extras.backstage.shared.providers);
  24401. }));
  24402. return renderToolbar({
  24403. type: toolbarType,
  24404. uid: generate$1('context-toolbar'),
  24405. initGroups: initGroups,
  24406. onEscape: Option.none,
  24407. cyclicKeying: true,
  24408. providers: extras.backstage.shared.providers
  24409. });
  24410. };
  24411. editor.on(showContextToolbarEvent, function (e) {
  24412. var scopes = getScopes();
  24413. get(scopes.lookupTable, e.toolbarKey).each(function (ctx) {
  24414. launchContext([ctx], e.target === editor ? Option.none() : Option.some(e));
  24415. InlineView.getContent(contextbar).each(Keying.focusIn);
  24416. });
  24417. });
  24418. var getAnchor = function (position, element) {
  24419. var anchorage = position === 'node' ? extras.backstage.shared.anchors.node(element) : extras.backstage.shared.anchors.cursor();
  24420. return deepMerge(anchorage, getAnchorLayout(position, isTouch()));
  24421. };
  24422. var launchContext = function (toolbarApi, elem) {
  24423. clearTimer();
  24424. if (isTouch() && extras.backstage.isContextMenuOpen()) {
  24425. return;
  24426. }
  24427. var toolbarSpec = buildToolbar(toolbarApi);
  24428. var sElem = elem.map(Element.fromDom);
  24429. var anchor = getAnchor(toolbarApi[0].position, sElem);
  24430. lastAnchor.set(Option.some(anchor));
  24431. lastElement.set(elem);
  24432. var contextBarEle = contextbar.element();
  24433. remove$6(contextBarEle, 'display');
  24434. InlineView.showWithinBounds(contextbar, anchor, wrapInPopDialog(toolbarSpec), function () {
  24435. return Option.some(getBounds());
  24436. });
  24437. if (shouldContextToolbarHide()) {
  24438. set$2(contextBarEle, 'display', 'none');
  24439. }
  24440. };
  24441. var launchContextToolbar = function () {
  24442. if (!editor.hasFocus()) {
  24443. return;
  24444. }
  24445. var scopes = getScopes();
  24446. lookup$1(scopes, editor).fold(function () {
  24447. lastAnchor.set(Option.none());
  24448. InlineView.hide(contextbar);
  24449. }, function (info) {
  24450. launchContext(info.toolbars, Option.some(info.elem.dom()));
  24451. });
  24452. };
  24453. var clearTimer = function () {
  24454. var current = timer.get();
  24455. if (current !== null) {
  24456. global$2.clearTimeout(current);
  24457. timer.set(null);
  24458. }
  24459. };
  24460. var resetTimer = function (t) {
  24461. clearTimer();
  24462. timer.set(t);
  24463. };
  24464. editor.on('init', function () {
  24465. editor.on(hideContextToolbarEvent, forceHide);
  24466. editor.on('ScrollContent ScrollWindow longpress', hideOrRepositionIfNecessary);
  24467. editor.on('click keyup focus SetContent ObjectResized ResizeEditor', function () {
  24468. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24469. });
  24470. editor.on('focusout', function (_e) {
  24471. global$2.setEditorTimeout(editor, function () {
  24472. if (search(sink.element()).isNone() && search(contextbar.element()).isNone()) {
  24473. lastAnchor.set(Option.none());
  24474. InlineView.hide(contextbar);
  24475. }
  24476. }, 0);
  24477. });
  24478. editor.on('SwitchMode', function () {
  24479. if (editor.mode.isReadOnly()) {
  24480. lastAnchor.set(Option.none());
  24481. InlineView.hide(contextbar);
  24482. }
  24483. });
  24484. editor.on('NodeChange', function (_e) {
  24485. search(contextbar.element()).fold(function () {
  24486. resetTimer(global$2.setEditorTimeout(editor, launchContextToolbar, 0));
  24487. }, function (_) {
  24488. });
  24489. });
  24490. });
  24491. };
  24492. var setup$3 = function (editor, mothership, uiMothership) {
  24493. var broadcastEvent = function (name, evt) {
  24494. each([
  24495. mothership,
  24496. uiMothership
  24497. ], function (ship) {
  24498. ship.broadcastEvent(name, evt);
  24499. });
  24500. };
  24501. var broadcastOn = function (channel, message) {
  24502. each([
  24503. mothership,
  24504. uiMothership
  24505. ], function (ship) {
  24506. ship.broadcastOn([channel], message);
  24507. });
  24508. };
  24509. var fireDismissPopups = function (evt) {
  24510. return broadcastOn(dismissPopups(), { target: evt.target() });
  24511. };
  24512. var onTouchstart = bind$3(Element.fromDom(domGlobals.document), 'touchstart', fireDismissPopups);
  24513. var onTouchmove = bind$3(Element.fromDom(domGlobals.document), 'touchmove', function (evt) {
  24514. return broadcastEvent(documentTouchmove(), evt);
  24515. });
  24516. var onTouchend = bind$3(Element.fromDom(domGlobals.document), 'touchend', function (evt) {
  24517. return broadcastEvent(documentTouchend(), evt);
  24518. });
  24519. var onMousedown = bind$3(Element.fromDom(domGlobals.document), 'mousedown', fireDismissPopups);
  24520. var onMouseup = bind$3(Element.fromDom(domGlobals.document), 'mouseup', function (evt) {
  24521. if (evt.raw().button === 0) {
  24522. broadcastOn(mouseReleased(), { target: evt.target() });
  24523. }
  24524. });
  24525. var onContentClick = function (raw) {
  24526. return broadcastOn(dismissPopups(), { target: Element.fromDom(raw.target) });
  24527. };
  24528. var onContentMouseup = function (raw) {
  24529. if (raw.button === 0) {
  24530. broadcastOn(mouseReleased(), { target: Element.fromDom(raw.target) });
  24531. }
  24532. };
  24533. var onWindowScroll = function (evt) {
  24534. return broadcastEvent(windowScroll(), fromRawEvent$1(evt));
  24535. };
  24536. var onWindowResize = function (evt) {
  24537. broadcastOn(repositionPopups(), {});
  24538. broadcastEvent(windowResize(), fromRawEvent$1(evt));
  24539. };
  24540. var onEditorResize = function () {
  24541. return broadcastOn(repositionPopups(), {});
  24542. };
  24543. editor.on('PostRender', function () {
  24544. editor.on('click', onContentClick);
  24545. editor.on('tap', onContentClick);
  24546. editor.on('mouseup', onContentMouseup);
  24547. editor.on('ScrollWindow', onWindowScroll);
  24548. editor.on('ResizeWindow', onWindowResize);
  24549. editor.on('ResizeEditor', onEditorResize);
  24550. });
  24551. editor.on('remove', function () {
  24552. editor.off('click', onContentClick);
  24553. editor.off('tap', onContentClick);
  24554. editor.off('mouseup', onContentMouseup);
  24555. editor.off('ScrollWindow', onWindowScroll);
  24556. editor.off('ResizeWindow', onWindowResize);
  24557. editor.off('ResizeEditor', onEditorResize);
  24558. onMousedown.unbind();
  24559. onTouchstart.unbind();
  24560. onTouchmove.unbind();
  24561. onTouchend.unbind();
  24562. onMouseup.unbind();
  24563. });
  24564. editor.on('detach', function () {
  24565. detachSystem(mothership);
  24566. detachSystem(uiMothership);
  24567. mothership.destroy();
  24568. uiMothership.destroy();
  24569. });
  24570. };
  24571. var parts$d = AlloyParts;
  24572. var partType$1 = PartType;
  24573. var schema$r = constant([
  24574. defaulted$1('shell', false),
  24575. strict$1('makeItem'),
  24576. defaulted$1('setupItem', noop),
  24577. SketchBehaviours.field('listBehaviours', [Replacing])
  24578. ]);
  24579. var customListDetail = function () {
  24580. return { behaviours: derive$1([Replacing.config({})]) };
  24581. };
  24582. var itemsPart = optional({
  24583. name: 'items',
  24584. overrides: customListDetail
  24585. });
  24586. var parts$e = constant([itemsPart]);
  24587. var name$2 = constant('CustomList');
  24588. var factory$f = function (detail, components, _spec, _external) {
  24589. var setItems = function (list, items) {
  24590. getListContainer(list).fold(function () {
  24591. domGlobals.console.error('Custom List was defined to not be a shell, but no item container was specified in components');
  24592. throw new Error('Custom List was defined to not be a shell, but no item container was specified in components');
  24593. }, function (container) {
  24594. var itemComps = Replacing.contents(container);
  24595. var numListsRequired = items.length;
  24596. var numListsToAdd = numListsRequired - itemComps.length;
  24597. var itemsToAdd = numListsToAdd > 0 ? range(numListsToAdd, function () {
  24598. return detail.makeItem();
  24599. }) : [];
  24600. var itemsToRemove = itemComps.slice(numListsRequired);
  24601. each(itemsToRemove, function (item) {
  24602. return Replacing.remove(container, item);
  24603. });
  24604. each(itemsToAdd, function (item) {
  24605. return Replacing.append(container, item);
  24606. });
  24607. var builtLists = Replacing.contents(container);
  24608. each(builtLists, function (item, i) {
  24609. detail.setupItem(list, item, items[i], i);
  24610. });
  24611. });
  24612. };
  24613. var extra = detail.shell ? {
  24614. behaviours: [Replacing.config({})],
  24615. components: []
  24616. } : {
  24617. behaviours: [],
  24618. components: components
  24619. };
  24620. var getListContainer = function (component) {
  24621. return detail.shell ? Option.some(component) : getPart(component, detail, 'items');
  24622. };
  24623. return {
  24624. uid: detail.uid,
  24625. dom: detail.dom,
  24626. components: extra.components,
  24627. behaviours: augment(detail.listBehaviours, extra.behaviours),
  24628. apis: { setItems: setItems }
  24629. };
  24630. };
  24631. var CustomList = composite$1({
  24632. name: name$2(),
  24633. configFields: schema$r(),
  24634. partFields: parts$e(),
  24635. factory: factory$f,
  24636. apis: {
  24637. setItems: function (apis, list, items) {
  24638. apis.setItems(list, items);
  24639. }
  24640. }
  24641. });
  24642. var getOffsetParent = function (element) {
  24643. var isFixed = getRaw(element, 'position').is('fixed');
  24644. var offsetParent$1 = isFixed ? Option.none() : offsetParent(element);
  24645. return offsetParent$1.orThunk(function () {
  24646. var marker = Element.fromTag('span');
  24647. return parent(element).bind(function (parent) {
  24648. append(parent, marker);
  24649. var offsetParent$1 = offsetParent(marker);
  24650. remove(marker);
  24651. return offsetParent$1;
  24652. });
  24653. });
  24654. };
  24655. var getOrigin = function (element) {
  24656. return getOffsetParent(element).map(absolute).getOrThunk(function () {
  24657. return Position(0, 0);
  24658. });
  24659. };
  24660. var morphAdt = Adt.generate([
  24661. { static: [] },
  24662. { absolute: ['positionCss'] },
  24663. { fixed: ['positionCss'] }
  24664. ]);
  24665. var appear = function (component, contextualInfo) {
  24666. var elem = component.element();
  24667. add$2(elem, contextualInfo.transitionClass);
  24668. remove$4(elem, contextualInfo.fadeOutClass);
  24669. add$2(elem, contextualInfo.fadeInClass);
  24670. contextualInfo.onShow(component);
  24671. };
  24672. var disappear = function (component, contextualInfo) {
  24673. var elem = component.element();
  24674. add$2(elem, contextualInfo.transitionClass);
  24675. remove$4(elem, contextualInfo.fadeInClass);
  24676. add$2(elem, contextualInfo.fadeOutClass);
  24677. contextualInfo.onHide(component);
  24678. };
  24679. var isPartiallyVisible = function (box, viewport) {
  24680. return box.y < viewport.bottom && box.bottom > viewport.y;
  24681. };
  24682. var isTopCompletelyVisible = function (box, viewport) {
  24683. return box.y >= viewport.y;
  24684. };
  24685. var isBottomCompletelyVisible = function (box, viewport) {
  24686. return box.bottom <= viewport.bottom;
  24687. };
  24688. var isVisibleForModes = function (modes, box, viewport) {
  24689. return forall(modes, function (mode) {
  24690. switch (mode) {
  24691. case 'bottom':
  24692. return isBottomCompletelyVisible(box, viewport);
  24693. case 'top':
  24694. return isTopCompletelyVisible(box, viewport);
  24695. }
  24696. });
  24697. };
  24698. var getPrior = function (elem, state) {
  24699. return state.getInitialPosition().map(function (pos) {
  24700. return bounds$1(pos.bounds.x, pos.bounds.y, get$7(elem), get$6(elem));
  24701. });
  24702. };
  24703. var storePrior = function (elem, box, state) {
  24704. state.setInitialPosition(Option.some({
  24705. style: getAllRaw(elem),
  24706. position: get$4(elem, 'position') || 'static',
  24707. bounds: box
  24708. }));
  24709. };
  24710. var revertToOriginal = function (elem, box$1, state) {
  24711. return state.getInitialPosition().bind(function (position) {
  24712. state.setInitialPosition(Option.none());
  24713. switch (position.position) {
  24714. case 'static':
  24715. return Option.some(morphAdt.static());
  24716. case 'absolute':
  24717. var offsetBox_1 = getOffsetParent(elem).map(box).getOrThunk(function () {
  24718. return box(body());
  24719. });
  24720. return Option.some(morphAdt.absolute(NuPositionCss('absolute', get(position.style, 'left').map(function (_left) {
  24721. return box$1.x - offsetBox_1.x;
  24722. }), get(position.style, 'top').map(function (_top) {
  24723. return box$1.y - offsetBox_1.y;
  24724. }), get(position.style, 'right').map(function (_right) {
  24725. return offsetBox_1.right - box$1.right;
  24726. }), get(position.style, 'bottom').map(function (_bottom) {
  24727. return offsetBox_1.bottom - box$1.bottom;
  24728. }))));
  24729. default:
  24730. return Option.none();
  24731. }
  24732. });
  24733. };
  24734. var morphToOriginal = function (elem, viewport, state) {
  24735. return getPrior(elem, state).filter(function (box) {
  24736. return isVisibleForModes(state.getModes(), box, viewport);
  24737. }).bind(function (box) {
  24738. return revertToOriginal(elem, box, state);
  24739. });
  24740. };
  24741. var morphToFixed = function (elem, viewport, state) {
  24742. var box$1 = box(elem);
  24743. if (!isVisibleForModes(state.getModes(), box$1, viewport)) {
  24744. storePrior(elem, box$1, state);
  24745. var winBox = win();
  24746. var left = box$1.x - winBox.x;
  24747. var top = viewport.y - winBox.y;
  24748. var bottom = winBox.bottom - viewport.bottom;
  24749. var isTop = box$1.y <= viewport.y;
  24750. return Option.some(morphAdt.fixed(NuPositionCss('fixed', Option.some(left), isTop ? Option.some(top) : Option.none(), Option.none(), !isTop ? Option.some(bottom) : Option.none())));
  24751. } else {
  24752. return Option.none();
  24753. }
  24754. };
  24755. var getMorph = function (component, viewport, state) {
  24756. var elem = component.element();
  24757. var isDocked = getRaw(elem, 'position').is('fixed');
  24758. return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state);
  24759. };
  24760. var getMorphToOriginal = function (component, state) {
  24761. var elem = component.element();
  24762. return getPrior(elem, state).bind(function (box) {
  24763. return revertToOriginal(elem, box, state);
  24764. });
  24765. };
  24766. var morphToStatic = function (component, config) {
  24767. each([
  24768. 'left',
  24769. 'right',
  24770. 'top',
  24771. 'bottom',
  24772. 'position'
  24773. ], function (prop) {
  24774. return remove$6(component.element(), prop);
  24775. });
  24776. config.onUndocked(component);
  24777. };
  24778. var morphToCoord = function (component, config, position) {
  24779. applyPositionCss(component.element(), position);
  24780. var method = position.position() === 'fixed' ? config.onDocked : config.onUndocked;
  24781. method(component);
  24782. };
  24783. var updateVisibility = function (component, config, state, viewport, morphToDocked) {
  24784. if (morphToDocked === void 0) {
  24785. morphToDocked = false;
  24786. }
  24787. config.contextual.each(function (contextInfo) {
  24788. contextInfo.lazyContext(component).each(function (box) {
  24789. var isVisible = isPartiallyVisible(box, viewport);
  24790. if (isVisible !== state.isVisible()) {
  24791. state.setVisible(isVisible);
  24792. if (morphToDocked && !isVisible) {
  24793. add$3(component.element(), [contextInfo.fadeOutClass]);
  24794. contextInfo.onHide(component);
  24795. } else {
  24796. var method = isVisible ? appear : disappear;
  24797. method(component, contextInfo);
  24798. }
  24799. }
  24800. });
  24801. });
  24802. };
  24803. var refreshInternal = function (component, config, state) {
  24804. var viewport = config.lazyViewport(component);
  24805. var isDocked = state.isDocked();
  24806. if (isDocked) {
  24807. updateVisibility(component, config, state, viewport);
  24808. }
  24809. getMorph(component, viewport, state).each(function (morph) {
  24810. state.setDocked(!isDocked);
  24811. morph.fold(function () {
  24812. return morphToStatic(component, config);
  24813. }, function (position) {
  24814. return morphToCoord(component, config, position);
  24815. }, function (position) {
  24816. updateVisibility(component, config, state, viewport, true);
  24817. morphToCoord(component, config, position);
  24818. });
  24819. });
  24820. };
  24821. var resetInternal = function (component, config, state) {
  24822. var elem = component.element();
  24823. state.setDocked(false);
  24824. getMorphToOriginal(component, state).each(function (morph) {
  24825. morph.fold(function () {
  24826. return morphToStatic(component, config);
  24827. }, function (position) {
  24828. return morphToCoord(component, config, position);
  24829. }, noop);
  24830. });
  24831. state.setVisible(true);
  24832. config.contextual.each(function (contextInfo) {
  24833. remove$5(elem, [
  24834. contextInfo.fadeInClass,
  24835. contextInfo.fadeOutClass,
  24836. contextInfo.transitionClass
  24837. ]);
  24838. contextInfo.onShow(component);
  24839. });
  24840. refresh$4(component, config, state);
  24841. };
  24842. var refresh$4 = function (component, config, state) {
  24843. if (component.getSystem().isConnected()) {
  24844. refreshInternal(component, config, state);
  24845. }
  24846. };
  24847. var reset = function (component, config, state) {
  24848. if (state.isDocked()) {
  24849. resetInternal(component, config, state);
  24850. }
  24851. };
  24852. var isDocked = function (component, config, state) {
  24853. return state.isDocked();
  24854. };
  24855. var setModes = function (component, config, state, modes) {
  24856. return state.setModes(modes);
  24857. };
  24858. var getModes = function (component, config, state) {
  24859. return state.getModes();
  24860. };
  24861. var DockingApis = /*#__PURE__*/Object.freeze({
  24862. __proto__: null,
  24863. refresh: refresh$4,
  24864. reset: reset,
  24865. isDocked: isDocked,
  24866. getModes: getModes,
  24867. setModes: setModes
  24868. });
  24869. var events$f = function (dockInfo, dockState) {
  24870. return derive([
  24871. runOnSource(transitionend(), function (component, simulatedEvent) {
  24872. dockInfo.contextual.each(function (contextInfo) {
  24873. if (has$2(component.element(), contextInfo.transitionClass)) {
  24874. remove$5(component.element(), [
  24875. contextInfo.transitionClass,
  24876. contextInfo.fadeInClass
  24877. ]);
  24878. var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden;
  24879. notify(component);
  24880. }
  24881. simulatedEvent.stop();
  24882. });
  24883. }),
  24884. run(windowScroll(), function (component, _) {
  24885. refresh$4(component, dockInfo, dockState);
  24886. }),
  24887. run(windowResize(), function (component, _) {
  24888. reset(component, dockInfo, dockState);
  24889. })
  24890. ]);
  24891. };
  24892. var ActiveDocking = /*#__PURE__*/Object.freeze({
  24893. __proto__: null,
  24894. events: events$f
  24895. });
  24896. var DockingSchema = [
  24897. optionObjOf('contextual', [
  24898. strictString('fadeInClass'),
  24899. strictString('fadeOutClass'),
  24900. strictString('transitionClass'),
  24901. strictFunction('lazyContext'),
  24902. onHandler('onShow'),
  24903. onHandler('onShown'),
  24904. onHandler('onHide'),
  24905. onHandler('onHidden')
  24906. ]),
  24907. defaultedFunction('lazyViewport', win),
  24908. defaultedArrayOf('modes', [
  24909. 'top',
  24910. 'bottom'
  24911. ], string),
  24912. onHandler('onDocked'),
  24913. onHandler('onUndocked')
  24914. ];
  24915. var init$b = function (spec) {
  24916. var docked = Cell(false);
  24917. var visible = Cell(true);
  24918. var initialBounds = Cell(Option.none());
  24919. var modes = Cell(spec.modes);
  24920. var readState = function () {
  24921. return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(',');
  24922. };
  24923. return nu$5({
  24924. isDocked: docked.get,
  24925. setDocked: docked.set,
  24926. getInitialPosition: initialBounds.get,
  24927. setInitialPosition: initialBounds.set,
  24928. isVisible: visible.get,
  24929. setVisible: visible.set,
  24930. getModes: modes.get,
  24931. setModes: modes.set,
  24932. readState: readState
  24933. });
  24934. };
  24935. var DockingState = /*#__PURE__*/Object.freeze({
  24936. __proto__: null,
  24937. init: init$b
  24938. });
  24939. var Docking = create$1({
  24940. fields: DockingSchema,
  24941. name: 'docking',
  24942. active: ActiveDocking,
  24943. apis: DockingApis,
  24944. state: DockingState
  24945. });
  24946. var visibility = {
  24947. fadeInClass: 'tox-editor-dock-fadein',
  24948. fadeOutClass: 'tox-editor-dock-fadeout',
  24949. transitionClass: 'tox-editor-dock-transition'
  24950. };
  24951. var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on';
  24952. var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off';
  24953. var scrollFromBehindHeader = function (e, containerHeader) {
  24954. var doc = owner(containerHeader);
  24955. var viewHeight = doc.dom().defaultView.innerHeight;
  24956. var scrollPos = get$8(doc);
  24957. var markerElement = Element.fromDom(e.elm);
  24958. var markerPos = absolute$1(markerElement);
  24959. var markerHeight = get$6(markerElement);
  24960. var markerTop = markerPos.y;
  24961. var markerBottom = markerTop + markerHeight;
  24962. var editorHeaderPos = absolute(containerHeader);
  24963. var editorHeaderHeight = get$6(containerHeader);
  24964. var editorHeaderTop = editorHeaderPos.top();
  24965. var editorHeaderBottom = editorHeaderTop + editorHeaderHeight;
  24966. var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top()) < 2;
  24967. var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top() + viewHeight)) < 2;
  24968. if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) {
  24969. to(scrollPos.left(), markerTop - editorHeaderHeight, doc);
  24970. } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) {
  24971. var y = markerTop - viewHeight + markerHeight + editorHeaderHeight;
  24972. to(scrollPos.left(), y, doc);
  24973. }
  24974. };
  24975. var isDockedMode = function (header, mode) {
  24976. return contains(Docking.getModes(header), mode);
  24977. };
  24978. var updateIframeContentFlow = function (header) {
  24979. var getOccupiedHeight = function (elm) {
  24980. return getOuter$1(elm) + (parseInt(get$4(elm, 'margin-top'), 10) || 0) + (parseInt(get$4(elm, 'margin-bottom'), 10) || 0);
  24981. };
  24982. var elm = header.element();
  24983. parent(elm).each(function (parentElem) {
  24984. var padding = 'padding-' + Docking.getModes(header)[0];
  24985. if (Docking.isDocked(header)) {
  24986. var parentWidth = get$7(parentElem);
  24987. set$2(elm, 'width', parentWidth + 'px');
  24988. set$2(parentElem, padding, getOccupiedHeight(elm) + 'px');
  24989. } else {
  24990. remove$6(elm, 'width');
  24991. remove$6(parentElem, padding);
  24992. }
  24993. });
  24994. };
  24995. var updateSinkVisibility = function (sinkElem, visible) {
  24996. if (visible) {
  24997. remove$4(sinkElem, visibility.fadeOutClass);
  24998. add$3(sinkElem, [
  24999. visibility.transitionClass,
  25000. visibility.fadeInClass
  25001. ]);
  25002. } else {
  25003. remove$4(sinkElem, visibility.fadeInClass);
  25004. add$3(sinkElem, [
  25005. visibility.fadeOutClass,
  25006. visibility.transitionClass
  25007. ]);
  25008. }
  25009. };
  25010. var updateEditorClasses = function (editor, docked) {
  25011. var editorContainer = Element.fromDom(editor.getContainer());
  25012. if (docked) {
  25013. add$2(editorContainer, editorStickyOnClass);
  25014. remove$4(editorContainer, editorStickyOffClass);
  25015. } else {
  25016. add$2(editorContainer, editorStickyOffClass);
  25017. remove$4(editorContainer, editorStickyOnClass);
  25018. }
  25019. };
  25020. var restoreFocus = function (headerElem, focusedElem) {
  25021. var ownerDoc = owner(focusedElem);
  25022. active(ownerDoc).filter(function (activeElm) {
  25023. return !eq$1(focusedElem, activeElm);
  25024. }).filter(function (activeElm) {
  25025. return eq$1(activeElm, Element.fromDom(ownerDoc.dom().body)) || contains$2(headerElem, activeElm);
  25026. }).each(function () {
  25027. return focus$1(focusedElem);
  25028. });
  25029. };
  25030. var findFocusedElem = function (rootElm, lazySink) {
  25031. return search(rootElm).orThunk(function () {
  25032. return lazySink().toOption().bind(function (sink) {
  25033. return search(sink.element());
  25034. });
  25035. });
  25036. };
  25037. var setup$4 = function (editor, sharedBackstage, lazyHeader) {
  25038. if (!editor.inline) {
  25039. if (!sharedBackstage.header.isPositionedAtTop()) {
  25040. editor.on('ResizeEditor', function () {
  25041. lazyHeader().each(Docking.reset);
  25042. });
  25043. }
  25044. editor.on('ResizeWindow ResizeEditor', function () {
  25045. lazyHeader().each(updateIframeContentFlow);
  25046. });
  25047. editor.on('SkinLoaded', function () {
  25048. lazyHeader().each(function (comp) {
  25049. Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp);
  25050. });
  25051. });
  25052. editor.on('FullscreenStateChanged', function () {
  25053. lazyHeader().each(Docking.reset);
  25054. });
  25055. }
  25056. editor.on('AfterScrollIntoView', function (e) {
  25057. lazyHeader().each(function (header) {
  25058. Docking.refresh(header);
  25059. var headerElem = header.element();
  25060. if (isVisible(headerElem)) {
  25061. scrollFromBehindHeader(e, headerElem);
  25062. }
  25063. });
  25064. });
  25065. editor.on('PostRender', function () {
  25066. updateEditorClasses(editor, false);
  25067. });
  25068. };
  25069. var isDocked$1 = function (lazyHeader) {
  25070. return lazyHeader().map(Docking.isDocked).getOr(false);
  25071. };
  25072. var getIframeBehaviours = function () {
  25073. var _a;
  25074. return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })];
  25075. };
  25076. var getBehaviours$2 = function (editor, sharedBackstage) {
  25077. var focusedElm = Cell(Option.none());
  25078. var lazySink = sharedBackstage.getSink;
  25079. var runOnSinkElement = function (f) {
  25080. lazySink().each(function (sink) {
  25081. return f(sink.element());
  25082. });
  25083. };
  25084. var onDockingSwitch = function (comp) {
  25085. if (!editor.inline) {
  25086. updateIframeContentFlow(comp);
  25087. }
  25088. updateEditorClasses(editor, Docking.isDocked(comp));
  25089. comp.getSystem().broadcastOn([repositionPopups()], {});
  25090. lazySink().each(function (sink) {
  25091. return sink.getSystem().broadcastOn([repositionPopups()], {});
  25092. });
  25093. };
  25094. var additionalBehaviours = editor.inline ? [] : getIframeBehaviours();
  25095. return __spreadArrays([
  25096. Focusing.config({}),
  25097. Docking.config({
  25098. contextual: __assign({
  25099. lazyContext: function (comp) {
  25100. var headerHeight = getOuter$1(comp.element());
  25101. var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer();
  25102. var box$1 = box(Element.fromDom(container));
  25103. var boxHeight = box$1.height - headerHeight;
  25104. var topBound = box$1.y + (isDockedMode(comp, 'top') ? 0 : headerHeight);
  25105. return Option.some(bounds$1(box$1.x, topBound, box$1.width, boxHeight));
  25106. },
  25107. onShow: function () {
  25108. runOnSinkElement(function (elem) {
  25109. return updateSinkVisibility(elem, true);
  25110. });
  25111. },
  25112. onShown: function (comp) {
  25113. runOnSinkElement(function (elem) {
  25114. return remove$5(elem, [
  25115. visibility.transitionClass,
  25116. visibility.fadeInClass
  25117. ]);
  25118. });
  25119. focusedElm.get().each(function (elem) {
  25120. restoreFocus(comp.element(), elem);
  25121. focusedElm.set(Option.none());
  25122. });
  25123. },
  25124. onHide: function (comp) {
  25125. focusedElm.set(findFocusedElem(comp.element(), lazySink));
  25126. runOnSinkElement(function (elem) {
  25127. return updateSinkVisibility(elem, false);
  25128. });
  25129. },
  25130. onHidden: function () {
  25131. runOnSinkElement(function (elem) {
  25132. return remove$5(elem, [visibility.transitionClass]);
  25133. });
  25134. }
  25135. }, visibility),
  25136. modes: [sharedBackstage.header.getDockingMode()],
  25137. onDocked: onDockingSwitch,
  25138. onUndocked: onDockingSwitch
  25139. })
  25140. ], additionalBehaviours);
  25141. };
  25142. var StickyHeader = /*#__PURE__*/Object.freeze({
  25143. __proto__: null,
  25144. setup: setup$4,
  25145. isDocked: isDocked$1,
  25146. getBehaviours: getBehaviours$2
  25147. });
  25148. var setup$5 = noop;
  25149. var isDocked$2 = never;
  25150. var getBehaviours$3 = constant([]);
  25151. var StaticHeader = /*#__PURE__*/Object.freeze({
  25152. __proto__: null,
  25153. setup: setup$5,
  25154. isDocked: isDocked$2,
  25155. getBehaviours: getBehaviours$3
  25156. });
  25157. var renderHeader = function (spec) {
  25158. var editor = spec.editor;
  25159. var getBehaviours = spec.sticky ? getBehaviours$2 : getBehaviours$3;
  25160. return {
  25161. uid: spec.uid,
  25162. dom: spec.dom,
  25163. components: spec.components,
  25164. behaviours: derive$1(getBehaviours(editor, spec.sharedBackstage))
  25165. };
  25166. };
  25167. var factory$g = function (detail, spec) {
  25168. var setMenus = function (comp, menus) {
  25169. var newMenus = map(menus, function (m) {
  25170. var buttonSpec = {
  25171. type: 'menubutton',
  25172. text: m.text,
  25173. fetch: function (callback) {
  25174. callback(m.getItems());
  25175. }
  25176. };
  25177. var internal = createMenuButton(buttonSpec).mapError(function (errInfo) {
  25178. return formatError(errInfo);
  25179. }).getOrDie();
  25180. return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Option.some('menuitem'));
  25181. });
  25182. Replacing.set(comp, newMenus);
  25183. };
  25184. var apis = {
  25185. focus: Keying.focusIn,
  25186. setMenus: setMenus
  25187. };
  25188. return {
  25189. uid: detail.uid,
  25190. dom: detail.dom,
  25191. components: [],
  25192. behaviours: derive$1([
  25193. Replacing.config({}),
  25194. config('menubar-events', [
  25195. runOnAttached(function (component) {
  25196. detail.onSetup(component);
  25197. }),
  25198. run(mouseover(), function (comp, se) {
  25199. descendant$1(comp.element(), '.' + 'tox-mbtn--active').each(function (activeButton) {
  25200. closest$3(se.event().target(), '.' + 'tox-mbtn').each(function (hoveredButton) {
  25201. if (!eq$1(activeButton, hoveredButton)) {
  25202. comp.getSystem().getByDom(activeButton).each(function (activeComp) {
  25203. comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) {
  25204. Dropdown.expand(hoveredComp);
  25205. Dropdown.close(activeComp);
  25206. Focusing.focus(hoveredComp);
  25207. });
  25208. });
  25209. }
  25210. });
  25211. });
  25212. }),
  25213. run(focusShifted(), function (comp, se) {
  25214. se.event().prevFocus().bind(function (prev) {
  25215. return comp.getSystem().getByDom(prev).toOption();
  25216. }).each(function (prev) {
  25217. se.event().newFocus().bind(function (nu) {
  25218. return comp.getSystem().getByDom(nu).toOption();
  25219. }).each(function (nu) {
  25220. if (Dropdown.isOpen(prev)) {
  25221. Dropdown.expand(nu);
  25222. Dropdown.close(prev);
  25223. }
  25224. });
  25225. });
  25226. })
  25227. ]),
  25228. Keying.config({
  25229. mode: 'flow',
  25230. selector: '.' + 'tox-mbtn',
  25231. onEscape: function (comp) {
  25232. detail.onEscape(comp);
  25233. return Option.some(true);
  25234. }
  25235. }),
  25236. Tabstopping.config({})
  25237. ]),
  25238. apis: apis,
  25239. domModification: { attributes: { role: 'menubar' } }
  25240. };
  25241. };
  25242. var SilverMenubar = single$2({
  25243. factory: factory$g,
  25244. name: 'silver.Menubar',
  25245. configFields: [
  25246. strict$1('dom'),
  25247. strict$1('uid'),
  25248. strict$1('onEscape'),
  25249. strict$1('backstage'),
  25250. defaulted$1('onSetup', noop)
  25251. ],
  25252. apis: {
  25253. focus: function (apis, comp) {
  25254. apis.focus(comp);
  25255. },
  25256. setMenus: function (apis, comp, menus) {
  25257. apis.setMenus(comp, menus);
  25258. }
  25259. }
  25260. });
  25261. var owner$4 = 'container';
  25262. var schema$s = [field$1('slotBehaviours', [])];
  25263. var getPartName$1 = function (name) {
  25264. return '<alloy.field.' + name + '>';
  25265. };
  25266. var sketch$2 = function (sSpec) {
  25267. var parts = function () {
  25268. var record = [];
  25269. var slot = function (name, config) {
  25270. record.push(name);
  25271. return generateOne(owner$4, getPartName$1(name), config);
  25272. };
  25273. return {
  25274. slot: slot,
  25275. record: function () {
  25276. return record;
  25277. }
  25278. };
  25279. }();
  25280. var spec = sSpec(parts);
  25281. var partNames = parts.record();
  25282. var fieldParts = map(partNames, function (n) {
  25283. return required({
  25284. name: n,
  25285. pname: getPartName$1(n)
  25286. });
  25287. });
  25288. return composite(owner$4, schema$s, fieldParts, make$7, spec);
  25289. };
  25290. var make$7 = function (detail, components) {
  25291. var getSlotNames = function (_) {
  25292. return getAllPartNames(detail);
  25293. };
  25294. var getSlot = function (container, key) {
  25295. return getPart(container, detail, key);
  25296. };
  25297. var onSlot = function (f, def) {
  25298. return function (container, key) {
  25299. return getPart(container, detail, key).map(function (slot) {
  25300. return f(slot, key);
  25301. }).getOr(def);
  25302. };
  25303. };
  25304. var onSlots = function (f) {
  25305. return function (container, keys) {
  25306. each(keys, function (key) {
  25307. return f(container, key);
  25308. });
  25309. };
  25310. };
  25311. var doShowing = function (comp, _key) {
  25312. return get$2(comp.element(), 'aria-hidden') !== 'true';
  25313. };
  25314. var doShow = function (comp, key) {
  25315. if (!doShowing(comp)) {
  25316. var element = comp.element();
  25317. remove$6(element, 'display');
  25318. remove$1(element, 'aria-hidden');
  25319. emitWith(comp, slotVisibility(), {
  25320. name: key,
  25321. visible: true
  25322. });
  25323. }
  25324. };
  25325. var doHide = function (comp, key) {
  25326. if (doShowing(comp)) {
  25327. var element = comp.element();
  25328. set$2(element, 'display', 'none');
  25329. set$1(element, 'aria-hidden', 'true');
  25330. emitWith(comp, slotVisibility(), {
  25331. name: key,
  25332. visible: false
  25333. });
  25334. }
  25335. };
  25336. var isShowing = onSlot(doShowing, false);
  25337. var hideSlot = onSlot(doHide);
  25338. var hideSlots = onSlots(hideSlot);
  25339. var hideAllSlots = function (container) {
  25340. return hideSlots(container, getSlotNames());
  25341. };
  25342. var showSlot = onSlot(doShow);
  25343. var apis = {
  25344. getSlotNames: getSlotNames,
  25345. getSlot: getSlot,
  25346. isShowing: isShowing,
  25347. hideSlot: hideSlot,
  25348. hideAllSlots: hideAllSlots,
  25349. showSlot: showSlot
  25350. };
  25351. return {
  25352. uid: detail.uid,
  25353. dom: detail.dom,
  25354. components: components,
  25355. behaviours: get$c(detail.slotBehaviours),
  25356. apis: apis
  25357. };
  25358. };
  25359. var slotApis = map$1({
  25360. getSlotNames: function (apis, c) {
  25361. return apis.getSlotNames(c);
  25362. },
  25363. getSlot: function (apis, c, key) {
  25364. return apis.getSlot(c, key);
  25365. },
  25366. isShowing: function (apis, c, key) {
  25367. return apis.isShowing(c, key);
  25368. },
  25369. hideSlot: function (apis, c, key) {
  25370. return apis.hideSlot(c, key);
  25371. },
  25372. hideAllSlots: function (apis, c) {
  25373. return apis.hideAllSlots(c);
  25374. },
  25375. showSlot: function (apis, c, key) {
  25376. return apis.showSlot(c, key);
  25377. }
  25378. }, function (value) {
  25379. return makeApi(value);
  25380. });
  25381. var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch$2 });
  25382. var sidebarSchema = objOf([
  25383. optionString('icon'),
  25384. optionString('tooltip'),
  25385. defaultedFunction('onShow', noop),
  25386. defaultedFunction('onHide', noop),
  25387. defaultedFunction('onSetup', function () {
  25388. return noop;
  25389. })
  25390. ]);
  25391. var createSidebar = function (spec) {
  25392. return asRaw('sidebar', sidebarSchema, spec);
  25393. };
  25394. var setup$6 = function (editor) {
  25395. var sidebars = editor.ui.registry.getAll().sidebars;
  25396. each(keys(sidebars), function (name) {
  25397. var spec = sidebars[name];
  25398. var isActive = function () {
  25399. return Option.from(editor.queryCommandValue('ToggleSidebar')).is(name);
  25400. };
  25401. editor.ui.registry.addToggleButton(name, {
  25402. icon: spec.icon,
  25403. tooltip: spec.tooltip,
  25404. onAction: function (buttonApi) {
  25405. editor.execCommand('ToggleSidebar', false, name);
  25406. buttonApi.setActive(isActive());
  25407. },
  25408. onSetup: function (buttonApi) {
  25409. var handleToggle = function () {
  25410. return buttonApi.setActive(isActive());
  25411. };
  25412. editor.on('ToggleSidebar', handleToggle);
  25413. return function () {
  25414. editor.off('ToggleSidebar', handleToggle);
  25415. };
  25416. }
  25417. });
  25418. });
  25419. };
  25420. var getApi = function (comp) {
  25421. return {
  25422. element: function () {
  25423. return comp.element().dom();
  25424. }
  25425. };
  25426. };
  25427. var makePanels = function (parts, panelConfigs) {
  25428. var specs = map(keys(panelConfigs), function (name) {
  25429. var spec = panelConfigs[name];
  25430. var bridged = getOrDie(createSidebar(spec));
  25431. return {
  25432. name: name,
  25433. getApi: getApi,
  25434. onSetup: bridged.onSetup,
  25435. onShow: bridged.onShow,
  25436. onHide: bridged.onHide
  25437. };
  25438. });
  25439. return map(specs, function (spec) {
  25440. var editorOffCell = Cell(noop);
  25441. return parts.slot(spec.name, {
  25442. dom: {
  25443. tag: 'div',
  25444. classes: ['tox-sidebar__pane']
  25445. },
  25446. behaviours: SimpleBehaviours.unnamedEvents([
  25447. onControlAttached(spec, editorOffCell),
  25448. onControlDetached(spec, editorOffCell),
  25449. run(slotVisibility(), function (sidepanel, se) {
  25450. var data = se.event();
  25451. var optSidePanelSpec = find(specs, function (config) {
  25452. return config.name === data.name();
  25453. });
  25454. optSidePanelSpec.each(function (sidePanelSpec) {
  25455. var handler = data.visible() ? sidePanelSpec.onShow : sidePanelSpec.onHide;
  25456. handler(sidePanelSpec.getApi(sidepanel));
  25457. });
  25458. })
  25459. ])
  25460. });
  25461. });
  25462. };
  25463. var makeSidebar = function (panelConfigs) {
  25464. return SlotContainer.sketch(function (parts) {
  25465. return {
  25466. dom: {
  25467. tag: 'div',
  25468. classes: ['tox-sidebar__pane-container']
  25469. },
  25470. components: makePanels(parts, panelConfigs),
  25471. slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) {
  25472. return SlotContainer.hideAllSlots(slotContainer);
  25473. })])
  25474. };
  25475. });
  25476. };
  25477. var setSidebar = function (sidebar, panelConfigs) {
  25478. var optSlider = Composing.getCurrent(sidebar);
  25479. optSlider.each(function (slider) {
  25480. return Replacing.set(slider, [makeSidebar(panelConfigs)]);
  25481. });
  25482. };
  25483. var toggleSidebar = function (sidebar, name) {
  25484. var optSlider = Composing.getCurrent(sidebar);
  25485. optSlider.each(function (slider) {
  25486. var optSlotContainer = Composing.getCurrent(slider);
  25487. optSlotContainer.each(function (slotContainer) {
  25488. if (Sliding.hasGrown(slider)) {
  25489. if (SlotContainer.isShowing(slotContainer, name)) {
  25490. Sliding.shrink(slider);
  25491. } else {
  25492. SlotContainer.hideAllSlots(slotContainer);
  25493. SlotContainer.showSlot(slotContainer, name);
  25494. }
  25495. } else {
  25496. SlotContainer.hideAllSlots(slotContainer);
  25497. SlotContainer.showSlot(slotContainer, name);
  25498. Sliding.grow(slider);
  25499. }
  25500. });
  25501. });
  25502. };
  25503. var whichSidebar = function (sidebar) {
  25504. var optSlider = Composing.getCurrent(sidebar);
  25505. return optSlider.bind(function (slider) {
  25506. var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider);
  25507. if (sidebarOpen) {
  25508. var optSlotContainer = Composing.getCurrent(slider);
  25509. return optSlotContainer.bind(function (slotContainer) {
  25510. return find(SlotContainer.getSlotNames(slotContainer), function (name) {
  25511. return SlotContainer.isShowing(slotContainer, name);
  25512. });
  25513. });
  25514. } else {
  25515. return Option.none();
  25516. }
  25517. });
  25518. };
  25519. var fixSize = generate$1('FixSizeEvent');
  25520. var autoSize = generate$1('AutoSizeEvent');
  25521. var renderSidebar = function (spec) {
  25522. return {
  25523. uid: spec.uid,
  25524. dom: {
  25525. tag: 'div',
  25526. classes: ['tox-sidebar'],
  25527. attributes: { role: 'complementary' }
  25528. },
  25529. components: [{
  25530. dom: {
  25531. tag: 'div',
  25532. classes: ['tox-sidebar__slider']
  25533. },
  25534. components: [],
  25535. behaviours: derive$1([
  25536. Tabstopping.config({}),
  25537. Focusing.config({}),
  25538. Sliding.config({
  25539. dimension: { property: 'width' },
  25540. closedClass: 'tox-sidebar--sliding-closed',
  25541. openClass: 'tox-sidebar--sliding-open',
  25542. shrinkingClass: 'tox-sidebar--sliding-shrinking',
  25543. growingClass: 'tox-sidebar--sliding-growing',
  25544. onShrunk: function (slider) {
  25545. var optSlotContainer = Composing.getCurrent(slider);
  25546. optSlotContainer.each(SlotContainer.hideAllSlots);
  25547. emit(slider, autoSize);
  25548. },
  25549. onGrown: function (slider) {
  25550. emit(slider, autoSize);
  25551. },
  25552. onStartGrow: function (slider) {
  25553. emitWith(slider, fixSize, { width: getRaw(slider.element(), 'width').getOr('') });
  25554. },
  25555. onStartShrink: function (slider) {
  25556. emitWith(slider, fixSize, { width: get$7(slider.element()) + 'px' });
  25557. }
  25558. }),
  25559. Replacing.config({}),
  25560. Composing.config({
  25561. find: function (comp) {
  25562. var children = Replacing.contents(comp);
  25563. return head(children);
  25564. }
  25565. })
  25566. ])
  25567. }],
  25568. behaviours: derive$1([
  25569. ComposingConfigs.childAt(0),
  25570. config('sidebar-sliding-events', [
  25571. run(fixSize, function (comp, se) {
  25572. set$2(comp.element(), 'width', se.event().width());
  25573. }),
  25574. run(autoSize, function (comp, _se) {
  25575. remove$6(comp.element(), 'width');
  25576. })
  25577. ])
  25578. ])
  25579. };
  25580. };
  25581. var getAttrs = function (elem) {
  25582. var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
  25583. return foldl(attributes, function (b, attr) {
  25584. var _a;
  25585. if (attr.name === 'class') {
  25586. return b;
  25587. } else {
  25588. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  25589. }
  25590. }, {});
  25591. };
  25592. var getClasses = function (elem) {
  25593. return Array.prototype.slice.call(elem.dom().classList, 0);
  25594. };
  25595. var fromHtml$2 = function (html) {
  25596. var elem = Element.fromHtml(html);
  25597. var children$1 = children(elem);
  25598. var attrs = getAttrs(elem);
  25599. var classes = getClasses(elem);
  25600. var contents = children$1.length === 0 ? {} : { innerHtml: get$1(elem) };
  25601. return __assign({
  25602. tag: name(elem),
  25603. classes: classes,
  25604. attributes: attrs
  25605. }, contents);
  25606. };
  25607. var renderSpinner = function (providerBackstage) {
  25608. return {
  25609. dom: {
  25610. tag: 'div',
  25611. attributes: { 'aria-label': providerBackstage.translate('Loading...') },
  25612. classes: ['tox-throbber__busy-spinner']
  25613. },
  25614. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }],
  25615. behaviours: derive$1([
  25616. Keying.config({
  25617. mode: 'special',
  25618. onTab: function () {
  25619. return Option.some(true);
  25620. },
  25621. onShiftTab: function () {
  25622. return Option.some(true);
  25623. }
  25624. }),
  25625. Focusing.config({})
  25626. ])
  25627. };
  25628. };
  25629. var toggleThrobber = function (comp, state, providerBackstage) {
  25630. var element = comp.element();
  25631. if (state === true) {
  25632. Replacing.set(comp, [renderSpinner(providerBackstage)]);
  25633. remove$6(element, 'display');
  25634. remove$1(element, 'aria-hidden');
  25635. } else {
  25636. Replacing.set(comp, []);
  25637. set$2(element, 'display', 'none');
  25638. set$1(element, 'aria-hidden', 'true');
  25639. }
  25640. };
  25641. var renderThrobber = function (spec) {
  25642. return {
  25643. uid: spec.uid,
  25644. dom: {
  25645. tag: 'div',
  25646. attributes: { 'aria-hidden': 'true' },
  25647. classes: ['tox-throbber'],
  25648. styles: { display: 'none' }
  25649. },
  25650. behaviours: derive$1([Replacing.config({})]),
  25651. components: []
  25652. };
  25653. };
  25654. var setup$7 = function (editor, lazyThrobber, sharedBackstage) {
  25655. var throbberState = Cell(false);
  25656. var timer = Cell(Option.none());
  25657. var toggle = function (state) {
  25658. if (state !== throbberState.get()) {
  25659. toggleThrobber(lazyThrobber(), state, sharedBackstage.providers);
  25660. throbberState.set(state);
  25661. }
  25662. };
  25663. editor.on('ProgressState', function (e) {
  25664. timer.get().each(global$2.clearTimeout);
  25665. if (isNumber(e.time)) {
  25666. var timerId = global$2.setEditorTimeout(editor, function () {
  25667. return toggle(e.state);
  25668. }, e.time);
  25669. timer.set(Option.some(timerId));
  25670. } else {
  25671. toggle(e.state);
  25672. timer.set(Option.none());
  25673. }
  25674. });
  25675. };
  25676. var factory$h = function (detail, components, _spec) {
  25677. var apis = {
  25678. getSocket: function (comp) {
  25679. return parts$d.getPart(comp, detail, 'socket');
  25680. },
  25681. setSidebar: function (comp, panelConfigs) {
  25682. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25683. return setSidebar(sidebar, panelConfigs);
  25684. });
  25685. },
  25686. toggleSidebar: function (comp, name) {
  25687. parts$d.getPart(comp, detail, 'sidebar').each(function (sidebar) {
  25688. return toggleSidebar(sidebar, name);
  25689. });
  25690. },
  25691. whichSidebar: function (comp) {
  25692. return parts$d.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull();
  25693. },
  25694. getHeader: function (comp) {
  25695. return parts$d.getPart(comp, detail, 'header');
  25696. },
  25697. getToolbar: function (comp) {
  25698. return parts$d.getPart(comp, detail, 'toolbar');
  25699. },
  25700. setToolbar: function (comp, groups) {
  25701. parts$d.getPart(comp, detail, 'toolbar').each(function (toolbar) {
  25702. toolbar.getApis().setGroups(toolbar, groups);
  25703. });
  25704. },
  25705. setToolbars: function (comp, toolbars) {
  25706. parts$d.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) {
  25707. CustomList.setItems(mToolbar, toolbars);
  25708. });
  25709. },
  25710. refreshToolbar: function (comp) {
  25711. var toolbar = parts$d.getPart(comp, detail, 'toolbar');
  25712. toolbar.each(function (toolbar) {
  25713. return toolbar.getApis().refresh(toolbar);
  25714. });
  25715. },
  25716. getThrobber: function (comp) {
  25717. return parts$d.getPart(comp, detail, 'throbber');
  25718. },
  25719. focusToolbar: function (comp) {
  25720. var optToolbar = parts$d.getPart(comp, detail, 'toolbar').orThunk(function () {
  25721. return parts$d.getPart(comp, detail, 'multiple-toolbar');
  25722. });
  25723. optToolbar.each(function (toolbar) {
  25724. Keying.focusIn(toolbar);
  25725. });
  25726. },
  25727. setMenubar: function (comp, menus) {
  25728. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25729. SilverMenubar.setMenus(menubar, menus);
  25730. });
  25731. },
  25732. focusMenubar: function (comp) {
  25733. parts$d.getPart(comp, detail, 'menubar').each(function (menubar) {
  25734. SilverMenubar.focus(menubar);
  25735. });
  25736. }
  25737. };
  25738. return {
  25739. uid: detail.uid,
  25740. dom: detail.dom,
  25741. components: components,
  25742. apis: apis,
  25743. behaviours: detail.behaviours
  25744. };
  25745. };
  25746. var partMenubar = partType$1.optional({
  25747. factory: SilverMenubar,
  25748. name: 'menubar',
  25749. schema: [strict$1('backstage')]
  25750. });
  25751. var toolbarFactory = function (spec) {
  25752. if (spec.type === ToolbarMode.sliding) {
  25753. return renderSlidingMoreToolbar;
  25754. } else if (spec.type === ToolbarMode.floating) {
  25755. return renderFloatingMoreToolbar;
  25756. } else {
  25757. return renderToolbar;
  25758. }
  25759. };
  25760. var partMultipleToolbar = partType$1.optional({
  25761. factory: {
  25762. sketch: function (spec) {
  25763. return CustomList.sketch({
  25764. uid: spec.uid,
  25765. dom: spec.dom,
  25766. listBehaviours: derive$1([Keying.config({
  25767. mode: 'acyclic',
  25768. selector: '.tox-toolbar'
  25769. })]),
  25770. makeItem: function () {
  25771. return renderToolbar({
  25772. type: spec.type,
  25773. uid: generate$1('multiple-toolbar-item'),
  25774. cyclicKeying: false,
  25775. initGroups: [],
  25776. providers: spec.providers,
  25777. onEscape: function () {
  25778. return Option.none();
  25779. }
  25780. });
  25781. },
  25782. setupItem: function (_mToolbar, tc, data, _index) {
  25783. Toolbar.setGroups(tc, data);
  25784. },
  25785. shell: true
  25786. });
  25787. }
  25788. },
  25789. name: 'multiple-toolbar',
  25790. schema: [
  25791. strict$1('dom'),
  25792. strict$1('onEscape')
  25793. ]
  25794. });
  25795. var partToolbar = partType$1.optional({
  25796. factory: {
  25797. sketch: function (spec) {
  25798. var renderer = toolbarFactory(spec);
  25799. var toolbarSpec = {
  25800. type: spec.type,
  25801. uid: spec.uid,
  25802. onEscape: function () {
  25803. spec.onEscape();
  25804. return Option.some(true);
  25805. },
  25806. cyclicKeying: false,
  25807. initGroups: [],
  25808. getSink: spec.getSink,
  25809. providers: spec.providers,
  25810. moreDrawerData: {
  25811. lazyToolbar: spec.lazyToolbar,
  25812. lazyMoreButton: spec.lazyMoreButton,
  25813. lazyHeader: spec.lazyHeader
  25814. },
  25815. attributes: spec.attributes
  25816. };
  25817. return renderer(toolbarSpec);
  25818. }
  25819. },
  25820. name: 'toolbar',
  25821. schema: [
  25822. strict$1('dom'),
  25823. strict$1('onEscape'),
  25824. strict$1('getSink')
  25825. ]
  25826. });
  25827. var partHeader = partType$1.optional({
  25828. factory: { sketch: renderHeader },
  25829. name: 'header',
  25830. schema: [strict$1('dom')]
  25831. });
  25832. var partSocket = partType$1.optional({
  25833. name: 'socket',
  25834. schema: [strict$1('dom')]
  25835. });
  25836. var partSidebar = partType$1.optional({
  25837. factory: { sketch: renderSidebar },
  25838. name: 'sidebar',
  25839. schema: [strict$1('dom')]
  25840. });
  25841. var partThrobber = partType$1.optional({
  25842. factory: { sketch: renderThrobber },
  25843. name: 'throbber',
  25844. schema: [strict$1('dom')]
  25845. });
  25846. var OuterContainer = composite$1({
  25847. name: 'OuterContainer',
  25848. factory: factory$h,
  25849. configFields: [
  25850. strict$1('dom'),
  25851. strict$1('behaviours')
  25852. ],
  25853. partFields: [
  25854. partHeader,
  25855. partMenubar,
  25856. partToolbar,
  25857. partMultipleToolbar,
  25858. partSocket,
  25859. partSidebar,
  25860. partThrobber
  25861. ],
  25862. apis: {
  25863. getSocket: function (apis, comp) {
  25864. return apis.getSocket(comp);
  25865. },
  25866. setSidebar: function (apis, comp, panelConfigs) {
  25867. apis.setSidebar(comp, panelConfigs);
  25868. },
  25869. toggleSidebar: function (apis, comp, name) {
  25870. apis.toggleSidebar(comp, name);
  25871. },
  25872. whichSidebar: function (apis, comp) {
  25873. return apis.whichSidebar(comp);
  25874. },
  25875. getHeader: function (apis, comp) {
  25876. return apis.getHeader(comp);
  25877. },
  25878. getToolbar: function (apis, comp) {
  25879. return apis.getToolbar(comp);
  25880. },
  25881. setToolbar: function (apis, comp, grps) {
  25882. var groups = map(grps, function (grp) {
  25883. return renderToolbarGroup(grp);
  25884. });
  25885. apis.setToolbar(comp, groups);
  25886. },
  25887. setToolbars: function (apis, comp, ts) {
  25888. var renderedToolbars = map(ts, function (g) {
  25889. return map(g, renderToolbarGroup);
  25890. });
  25891. apis.setToolbars(comp, renderedToolbars);
  25892. },
  25893. refreshToolbar: function (apis, comp) {
  25894. return apis.refreshToolbar(comp);
  25895. },
  25896. getThrobber: function (apis, comp) {
  25897. return apis.getThrobber(comp);
  25898. },
  25899. setMenubar: function (apis, comp, menus) {
  25900. apis.setMenubar(comp, menus);
  25901. },
  25902. focusMenubar: function (apis, comp) {
  25903. apis.focusMenubar(comp);
  25904. },
  25905. focusToolbar: function (apis, comp) {
  25906. apis.focusToolbar(comp);
  25907. }
  25908. }
  25909. });
  25910. var defaultMenubar = 'file edit view insert format tools table help';
  25911. var defaultMenus = {
  25912. file: {
  25913. title: 'File',
  25914. items: 'newdocument restoredraft | preview | print | deleteallconversations'
  25915. },
  25916. edit: {
  25917. title: 'Edit',
  25918. items: 'undo redo | cut copy paste pastetext | selectall | searchreplace'
  25919. },
  25920. view: {
  25921. title: 'View',
  25922. items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments'
  25923. },
  25924. insert: {
  25925. title: 'Insert',
  25926. items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
  25927. },
  25928. format: {
  25929. title: 'Format',
  25930. items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align | forecolor backcolor | removeformat'
  25931. },
  25932. tools: {
  25933. title: 'Tools',
  25934. items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount'
  25935. },
  25936. table: {
  25937. title: 'Table',
  25938. items: 'inserttable | cell row column | advtablesort | tableprops deletetable'
  25939. },
  25940. help: {
  25941. title: 'Help',
  25942. items: 'help'
  25943. }
  25944. };
  25945. var make$8 = function (menu, registry, editor) {
  25946. var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/);
  25947. return {
  25948. text: menu.title,
  25949. getItems: function () {
  25950. return bind(menu.items, function (i) {
  25951. var itemName = i.toLowerCase();
  25952. if (itemName.trim().length === 0) {
  25953. return [];
  25954. } else if (exists(removedMenuItems, function (removedMenuItem) {
  25955. return removedMenuItem === itemName;
  25956. })) {
  25957. return [];
  25958. } else if (itemName === 'separator' || itemName === '|') {
  25959. return [{ type: 'separator' }];
  25960. } else if (registry.menuItems[itemName]) {
  25961. return [registry.menuItems[itemName]];
  25962. } else {
  25963. return [];
  25964. }
  25965. });
  25966. }
  25967. };
  25968. };
  25969. var parseItemsString = function (items) {
  25970. if (typeof items === 'string') {
  25971. return items.split(' ');
  25972. }
  25973. return items;
  25974. };
  25975. var identifyMenus = function (editor, registry) {
  25976. var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus);
  25977. var userDefinedMenus = keys(registry.menus).length > 0;
  25978. var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar);
  25979. var validMenus = filter(menubar, function (menuName) {
  25980. return userDefinedMenus ? registry.menus.hasOwnProperty(menuName) && registry.menus[menuName].hasOwnProperty('items') || defaultMenus.hasOwnProperty(menuName) : defaultMenus.hasOwnProperty(menuName);
  25981. });
  25982. var menus = map(validMenus, function (menuName) {
  25983. var menuData = rawMenuData[menuName];
  25984. return make$8({
  25985. title: menuData.title,
  25986. items: parseItemsString(menuData.items)
  25987. }, registry, editor);
  25988. });
  25989. return filter(menus, function (menu) {
  25990. var isNotSeparator = function (item) {
  25991. return item.type !== 'separator';
  25992. };
  25993. return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator);
  25994. });
  25995. };
  25996. var fireSkinLoaded$1 = function (editor) {
  25997. var done = function () {
  25998. editor._skinLoaded = true;
  25999. fireSkinLoaded(editor);
  26000. };
  26001. return function () {
  26002. if (editor.initialized) {
  26003. done();
  26004. } else {
  26005. editor.on('init', done);
  26006. }
  26007. };
  26008. };
  26009. var fireSkinLoadError$1 = function (editor, err) {
  26010. return function () {
  26011. return fireSkinLoadError(editor, { message: err });
  26012. };
  26013. };
  26014. var loadSkin = function (isInline, editor) {
  26015. var skinUrl = getSkinUrl(editor);
  26016. var skinUiCss;
  26017. if (skinUrl) {
  26018. skinUiCss = skinUrl + '/skin.min.css';
  26019. editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css');
  26020. }
  26021. if (isSkinDisabled(editor) === false && skinUiCss) {
  26022. global$7.DOM.styleSheetLoader.load(skinUiCss, fireSkinLoaded$1(editor), fireSkinLoadError$1(editor, 'Skin could not be loaded'));
  26023. } else {
  26024. fireSkinLoaded$1(editor)();
  26025. }
  26026. };
  26027. var iframe = curry(loadSkin, false);
  26028. var inline = curry(loadSkin, true);
  26029. var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) {
  26030. var comp = uiComponents.outerContainer;
  26031. var toolbarConfig = rawUiConfig.toolbar;
  26032. var toolbarButtonsConfig = rawUiConfig.buttons;
  26033. if (isArrayOf(toolbarConfig, isString)) {
  26034. var toolbars = toolbarConfig.map(function (t) {
  26035. var config = {
  26036. toolbar: t,
  26037. buttons: toolbarButtonsConfig,
  26038. allowToolbarGroups: rawUiConfig.allowToolbarGroups
  26039. };
  26040. return identifyButtons(editor, config, { backstage: backstage }, Option.none());
  26041. });
  26042. OuterContainer.setToolbars(comp, toolbars);
  26043. } else {
  26044. OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Option.none()));
  26045. }
  26046. };
  26047. var DOM = global$7.DOM;
  26048. var detection = detect$3();
  26049. var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12;
  26050. var setupEvents = function (editor) {
  26051. var contentWindow = editor.getWin();
  26052. var initialDocEle = editor.getDoc().documentElement;
  26053. var lastWindowDimensions = Cell(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  26054. var lastDocumentDimensions = Cell(Position(initialDocEle.offsetWidth, initialDocEle.offsetHeight));
  26055. var resizeWindow = function (e) {
  26056. var outer = lastWindowDimensions.get();
  26057. if (outer.left() !== contentWindow.innerWidth || outer.top() !== contentWindow.innerHeight) {
  26058. lastWindowDimensions.set(Position(contentWindow.innerWidth, contentWindow.innerHeight));
  26059. fireResizeContent(editor, e);
  26060. }
  26061. };
  26062. var resizeDocument = function (e) {
  26063. var docEle = editor.getDoc().documentElement;
  26064. var inner = lastDocumentDimensions.get();
  26065. if (inner.left() !== docEle.offsetWidth || inner.top() !== docEle.offsetHeight) {
  26066. lastDocumentDimensions.set(Position(docEle.offsetWidth, docEle.offsetHeight));
  26067. fireResizeContent(editor, e);
  26068. }
  26069. };
  26070. var scroll = function (e) {
  26071. return fireScrollContent(editor, e);
  26072. };
  26073. DOM.bind(contentWindow, 'resize', resizeWindow);
  26074. DOM.bind(contentWindow, 'scroll', scroll);
  26075. var elementLoad = capture$1(Element.fromDom(editor.getBody()), 'load', resizeDocument);
  26076. editor.on('NodeChange', resizeDocument);
  26077. editor.on('remove', function () {
  26078. elementLoad.unbind();
  26079. DOM.unbind(contentWindow, 'resize', resizeWindow);
  26080. DOM.unbind(contentWindow, 'scroll', scroll);
  26081. });
  26082. };
  26083. var render = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26084. var lastToolbarWidth = Cell(0);
  26085. iframe(editor);
  26086. attachSystemAfter(Element.fromDom(args.targetNode), uiComponents.mothership);
  26087. attachSystem(body(), uiComponents.uiMothership);
  26088. editor.on('PostRender', function () {
  26089. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26090. lastToolbarWidth.set(editor.getWin().innerWidth);
  26091. OuterContainer.setMenubar(uiComponents.outerContainer, identifyMenus(editor, rawUiConfig));
  26092. OuterContainer.setSidebar(uiComponents.outerContainer, rawUiConfig.sidebar);
  26093. setupEvents(editor);
  26094. });
  26095. var socket = OuterContainer.getSocket(uiComponents.outerContainer).getOrDie('Could not find expected socket element');
  26096. if (isiOS12 === true) {
  26097. setAll$1(socket.element(), {
  26098. 'overflow': 'scroll',
  26099. '-webkit-overflow-scrolling': 'touch'
  26100. });
  26101. var limit = first(function () {
  26102. editor.fire('ScrollContent');
  26103. }, 20);
  26104. bind$3(socket.element(), 'scroll', limit.throttle);
  26105. }
  26106. setupReadonlyModeSwitch(editor, uiComponents);
  26107. editor.addCommand('ToggleSidebar', function (ui, value) {
  26108. OuterContainer.toggleSidebar(uiComponents.outerContainer, value);
  26109. editor.fire('ToggleSidebar');
  26110. });
  26111. editor.addQueryValueHandler('ToggleSidebar', function () {
  26112. return OuterContainer.whichSidebar(uiComponents.outerContainer);
  26113. });
  26114. var toolbarMode = getToolbarMode(editor);
  26115. var refreshDrawer = function () {
  26116. OuterContainer.refreshToolbar(uiComponents.outerContainer);
  26117. };
  26118. if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) {
  26119. editor.on('ResizeWindow ResizeEditor ResizeContent', function () {
  26120. var width = editor.getWin().innerWidth;
  26121. if (width !== lastToolbarWidth.get()) {
  26122. refreshDrawer();
  26123. lastToolbarWidth.set(width);
  26124. }
  26125. });
  26126. }
  26127. return {
  26128. iframeContainer: socket.element().dom(),
  26129. editorContainer: uiComponents.outerContainer.element().dom()
  26130. };
  26131. };
  26132. var Iframe = /*#__PURE__*/Object.freeze({
  26133. __proto__: null,
  26134. render: render
  26135. });
  26136. var revocable = function (doRevoke) {
  26137. var subject = Cell(Option.none());
  26138. var revoke = function () {
  26139. subject.get().each(doRevoke);
  26140. };
  26141. var clear = function () {
  26142. revoke();
  26143. subject.set(Option.none());
  26144. };
  26145. var set = function (s) {
  26146. revoke();
  26147. subject.set(Option.some(s));
  26148. };
  26149. var isSet = function () {
  26150. return subject.get().isSome();
  26151. };
  26152. return {
  26153. clear: clear,
  26154. isSet: isSet,
  26155. set: set
  26156. };
  26157. };
  26158. var unbindable = function () {
  26159. return revocable(function (s) {
  26160. s.unbind();
  26161. });
  26162. };
  26163. var value$3 = function () {
  26164. var subject = Cell(Option.none());
  26165. var clear = function () {
  26166. subject.set(Option.none());
  26167. };
  26168. var set = function (s) {
  26169. subject.set(Option.some(s));
  26170. };
  26171. var on = function (f) {
  26172. subject.get().each(f);
  26173. };
  26174. var isSet = function () {
  26175. return subject.get().isSome();
  26176. };
  26177. return {
  26178. clear: clear,
  26179. set: set,
  26180. isSet: isSet,
  26181. on: on
  26182. };
  26183. };
  26184. var parseToInt = function (val) {
  26185. var re = /^[0-9\.]+(|px)$/i;
  26186. if (re.test('' + val)) {
  26187. return Option.some(parseInt('' + val, 10));
  26188. }
  26189. return Option.none();
  26190. };
  26191. var numToPx = function (val) {
  26192. return isNumber(val) ? val + 'px' : val;
  26193. };
  26194. var calcCappedSize = function (size, minSize, maxSize) {
  26195. var minOverride = minSize.filter(function (min) {
  26196. return size < min;
  26197. });
  26198. var maxOverride = maxSize.filter(function (max) {
  26199. return size > max;
  26200. });
  26201. return minOverride.or(maxOverride).getOr(size);
  26202. };
  26203. var getHeight$1 = function (editor) {
  26204. var baseHeight = getHeightSetting(editor);
  26205. var minHeight = getMinHeightSetting(editor);
  26206. var maxHeight = getMaxHeightSetting(editor);
  26207. return parseToInt(baseHeight).map(function (height) {
  26208. return calcCappedSize(height, minHeight, maxHeight);
  26209. });
  26210. };
  26211. var getHeightWithFallback = function (editor) {
  26212. var height = getHeight$1(editor);
  26213. return height.getOr(getHeightSetting(editor));
  26214. };
  26215. var getWidth$1 = function (editor) {
  26216. var baseWidth = getWidthSetting(editor);
  26217. var minWidth = getMinWidthSetting(editor);
  26218. var maxWidth = getMaxWidthSetting(editor);
  26219. return parseToInt(baseWidth).map(function (width) {
  26220. return calcCappedSize(width, minWidth, maxWidth);
  26221. });
  26222. };
  26223. var getWidthWithFallback = function (editor) {
  26224. var width = getWidth$1(editor);
  26225. return width.getOr(getWidthSetting(editor));
  26226. };
  26227. var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) {
  26228. var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26229. var DOM = global$7.DOM;
  26230. var useFixedToolbarContainer = useFixedContainer(editor);
  26231. var isSticky = isStickyToolbar(editor);
  26232. var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth$1(editor));
  26233. var headerBackstage = backstage.shared.header;
  26234. var isPositionedAtTop = headerBackstage.isPositionedAtTop;
  26235. var toolbarMode = getToolbarMode(editor);
  26236. var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating;
  26237. var visible = Cell(false);
  26238. var isVisible = function () {
  26239. return visible.get() && !editor.removed;
  26240. };
  26241. var calcToolbarOffset = function (toolbar) {
  26242. return isSplitToolbar ? toolbar.fold(function () {
  26243. return 0;
  26244. }, function (tbar) {
  26245. return tbar.components().length > 1 ? get$6(tbar.components()[1].element()) : 0;
  26246. }) : 0;
  26247. };
  26248. var calcMode = function (container) {
  26249. switch (getToolbarLocation(editor)) {
  26250. case ToolbarLocation.auto:
  26251. var toolbar_1 = OuterContainer.getToolbar(outerContainer);
  26252. var offset = calcToolbarOffset(toolbar_1);
  26253. var toolbarHeight = get$6(container.element()) - offset;
  26254. var targetBounds = box(targetElm);
  26255. var roomAtTop = targetBounds.y > toolbarHeight;
  26256. if (roomAtTop) {
  26257. return 'top';
  26258. } else {
  26259. var doc = documentElement(targetElm);
  26260. var docHeight = Math.max(doc.dom().scrollHeight, get$6(doc));
  26261. var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight;
  26262. if (roomAtBottom) {
  26263. return 'bottom';
  26264. } else {
  26265. var winBounds = win();
  26266. var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight;
  26267. return isRoomAtBottomViewport ? 'bottom' : 'top';
  26268. }
  26269. }
  26270. case ToolbarLocation.bottom:
  26271. return 'bottom';
  26272. case ToolbarLocation.top:
  26273. default:
  26274. return 'top';
  26275. }
  26276. };
  26277. var setupMode = function (mode) {
  26278. var container = floatContainer.get();
  26279. Docking.setModes(container, [mode]);
  26280. headerBackstage.setDockingMode(mode);
  26281. var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop;
  26282. set$1(container.element(), Attribute, verticalDir);
  26283. };
  26284. var updateChromeWidth = function () {
  26285. var maxWidth = editorMaxWidthOpt.getOrThunk(function () {
  26286. var bodyMargin = parseToInt(get$4(body(), 'margin-left')).getOr(0);
  26287. return get$7(body()) - absolute(targetElm).left() + bodyMargin;
  26288. });
  26289. set$2(floatContainer.get().element(), 'max-width', maxWidth + 'px');
  26290. };
  26291. var updateChromePosition = function () {
  26292. var toolbar = OuterContainer.getToolbar(outerContainer);
  26293. var offset = calcToolbarOffset(toolbar);
  26294. var targetBounds = box(targetElm);
  26295. var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$6(floatContainer.get().element()) + offset, 0) : targetBounds.bottom;
  26296. setAll$1(outerContainer.element(), {
  26297. position: 'absolute',
  26298. top: Math.round(top) + 'px',
  26299. left: Math.round(targetBounds.x) + 'px'
  26300. });
  26301. };
  26302. var repositionPopups$1 = function () {
  26303. uiMothership.broadcastOn([repositionPopups()], {});
  26304. };
  26305. var updateChromeUi = function (resetDocking) {
  26306. if (resetDocking === void 0) {
  26307. resetDocking = false;
  26308. }
  26309. if (!isVisible()) {
  26310. return;
  26311. }
  26312. if (!useFixedToolbarContainer) {
  26313. updateChromeWidth();
  26314. }
  26315. if (isSplitToolbar) {
  26316. OuterContainer.refreshToolbar(outerContainer);
  26317. }
  26318. if (!useFixedToolbarContainer) {
  26319. updateChromePosition();
  26320. }
  26321. if (isSticky) {
  26322. var floatContainerComp = floatContainer.get();
  26323. resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp);
  26324. }
  26325. repositionPopups$1();
  26326. };
  26327. var updateMode = function (updateUi) {
  26328. if (updateUi === void 0) {
  26329. updateUi = true;
  26330. }
  26331. if (useFixedToolbarContainer || !isSticky || !isVisible()) {
  26332. return;
  26333. }
  26334. var currentMode = headerBackstage.getDockingMode();
  26335. var newMode = calcMode(floatContainer.get());
  26336. if (newMode !== currentMode) {
  26337. setupMode(newMode);
  26338. if (updateUi) {
  26339. updateChromeUi(true);
  26340. }
  26341. }
  26342. };
  26343. var show = function () {
  26344. visible.set(true);
  26345. set$2(outerContainer.element(), 'display', 'flex');
  26346. DOM.addClass(editor.getBody(), 'mce-edit-focus');
  26347. remove$6(uiMothership.element(), 'display');
  26348. updateMode(false);
  26349. updateChromeUi();
  26350. };
  26351. var hide = function () {
  26352. visible.set(false);
  26353. if (uiComponents.outerContainer) {
  26354. set$2(outerContainer.element(), 'display', 'none');
  26355. DOM.removeClass(editor.getBody(), 'mce-edit-focus');
  26356. }
  26357. set$2(uiMothership.element(), 'display', 'none');
  26358. };
  26359. return {
  26360. isVisible: isVisible,
  26361. isPositionedAtTop: isPositionedAtTop,
  26362. show: show,
  26363. hide: hide,
  26364. update: updateChromeUi,
  26365. updateMode: updateMode,
  26366. repositionPopups: repositionPopups$1
  26367. };
  26368. };
  26369. var getTargetPosAndBounds = function (targetElm, isToolbarTop) {
  26370. var bounds = box(targetElm);
  26371. return {
  26372. pos: isToolbarTop ? bounds.y : bounds.bottom,
  26373. bounds: bounds
  26374. };
  26375. };
  26376. var setupEvents$1 = function (editor, targetElm, ui) {
  26377. var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()));
  26378. var resizeContent = function (e) {
  26379. var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds;
  26380. var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds;
  26381. var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width;
  26382. prevPosAndBounds.set({
  26383. pos: pos,
  26384. bounds: bounds
  26385. });
  26386. if (hasResized) {
  26387. fireResizeContent(editor, e);
  26388. }
  26389. if (ui.isVisible()) {
  26390. if (prevPos !== pos) {
  26391. ui.update(true);
  26392. } else if (hasResized) {
  26393. ui.updateMode();
  26394. ui.repositionPopups();
  26395. }
  26396. }
  26397. };
  26398. editor.on('activate', ui.show);
  26399. editor.on('deactivate', ui.hide);
  26400. editor.on('SkinLoaded ResizeWindow', function () {
  26401. return ui.update(true);
  26402. });
  26403. editor.on('NodeChange keydown', function (e) {
  26404. global$2.requestAnimationFrame(function () {
  26405. return resizeContent(e);
  26406. });
  26407. });
  26408. editor.on('ScrollWindow', function () {
  26409. return ui.updateMode();
  26410. });
  26411. var elementLoad = unbindable();
  26412. elementLoad.set(capture$1(Element.fromDom(editor.getBody()), 'load', resizeContent));
  26413. editor.on('remove', function () {
  26414. elementLoad.clear();
  26415. });
  26416. };
  26417. var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) {
  26418. var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer;
  26419. var floatContainer = Cell(null);
  26420. var targetElm = Element.fromDom(args.targetNode);
  26421. var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer);
  26422. inline(editor);
  26423. var render = function () {
  26424. if (floatContainer.get()) {
  26425. ui.show();
  26426. return;
  26427. }
  26428. floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie());
  26429. var uiContainer = getUiContainer(editor);
  26430. attachSystem(uiContainer, mothership);
  26431. attachSystem(uiContainer, uiMothership);
  26432. setToolbar(editor, uiComponents, rawUiConfig, backstage);
  26433. OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig));
  26434. ui.show();
  26435. setupEvents$1(editor, targetElm, ui);
  26436. editor.nodeChanged();
  26437. };
  26438. editor.on('focus', render);
  26439. editor.on('blur hide', ui.hide);
  26440. editor.on('init', function () {
  26441. if (editor.hasFocus()) {
  26442. render();
  26443. }
  26444. });
  26445. setupReadonlyModeSwitch(editor, uiComponents);
  26446. return { editorContainer: outerContainer.element().dom() };
  26447. };
  26448. var Inline = /*#__PURE__*/Object.freeze({
  26449. __proto__: null,
  26450. render: render$1
  26451. });
  26452. var register$5 = function (editor) {
  26453. var alignToolbarButtons = [
  26454. {
  26455. name: 'alignleft',
  26456. text: 'Align left',
  26457. cmd: 'JustifyLeft',
  26458. icon: 'align-left'
  26459. },
  26460. {
  26461. name: 'aligncenter',
  26462. text: 'Align center',
  26463. cmd: 'JustifyCenter',
  26464. icon: 'align-center'
  26465. },
  26466. {
  26467. name: 'alignright',
  26468. text: 'Align right',
  26469. cmd: 'JustifyRight',
  26470. icon: 'align-right'
  26471. },
  26472. {
  26473. name: 'alignjustify',
  26474. text: 'Justify',
  26475. cmd: 'JustifyFull',
  26476. icon: 'align-justify'
  26477. }
  26478. ];
  26479. global$e.each(alignToolbarButtons, function (item) {
  26480. editor.ui.registry.addToggleButton(item.name, {
  26481. tooltip: item.text,
  26482. onAction: function () {
  26483. return editor.execCommand(item.cmd);
  26484. },
  26485. icon: item.icon,
  26486. onSetup: onSetupFormatToggle(editor, item.name)
  26487. });
  26488. });
  26489. var alignNoneToolbarButton = {
  26490. name: 'alignnone',
  26491. text: 'No alignment',
  26492. cmd: 'JustifyNone',
  26493. icon: 'align-none'
  26494. };
  26495. editor.ui.registry.addButton(alignNoneToolbarButton.name, {
  26496. tooltip: alignNoneToolbarButton.text,
  26497. onAction: function () {
  26498. return editor.execCommand(alignNoneToolbarButton.cmd);
  26499. },
  26500. icon: alignNoneToolbarButton.icon
  26501. });
  26502. };
  26503. var toggleFormat = function (editor, fmt) {
  26504. return function () {
  26505. editor.execCommand('mceToggleFormat', false, fmt);
  26506. };
  26507. };
  26508. var registerFormatButtons = function (editor) {
  26509. global$e.each([
  26510. {
  26511. name: 'bold',
  26512. text: 'Bold',
  26513. icon: 'bold'
  26514. },
  26515. {
  26516. name: 'italic',
  26517. text: 'Italic',
  26518. icon: 'italic'
  26519. },
  26520. {
  26521. name: 'underline',
  26522. text: 'Underline',
  26523. icon: 'underline'
  26524. },
  26525. {
  26526. name: 'strikethrough',
  26527. text: 'Strikethrough',
  26528. icon: 'strike-through'
  26529. },
  26530. {
  26531. name: 'subscript',
  26532. text: 'Subscript',
  26533. icon: 'subscript'
  26534. },
  26535. {
  26536. name: 'superscript',
  26537. text: 'Superscript',
  26538. icon: 'superscript'
  26539. }
  26540. ], function (btn, _idx) {
  26541. editor.ui.registry.addToggleButton(btn.name, {
  26542. tooltip: btn.text,
  26543. icon: btn.icon,
  26544. onSetup: onSetupFormatToggle(editor, btn.name),
  26545. onAction: toggleFormat(editor, btn.name)
  26546. });
  26547. });
  26548. for (var i = 1; i <= 6; i++) {
  26549. var name_1 = 'h' + i;
  26550. editor.ui.registry.addToggleButton(name_1, {
  26551. text: name_1.toUpperCase(),
  26552. tooltip: 'Heading ' + i,
  26553. onSetup: onSetupFormatToggle(editor, name_1),
  26554. onAction: toggleFormat(editor, name_1)
  26555. });
  26556. }
  26557. };
  26558. var registerCommandButtons = function (editor) {
  26559. global$e.each([
  26560. {
  26561. name: 'cut',
  26562. text: 'Cut',
  26563. action: 'Cut',
  26564. icon: 'cut'
  26565. },
  26566. {
  26567. name: 'copy',
  26568. text: 'Copy',
  26569. action: 'Copy',
  26570. icon: 'copy'
  26571. },
  26572. {
  26573. name: 'paste',
  26574. text: 'Paste',
  26575. action: 'Paste',
  26576. icon: 'paste'
  26577. },
  26578. {
  26579. name: 'help',
  26580. text: 'Help',
  26581. action: 'mceHelp',
  26582. icon: 'help'
  26583. },
  26584. {
  26585. name: 'selectall',
  26586. text: 'Select all',
  26587. action: 'SelectAll',
  26588. icon: 'select-all'
  26589. },
  26590. {
  26591. name: 'newdocument',
  26592. text: 'New document',
  26593. action: 'mceNewDocument',
  26594. icon: 'new-document'
  26595. },
  26596. {
  26597. name: 'removeformat',
  26598. text: 'Clear formatting',
  26599. action: 'RemoveFormat',
  26600. icon: 'remove-formatting'
  26601. },
  26602. {
  26603. name: 'remove',
  26604. text: 'Remove',
  26605. action: 'Delete',
  26606. icon: 'remove'
  26607. }
  26608. ], function (btn) {
  26609. editor.ui.registry.addButton(btn.name, {
  26610. tooltip: btn.text,
  26611. icon: btn.icon,
  26612. onAction: function () {
  26613. return editor.execCommand(btn.action);
  26614. }
  26615. });
  26616. });
  26617. };
  26618. var registerCommandToggleButtons = function (editor) {
  26619. global$e.each([{
  26620. name: 'blockquote',
  26621. text: 'Blockquote',
  26622. action: 'mceBlockQuote',
  26623. icon: 'quote'
  26624. }], function (btn) {
  26625. editor.ui.registry.addToggleButton(btn.name, {
  26626. tooltip: btn.text,
  26627. icon: btn.icon,
  26628. onAction: function () {
  26629. return editor.execCommand(btn.action);
  26630. },
  26631. onSetup: onSetupFormatToggle(editor, btn.name)
  26632. });
  26633. });
  26634. };
  26635. var registerButtons = function (editor) {
  26636. registerFormatButtons(editor);
  26637. registerCommandButtons(editor);
  26638. registerCommandToggleButtons(editor);
  26639. };
  26640. var registerMenuItems = function (editor) {
  26641. global$e.each([
  26642. {
  26643. name: 'bold',
  26644. text: 'Bold',
  26645. action: 'Bold',
  26646. icon: 'bold',
  26647. shortcut: 'Meta+B'
  26648. },
  26649. {
  26650. name: 'italic',
  26651. text: 'Italic',
  26652. action: 'Italic',
  26653. icon: 'italic',
  26654. shortcut: 'Meta+I'
  26655. },
  26656. {
  26657. name: 'underline',
  26658. text: 'Underline',
  26659. action: 'Underline',
  26660. icon: 'underline',
  26661. shortcut: 'Meta+U'
  26662. },
  26663. {
  26664. name: 'strikethrough',
  26665. text: 'Strikethrough',
  26666. action: 'Strikethrough',
  26667. icon: 'strike-through',
  26668. shortcut: ''
  26669. },
  26670. {
  26671. name: 'subscript',
  26672. text: 'Subscript',
  26673. action: 'Subscript',
  26674. icon: 'subscript',
  26675. shortcut: ''
  26676. },
  26677. {
  26678. name: 'superscript',
  26679. text: 'Superscript',
  26680. action: 'Superscript',
  26681. icon: 'superscript',
  26682. shortcut: ''
  26683. },
  26684. {
  26685. name: 'removeformat',
  26686. text: 'Clear formatting',
  26687. action: 'RemoveFormat',
  26688. icon: 'remove-formatting',
  26689. shortcut: ''
  26690. },
  26691. {
  26692. name: 'newdocument',
  26693. text: 'New document',
  26694. action: 'mceNewDocument',
  26695. icon: 'new-document',
  26696. shortcut: ''
  26697. },
  26698. {
  26699. name: 'cut',
  26700. text: 'Cut',
  26701. action: 'Cut',
  26702. icon: 'cut',
  26703. shortcut: 'Meta+X'
  26704. },
  26705. {
  26706. name: 'copy',
  26707. text: 'Copy',
  26708. action: 'Copy',
  26709. icon: 'copy',
  26710. shortcut: 'Meta+C'
  26711. },
  26712. {
  26713. name: 'paste',
  26714. text: 'Paste',
  26715. action: 'Paste',
  26716. icon: 'paste',
  26717. shortcut: 'Meta+V'
  26718. },
  26719. {
  26720. name: 'selectall',
  26721. text: 'Select all',
  26722. action: 'SelectAll',
  26723. icon: 'select-all',
  26724. shortcut: 'Meta+A'
  26725. }
  26726. ], function (btn) {
  26727. editor.ui.registry.addMenuItem(btn.name, {
  26728. text: btn.text,
  26729. icon: btn.icon,
  26730. shortcut: btn.shortcut,
  26731. onAction: function () {
  26732. return editor.execCommand(btn.action);
  26733. }
  26734. });
  26735. });
  26736. editor.ui.registry.addMenuItem('codeformat', {
  26737. text: 'Code',
  26738. icon: 'sourcecode',
  26739. onAction: toggleFormat(editor, 'code')
  26740. });
  26741. };
  26742. var register$6 = function (editor) {
  26743. registerButtons(editor);
  26744. registerMenuItems(editor);
  26745. };
  26746. var toggleUndoRedoState = function (api, editor, type) {
  26747. var checkState = function () {
  26748. return editor.undoManager ? editor.undoManager[type]() : false;
  26749. };
  26750. var onUndoStateChange = function () {
  26751. api.setDisabled(editor.mode.isReadOnly() || !checkState());
  26752. };
  26753. api.setDisabled(!checkState());
  26754. editor.on('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26755. return function () {
  26756. return editor.off('Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', onUndoStateChange);
  26757. };
  26758. };
  26759. var registerMenuItems$1 = function (editor) {
  26760. editor.ui.registry.addMenuItem('undo', {
  26761. text: 'Undo',
  26762. icon: 'undo',
  26763. shortcut: 'Meta+Z',
  26764. onSetup: function (api) {
  26765. return toggleUndoRedoState(api, editor, 'hasUndo');
  26766. },
  26767. onAction: function () {
  26768. return editor.execCommand('undo');
  26769. }
  26770. });
  26771. editor.ui.registry.addMenuItem('redo', {
  26772. text: 'Redo',
  26773. icon: 'redo',
  26774. shortcut: 'Meta+Y',
  26775. onSetup: function (api) {
  26776. return toggleUndoRedoState(api, editor, 'hasRedo');
  26777. },
  26778. onAction: function () {
  26779. return editor.execCommand('redo');
  26780. }
  26781. });
  26782. };
  26783. var registerButtons$1 = function (editor) {
  26784. editor.ui.registry.addButton('undo', {
  26785. tooltip: 'Undo',
  26786. icon: 'undo',
  26787. onSetup: function (api) {
  26788. return toggleUndoRedoState(api, editor, 'hasUndo');
  26789. },
  26790. onAction: function () {
  26791. return editor.execCommand('undo');
  26792. }
  26793. });
  26794. editor.ui.registry.addButton('redo', {
  26795. tooltip: 'Redo',
  26796. icon: 'redo',
  26797. onSetup: function (api) {
  26798. return toggleUndoRedoState(api, editor, 'hasRedo');
  26799. },
  26800. onAction: function () {
  26801. return editor.execCommand('redo');
  26802. }
  26803. });
  26804. };
  26805. var register$7 = function (editor) {
  26806. registerMenuItems$1(editor);
  26807. registerButtons$1(editor);
  26808. };
  26809. var toggleVisualAidState = function (api, editor) {
  26810. api.setActive(editor.hasVisual);
  26811. var onVisualAid = function (e) {
  26812. api.setActive(e.hasVisual);
  26813. };
  26814. editor.on('VisualAid', onVisualAid);
  26815. return function () {
  26816. return editor.off('VisualAid', onVisualAid);
  26817. };
  26818. };
  26819. var registerMenuItems$2 = function (editor) {
  26820. editor.ui.registry.addToggleMenuItem('visualaid', {
  26821. text: 'Visual aids',
  26822. onSetup: function (api) {
  26823. return toggleVisualAidState(api, editor);
  26824. },
  26825. onAction: function () {
  26826. editor.execCommand('mceToggleVisualAid');
  26827. }
  26828. });
  26829. };
  26830. var registerToolbarButton = function (editor) {
  26831. editor.ui.registry.addButton('visualaid', {
  26832. tooltip: 'Visual aids',
  26833. text: 'Visual aids',
  26834. onAction: function () {
  26835. return editor.execCommand('mceToggleVisualAid');
  26836. }
  26837. });
  26838. };
  26839. var register$8 = function (editor) {
  26840. registerToolbarButton(editor);
  26841. registerMenuItems$2(editor);
  26842. };
  26843. var toggleOutdentState = function (api, editor) {
  26844. api.setDisabled(!editor.queryCommandState('outdent'));
  26845. var onNodeChange = function () {
  26846. api.setDisabled(!editor.queryCommandState('outdent'));
  26847. };
  26848. editor.on('NodeChange', onNodeChange);
  26849. return function () {
  26850. return editor.off('NodeChange', onNodeChange);
  26851. };
  26852. };
  26853. var registerButtons$2 = function (editor) {
  26854. editor.ui.registry.addButton('outdent', {
  26855. tooltip: 'Decrease indent',
  26856. icon: 'outdent',
  26857. onSetup: function (api) {
  26858. return toggleOutdentState(api, editor);
  26859. },
  26860. onAction: function () {
  26861. return editor.execCommand('outdent');
  26862. }
  26863. });
  26864. editor.ui.registry.addButton('indent', {
  26865. tooltip: 'Increase indent',
  26866. icon: 'indent',
  26867. onAction: function () {
  26868. return editor.execCommand('indent');
  26869. }
  26870. });
  26871. };
  26872. var register$9 = function (editor) {
  26873. registerButtons$2(editor);
  26874. };
  26875. var register$a = function (editor, backstage) {
  26876. alignSelectMenu(editor, backstage);
  26877. fontSelectMenu(editor, backstage);
  26878. styleSelectMenu(editor, backstage);
  26879. formatSelectMenu(editor, backstage);
  26880. fontsizeSelectMenu(editor, backstage);
  26881. };
  26882. var setup$8 = function (editor, backstage) {
  26883. register$5(editor);
  26884. register$6(editor);
  26885. register$a(editor, backstage);
  26886. register$7(editor);
  26887. register$1(editor);
  26888. register$8(editor);
  26889. register$9(editor);
  26890. };
  26891. var nu$d = function (x, y) {
  26892. return {
  26893. anchor: 'makeshift',
  26894. x: x,
  26895. y: y
  26896. };
  26897. };
  26898. var transpose$1 = function (pos, dx, dy) {
  26899. return nu$d(pos.x + dx, pos.y + dy);
  26900. };
  26901. var isTouchEvent$1 = function (e) {
  26902. return e.type === 'longpress' || e.type.indexOf('touch') === 0;
  26903. };
  26904. var fromPageXY = function (e) {
  26905. if (isTouchEvent$1(e)) {
  26906. var touch = e.touches[0];
  26907. return nu$d(touch.pageX, touch.pageY);
  26908. } else {
  26909. return nu$d(e.pageX, e.pageY);
  26910. }
  26911. };
  26912. var fromClientXY = function (e) {
  26913. if (isTouchEvent$1(e)) {
  26914. var touch = e.touches[0];
  26915. return nu$d(touch.clientX, touch.clientY);
  26916. } else {
  26917. return nu$d(e.clientX, e.clientY);
  26918. }
  26919. };
  26920. var transposeContentAreaContainer = function (element, pos) {
  26921. var containerPos = global$7.DOM.getPos(element);
  26922. return transpose$1(pos, containerPos.x, containerPos.y);
  26923. };
  26924. var getPointAnchor = function (editor, e) {
  26925. if (e.type === 'contextmenu' || e.type === 'longpress') {
  26926. if (editor.inline) {
  26927. return fromPageXY(e);
  26928. } else {
  26929. return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e));
  26930. }
  26931. } else {
  26932. return getSelectionAnchor(editor);
  26933. }
  26934. };
  26935. var getSelectionAnchor = function (editor) {
  26936. return {
  26937. anchor: 'selection',
  26938. root: Element.fromDom(editor.selection.getNode())
  26939. };
  26940. };
  26941. var getNodeAnchor$1 = function (editor) {
  26942. return {
  26943. anchor: 'node',
  26944. node: Option.some(Element.fromDom(editor.selection.getNode())),
  26945. root: Element.fromDom(editor.getBody())
  26946. };
  26947. };
  26948. var getAnchorSpec = function (editor, e, isTriggeredByKeyboardEvent) {
  26949. return isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  26950. };
  26951. var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  26952. var items = buildMenu();
  26953. var anchorSpec = getAnchorSpec(editor, e, isTriggeredByKeyboardEvent);
  26954. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) {
  26955. e.preventDefault();
  26956. InlineView.showMenuAt(contextmenu, anchorSpec, {
  26957. menu: { markers: markers$1('normal') },
  26958. data: menuData
  26959. });
  26960. });
  26961. };
  26962. var layouts = {
  26963. onLtr: function () {
  26964. return [
  26965. south$1,
  26966. southeast$1,
  26967. southwest$1,
  26968. northeast$1,
  26969. northwest$1,
  26970. north$1,
  26971. north$3,
  26972. south$3,
  26973. northeast$3,
  26974. southeast$3,
  26975. northwest$3,
  26976. southwest$3
  26977. ];
  26978. },
  26979. onRtl: function () {
  26980. return [
  26981. south$1,
  26982. southwest$1,
  26983. southeast$1,
  26984. northwest$1,
  26985. northeast$1,
  26986. north$1,
  26987. north$3,
  26988. south$3,
  26989. northwest$3,
  26990. southwest$3,
  26991. northeast$3,
  26992. southeast$3
  26993. ];
  26994. }
  26995. };
  26996. var bubbleSize$1 = 12;
  26997. var bubbleAlignments$2 = {
  26998. valignCentre: [],
  26999. alignCentre: [],
  27000. alignLeft: ['tox-pop--align-left'],
  27001. alignRight: ['tox-pop--align-right'],
  27002. right: ['tox-pop--right'],
  27003. left: ['tox-pop--left'],
  27004. bottom: ['tox-pop--bottom'],
  27005. top: ['tox-pop--top']
  27006. };
  27007. var isTouchWithinSelection = function (editor, e) {
  27008. var selection = editor.selection;
  27009. if (selection.isCollapsed() || e.touches.length < 1) {
  27010. return false;
  27011. } else {
  27012. var touch_1 = e.touches[0];
  27013. var rng = selection.getRng();
  27014. var rngRectOpt = getFirstRect$1(editor.getWin(), Selection.domRange(rng));
  27015. return rngRectOpt.exists(function (rngRect) {
  27016. return rngRect.left() <= touch_1.clientX && rngRect.right() >= touch_1.clientX && rngRect.top() <= touch_1.clientY && rngRect.bottom() >= touch_1.clientY;
  27017. });
  27018. }
  27019. };
  27020. var getAnchorSpec$1 = function (editor, isTriggeredByKeyboardEvent, e) {
  27021. var anchorSpec = isTriggeredByKeyboardEvent ? getNodeAnchor$1(editor) : getPointAnchor(editor, e);
  27022. return __assign({
  27023. bubble: nu$8(0, bubbleSize$1, bubbleAlignments$2),
  27024. layouts: layouts,
  27025. overrides: {
  27026. maxWidthFunction: expandable$1(),
  27027. maxHeightFunction: expandable()
  27028. }
  27029. }, anchorSpec);
  27030. };
  27031. var setupiOSOverrides = function (editor) {
  27032. var originalSelection = editor.selection.getRng();
  27033. var selectionReset = function () {
  27034. global$2.setEditorTimeout(editor, function () {
  27035. editor.selection.setRng(originalSelection);
  27036. }, 10);
  27037. unbindEventListeners();
  27038. };
  27039. editor.once('touchend', selectionReset);
  27040. var preventMousedown = function (e) {
  27041. e.preventDefault();
  27042. e.stopImmediatePropagation();
  27043. };
  27044. editor.on('mousedown', preventMousedown, true);
  27045. var clearSelectionReset = function () {
  27046. return unbindEventListeners();
  27047. };
  27048. editor.once('longpresscancel', clearSelectionReset);
  27049. var unbindEventListeners = function () {
  27050. editor.off('touchend', selectionReset);
  27051. editor.off('longpresscancel', clearSelectionReset);
  27052. editor.off('mousedown', preventMousedown);
  27053. };
  27054. };
  27055. var show = function (editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent, highlightImmediately) {
  27056. var anchorSpec = getAnchorSpec$1(editor, isTriggeredByKeyboardEvent, e);
  27057. build$2(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) {
  27058. e.preventDefault();
  27059. InlineView.showMenuWithinBounds(contextmenu, anchorSpec, {
  27060. menu: {
  27061. markers: markers$1('normal'),
  27062. highlightImmediately: highlightImmediately
  27063. },
  27064. data: menuData,
  27065. type: 'horizontal'
  27066. }, function () {
  27067. return Option.some(getContextToolbarBounds(editor, backstage.shared));
  27068. });
  27069. editor.fire(hideContextToolbarEvent);
  27070. });
  27071. };
  27072. var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent) {
  27073. var detection = detect$3();
  27074. var isiOS = detection.os.isiOS();
  27075. var isOSX = detection.os.isOSX();
  27076. var isAndroid = detection.os.isAndroid();
  27077. var isTouch = detection.deviceType.isTouch();
  27078. var shouldHighlightImmediately = function () {
  27079. return !(isAndroid || isiOS || isOSX && isTouch);
  27080. };
  27081. var open = function () {
  27082. var items = buildMenu();
  27083. show(editor, e, items, backstage, contextmenu, isTriggeredByKeyboardEvent, shouldHighlightImmediately());
  27084. };
  27085. if ((isOSX || isiOS) && !isTriggeredByKeyboardEvent) {
  27086. var openiOS_1 = function () {
  27087. setupiOSOverrides(editor);
  27088. open();
  27089. };
  27090. if (isTouchWithinSelection(editor, e)) {
  27091. openiOS_1();
  27092. } else {
  27093. editor.once('selectionchange', openiOS_1);
  27094. editor.once('touchend', function () {
  27095. return editor.off('selectionchange', openiOS_1);
  27096. });
  27097. }
  27098. } else {
  27099. if (isAndroid && !isTriggeredByKeyboardEvent) {
  27100. editor.selection.setCursorLocation(e.target, 0);
  27101. }
  27102. open();
  27103. }
  27104. };
  27105. var patchPipeConfig = function (config) {
  27106. return typeof config === 'string' ? config.split(/[ ,]/) : config;
  27107. };
  27108. var shouldNeverUseNative = function (editor) {
  27109. return editor.settings.contextmenu_never_use_native || false;
  27110. };
  27111. var getMenuItems = function (editor, name, defaultItems) {
  27112. var contextMenus = editor.ui.registry.getAll().contextMenus;
  27113. return get(editor.settings, name).map(patchPipeConfig).getOrThunk(function () {
  27114. return filter(patchPipeConfig(defaultItems), function (item) {
  27115. return has(contextMenus, item);
  27116. });
  27117. });
  27118. };
  27119. var isContextMenuDisabled = function (editor) {
  27120. return editor.getParam('contextmenu') === false;
  27121. };
  27122. var getContextMenu = function (editor) {
  27123. return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen');
  27124. };
  27125. var isSeparator$1 = function (item) {
  27126. return isString(item) ? item === '|' : item.type === 'separator';
  27127. };
  27128. var separator$3 = { type: 'separator' };
  27129. var makeContextItem = function (item) {
  27130. if (isString(item)) {
  27131. return item;
  27132. } else {
  27133. switch (item.type) {
  27134. case 'separator':
  27135. return separator$3;
  27136. case 'submenu':
  27137. return {
  27138. type: 'nestedmenuitem',
  27139. text: item.text,
  27140. icon: item.icon,
  27141. getSubmenuItems: function () {
  27142. var items = item.getSubmenuItems();
  27143. if (isString(items)) {
  27144. return items;
  27145. } else {
  27146. return map(items, makeContextItem);
  27147. }
  27148. }
  27149. };
  27150. default:
  27151. return {
  27152. type: 'menuitem',
  27153. text: item.text,
  27154. icon: item.icon,
  27155. onAction: noarg(item.onAction)
  27156. };
  27157. }
  27158. }
  27159. };
  27160. var addContextMenuGroup = function (xs, groupItems) {
  27161. if (groupItems.length === 0) {
  27162. return xs;
  27163. }
  27164. var lastMenuItem = last(xs).filter(function (item) {
  27165. return !isSeparator$1(item);
  27166. });
  27167. var before = lastMenuItem.fold(function () {
  27168. return [];
  27169. }, function (_) {
  27170. return [separator$3];
  27171. });
  27172. return xs.concat(before).concat(groupItems).concat([separator$3]);
  27173. };
  27174. var generateContextMenu = function (contextMenus, menuConfig, selectedElement) {
  27175. var sections = foldl(menuConfig, function (acc, name) {
  27176. if (has(contextMenus, name)) {
  27177. var items = contextMenus[name].update(selectedElement);
  27178. if (isString(items)) {
  27179. return addContextMenuGroup(acc, items.split(' '));
  27180. } else if (items.length > 0) {
  27181. var allItems = map(items, makeContextItem);
  27182. return addContextMenuGroup(acc, allItems);
  27183. } else {
  27184. return acc;
  27185. }
  27186. } else {
  27187. return acc.concat([name]);
  27188. }
  27189. }, []);
  27190. if (sections.length > 0 && isSeparator$1(sections[sections.length - 1])) {
  27191. sections.pop();
  27192. }
  27193. return sections;
  27194. };
  27195. var isNativeOverrideKeyEvent = function (editor, e) {
  27196. return e.ctrlKey && !shouldNeverUseNative(editor);
  27197. };
  27198. var isTriggeredByKeyboard = function (editor, e) {
  27199. return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === '');
  27200. };
  27201. var setup$9 = function (editor, lazySink, backstage) {
  27202. var detection = detect$3();
  27203. var isTouch = detection.deviceType.isTouch;
  27204. var contextmenu = build$1(InlineView.sketch({
  27205. dom: { tag: 'div' },
  27206. lazySink: lazySink,
  27207. onEscape: function () {
  27208. return editor.focus();
  27209. },
  27210. onShow: function () {
  27211. return backstage.setContextMenuState(true);
  27212. },
  27213. onHide: function () {
  27214. return backstage.setContextMenuState(false);
  27215. },
  27216. fireDismissalEventInstead: {},
  27217. inlineBehaviours: derive$1([config('dismissContextMenu', [run(dismissRequested(), function (comp, _se) {
  27218. Sandboxing.close(comp);
  27219. editor.focus();
  27220. })])])
  27221. }));
  27222. var hideContextMenu = function (_e) {
  27223. return InlineView.hide(contextmenu);
  27224. };
  27225. var showContextMenu = function (e) {
  27226. if (shouldNeverUseNative(editor)) {
  27227. e.preventDefault();
  27228. }
  27229. if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) {
  27230. return;
  27231. }
  27232. var isTriggeredByKeyboardEvent = isTriggeredByKeyboard(editor, e);
  27233. var buildMenu = function () {
  27234. var selectedElement = isTriggeredByKeyboardEvent ? editor.selection.getStart(true) : e.target;
  27235. var registry = editor.ui.registry.getAll();
  27236. var menuConfig = getContextMenu(editor);
  27237. return generateContextMenu(registry.contextMenus, menuConfig, selectedElement);
  27238. };
  27239. var initAndShow$2 = isTouch() ? initAndShow$1 : initAndShow;
  27240. initAndShow$2(editor, e, buildMenu, backstage, contextmenu, isTriggeredByKeyboardEvent);
  27241. };
  27242. editor.on('init', function () {
  27243. var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow');
  27244. editor.on(hideEvents, hideContextMenu);
  27245. editor.on('longpress contextmenu', showContextMenu);
  27246. });
  27247. };
  27248. var adt$c = Adt.generate([
  27249. {
  27250. offset: [
  27251. 'x',
  27252. 'y'
  27253. ]
  27254. },
  27255. {
  27256. absolute: [
  27257. 'x',
  27258. 'y'
  27259. ]
  27260. },
  27261. {
  27262. fixed: [
  27263. 'x',
  27264. 'y'
  27265. ]
  27266. }
  27267. ]);
  27268. var subtract = function (change) {
  27269. return function (point) {
  27270. return point.translate(-change.left(), -change.top());
  27271. };
  27272. };
  27273. var add$4 = function (change) {
  27274. return function (point) {
  27275. return point.translate(change.left(), change.top());
  27276. };
  27277. };
  27278. var transform$1 = function (changes) {
  27279. return function (x, y) {
  27280. return foldl(changes, function (rest, f) {
  27281. return f(rest);
  27282. }, Position(x, y));
  27283. };
  27284. };
  27285. var asFixed = function (coord, scroll, origin) {
  27286. return coord.fold(transform$1([
  27287. add$4(origin),
  27288. subtract(scroll)
  27289. ]), transform$1([subtract(scroll)]), transform$1([]));
  27290. };
  27291. var asAbsolute = function (coord, scroll, origin) {
  27292. return coord.fold(transform$1([add$4(origin)]), transform$1([]), transform$1([add$4(scroll)]));
  27293. };
  27294. var asOffset = function (coord, scroll, origin) {
  27295. return coord.fold(transform$1([]), transform$1([subtract(origin)]), transform$1([
  27296. add$4(scroll),
  27297. subtract(origin)
  27298. ]));
  27299. };
  27300. var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) {
  27301. var a1 = asAbsolute(coord1, scroll, origin);
  27302. var a2 = asAbsolute(coord2, scroll, origin);
  27303. return Math.abs(a1.left() - a2.left()) <= xRange && Math.abs(a1.top() - a2.top()) <= yRange;
  27304. };
  27305. var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) {
  27306. var a1 = asAbsolute(coord1, scroll, origin);
  27307. var a2 = asAbsolute(coord2, scroll, origin);
  27308. var left = Math.abs(a1.left() - a2.left());
  27309. var top = Math.abs(a1.top() - a2.top());
  27310. return Position(left, top);
  27311. };
  27312. var toStyles = function (coord, scroll, origin) {
  27313. var stylesOpt = coord.fold(function (x, y) {
  27314. return {
  27315. position: Option.some('absolute'),
  27316. left: Option.some(x + 'px'),
  27317. top: Option.some(y + 'px')
  27318. };
  27319. }, function (x, y) {
  27320. return {
  27321. position: Option.some('absolute'),
  27322. left: Option.some(x - origin.left() + 'px'),
  27323. top: Option.some(y - origin.top() + 'px')
  27324. };
  27325. }, function (x, y) {
  27326. return {
  27327. position: Option.some('fixed'),
  27328. left: Option.some(x + 'px'),
  27329. top: Option.some(y + 'px')
  27330. };
  27331. });
  27332. return __assign({
  27333. right: Option.none(),
  27334. bottom: Option.none()
  27335. }, stylesOpt);
  27336. };
  27337. var translate$2 = function (coord, deltaX, deltaY) {
  27338. return coord.fold(function (x, y) {
  27339. return offset(x + deltaX, y + deltaY);
  27340. }, function (x, y) {
  27341. return absolute$3(x + deltaX, y + deltaY);
  27342. }, function (x, y) {
  27343. return fixed$1(x + deltaX, y + deltaY);
  27344. });
  27345. };
  27346. var absorb = function (partialCoord, originalCoord, scroll, origin) {
  27347. var absorbOne = function (stencil, nu) {
  27348. return function (optX, optY) {
  27349. var original = stencil(originalCoord, scroll, origin);
  27350. return nu(optX.getOr(original.left()), optY.getOr(original.top()));
  27351. };
  27352. };
  27353. return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute$3), absorbOne(asFixed, fixed$1));
  27354. };
  27355. var offset = adt$c.offset;
  27356. var absolute$3 = adt$c.absolute;
  27357. var fixed$1 = adt$c.fixed;
  27358. var parseAttrToInt = function (element, name) {
  27359. var value = get$2(element, name);
  27360. return isUndefined(value) ? NaN : parseInt(value, 10);
  27361. };
  27362. var get$e = function (component, snapsInfo) {
  27363. var element = component.element();
  27364. var x = parseAttrToInt(element, snapsInfo.leftAttr);
  27365. var y = parseAttrToInt(element, snapsInfo.topAttr);
  27366. return isNaN(x) || isNaN(y) ? Option.none() : Option.some(Position(x, y));
  27367. };
  27368. var set$8 = function (component, snapsInfo, pt) {
  27369. var element = component.element();
  27370. set$1(element, snapsInfo.leftAttr, pt.left() + 'px');
  27371. set$1(element, snapsInfo.topAttr, pt.top() + 'px');
  27372. };
  27373. var clear = function (component, snapsInfo) {
  27374. var element = component.element();
  27375. remove$1(element, snapsInfo.leftAttr);
  27376. remove$1(element, snapsInfo.topAttr);
  27377. };
  27378. var getCoords = function (component, snapInfo, coord, delta) {
  27379. return get$e(component, snapInfo).fold(function () {
  27380. return coord;
  27381. }, function (fixed) {
  27382. return fixed$1(fixed.left() + delta.left(), fixed.top() + delta.top());
  27383. });
  27384. };
  27385. var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) {
  27386. var newCoord = getCoords(component, snapInfo, coord, delta);
  27387. var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin);
  27388. var fixedCoord = asFixed(newCoord, scroll, origin);
  27389. set$8(component, snapInfo, fixedCoord);
  27390. return snap.fold(function () {
  27391. return {
  27392. coord: fixed$1(fixedCoord.left(), fixedCoord.top()),
  27393. extra: Option.none()
  27394. };
  27395. }, function (spanned) {
  27396. return {
  27397. coord: spanned.output,
  27398. extra: spanned.extra
  27399. };
  27400. });
  27401. };
  27402. var stopDrag = function (component, snapInfo) {
  27403. clear(component, snapInfo);
  27404. };
  27405. var findMatchingSnap = function (snaps, newCoord, scroll, origin) {
  27406. return findMap(snaps, function (snap) {
  27407. var sensor = snap.sensor;
  27408. var inRange = withinRange(newCoord, sensor, snap.range.left(), snap.range.top(), scroll, origin);
  27409. return inRange ? Option.some({
  27410. output: absorb(snap.output, newCoord, scroll, origin),
  27411. extra: snap.extra
  27412. }) : Option.none();
  27413. });
  27414. };
  27415. var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27416. var snaps = snapInfo.getSnapPoints(component);
  27417. var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin);
  27418. return matchSnap.orThunk(function () {
  27419. var bestSnap = foldl(snaps, function (acc, snap) {
  27420. var sensor = snap.sensor;
  27421. var deltas = getDeltas(newCoord, sensor, snap.range.left(), snap.range.top(), scroll, origin);
  27422. return acc.deltas.fold(function () {
  27423. return {
  27424. deltas: Option.some(deltas),
  27425. snap: Option.some(snap)
  27426. };
  27427. }, function (bestDeltas) {
  27428. var currAvg = (deltas.left() + deltas.top()) / 2;
  27429. var bestAvg = (bestDeltas.left() + bestDeltas.top()) / 2;
  27430. if (currAvg <= bestAvg) {
  27431. return {
  27432. deltas: Option.some(deltas),
  27433. snap: Option.some(snap)
  27434. };
  27435. } else {
  27436. return acc;
  27437. }
  27438. });
  27439. }, {
  27440. deltas: Option.none(),
  27441. snap: Option.none()
  27442. });
  27443. return bestSnap.snap.map(function (snap) {
  27444. return {
  27445. output: absorb(snap.output, newCoord, scroll, origin),
  27446. extra: snap.extra
  27447. };
  27448. });
  27449. });
  27450. };
  27451. var findSnap = function (component, snapInfo, newCoord, scroll, origin) {
  27452. var snaps = snapInfo.getSnapPoints(component);
  27453. return findMatchingSnap(snaps, newCoord, scroll, origin);
  27454. };
  27455. var snapTo = function (snap, scroll, origin) {
  27456. return {
  27457. coord: absorb(snap.output, snap.output, scroll, origin),
  27458. extra: snap.extra
  27459. };
  27460. };
  27461. var snapTo$1 = function (component, dragConfig, _state, snap) {
  27462. var target = dragConfig.getTarget(component.element());
  27463. if (dragConfig.repositionTarget) {
  27464. var doc = owner(component.element());
  27465. var scroll = get$8(doc);
  27466. var origin = getOrigin(target);
  27467. var snapPin = snapTo(snap, scroll, origin);
  27468. var styles = toStyles(snapPin.coord, scroll, origin);
  27469. setOptions(target, styles);
  27470. }
  27471. };
  27472. var DraggingApis = /*#__PURE__*/Object.freeze({
  27473. __proto__: null,
  27474. snapTo: snapTo$1
  27475. });
  27476. var initialAttribute = 'data-initial-z-index';
  27477. var resetZIndex = function (blocker) {
  27478. parent(blocker.element()).filter(isElement).each(function (root) {
  27479. getOpt(root, initialAttribute).fold(function () {
  27480. return remove$6(root, 'z-index');
  27481. }, function (zIndex) {
  27482. return set$2(root, 'z-index', zIndex);
  27483. });
  27484. remove$1(root, initialAttribute);
  27485. });
  27486. };
  27487. var changeZIndex = function (blocker) {
  27488. parent(blocker.element()).filter(isElement).each(function (root) {
  27489. getRaw(root, 'z-index').each(function (zindex) {
  27490. set$1(root, initialAttribute, zindex);
  27491. });
  27492. set$2(root, 'z-index', get$4(blocker.element(), 'z-index'));
  27493. });
  27494. };
  27495. var instigate = function (anyComponent, blocker) {
  27496. anyComponent.getSystem().addToGui(blocker);
  27497. changeZIndex(blocker);
  27498. };
  27499. var discard = function (blocker) {
  27500. resetZIndex(blocker);
  27501. blocker.getSystem().removeFromGui(blocker);
  27502. };
  27503. var createComponent = function (component, blockerClass, blockerEvents) {
  27504. return component.getSystem().build(Container.sketch({
  27505. dom: {
  27506. styles: {
  27507. 'left': '0px',
  27508. 'top': '0px',
  27509. 'width': '100%',
  27510. 'height': '100%',
  27511. 'position': 'fixed',
  27512. 'z-index': '1000000000000000'
  27513. },
  27514. classes: [blockerClass]
  27515. },
  27516. events: blockerEvents
  27517. }));
  27518. };
  27519. var SnapSchema = optionObjOf('snaps', [
  27520. strict$1('getSnapPoints'),
  27521. onHandler('onSensor'),
  27522. strict$1('leftAttr'),
  27523. strict$1('topAttr'),
  27524. defaulted$1('lazyViewport', win),
  27525. defaulted$1('mustSnap', false)
  27526. ]);
  27527. var schema$t = [
  27528. defaulted$1('useFixed', never),
  27529. strict$1('blockerClass'),
  27530. defaulted$1('getTarget', identity),
  27531. defaulted$1('onDrag', noop),
  27532. defaulted$1('repositionTarget', true),
  27533. defaulted$1('onDrop', noop),
  27534. defaultedFunction('getBounds', win),
  27535. SnapSchema
  27536. ];
  27537. var getCurrentCoord = function (target) {
  27538. return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) {
  27539. var nu = position === 'fixed' ? fixed$1 : offset;
  27540. return nu(parseInt(left, 10), parseInt(top, 10));
  27541. }).getOrThunk(function () {
  27542. var location = absolute(target);
  27543. return absolute$3(location.left(), location.top());
  27544. });
  27545. };
  27546. var clampCoords = function (component, coords, scroll, origin, startData) {
  27547. var bounds = startData.bounds;
  27548. var absoluteCoord = asAbsolute(coords, scroll, origin);
  27549. var newX = clamp(absoluteCoord.left(), bounds.x, bounds.x + bounds.width - startData.width);
  27550. var newY = clamp(absoluteCoord.top(), bounds.y, bounds.y + bounds.height - startData.height);
  27551. var newCoords = absolute$3(newX, newY);
  27552. return coords.fold(function () {
  27553. var offset$1 = asOffset(newCoords, scroll, origin);
  27554. return offset(offset$1.left(), offset$1.top());
  27555. }, function () {
  27556. return newCoords;
  27557. }, function () {
  27558. var fixed = asFixed(newCoords, scroll, origin);
  27559. return fixed$1(fixed.left(), fixed.top());
  27560. });
  27561. };
  27562. var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) {
  27563. var newCoord = optSnaps.fold(function () {
  27564. var translated = translate$2(currentCoord, delta.left(), delta.top());
  27565. var fixedCoord = asFixed(translated, scroll, origin);
  27566. return fixed$1(fixedCoord.left(), fixedCoord.top());
  27567. }, function (snapInfo) {
  27568. var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin);
  27569. snapping.extra.each(function (extra) {
  27570. snapInfo.onSensor(component, extra);
  27571. });
  27572. return snapping.coord;
  27573. });
  27574. return clampCoords(component, newCoord, scroll, origin, startData);
  27575. };
  27576. var dragBy = function (component, dragConfig, startData, delta) {
  27577. var target = dragConfig.getTarget(component.element());
  27578. if (dragConfig.repositionTarget) {
  27579. var doc = owner(component.element());
  27580. var scroll = get$8(doc);
  27581. var origin = getOrigin(target);
  27582. var currentCoord = getCurrentCoord(target);
  27583. var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll, origin, delta, startData);
  27584. var styles = toStyles(newCoord, scroll, origin);
  27585. setOptions(target, styles);
  27586. }
  27587. dragConfig.onDrag(component, target, delta);
  27588. };
  27589. var calcStartData = function (dragConfig, comp) {
  27590. return {
  27591. bounds: dragConfig.getBounds(),
  27592. height: getOuter$1(comp.element()),
  27593. width: getOuter$2(comp.element())
  27594. };
  27595. };
  27596. var move$1 = function (component, dragConfig, dragState, dragMode, event) {
  27597. var delta = dragState.update(dragMode, event);
  27598. var dragStartData = dragState.getStartData().getOrThunk(function () {
  27599. return calcStartData(dragConfig, component);
  27600. });
  27601. delta.each(function (dlt) {
  27602. dragBy(component, dragConfig, dragStartData, dlt);
  27603. });
  27604. };
  27605. var stop = function (component, blocker, dragConfig, dragState) {
  27606. blocker.each(discard);
  27607. dragConfig.snaps.each(function (snapInfo) {
  27608. stopDrag(component, snapInfo);
  27609. });
  27610. var target = dragConfig.getTarget(component.element());
  27611. dragState.reset();
  27612. dragConfig.onDrop(component, target);
  27613. };
  27614. var handlers = function (events) {
  27615. return function (dragConfig, dragState) {
  27616. var updateStartState = function (comp) {
  27617. dragState.setStartData(calcStartData(dragConfig, comp));
  27618. };
  27619. return derive(__spreadArrays([run(windowScroll(), function (comp) {
  27620. dragState.getStartData().each(function () {
  27621. return updateStartState(comp);
  27622. });
  27623. })], events(dragConfig, dragState, updateStartState)));
  27624. };
  27625. };
  27626. var init$c = function (dragApi) {
  27627. return derive([
  27628. run(mousedown(), dragApi.forceDrop),
  27629. run(mouseup(), dragApi.drop),
  27630. run(mousemove(), function (comp, simulatedEvent) {
  27631. dragApi.move(simulatedEvent.event());
  27632. }),
  27633. run(mouseout(), dragApi.delayDrop)
  27634. ]);
  27635. };
  27636. var getData$1 = function (event) {
  27637. return Option.from(Position(event.x(), event.y()));
  27638. };
  27639. var getDelta$1 = function (old, nu) {
  27640. return Position(nu.left() - old.left(), nu.top() - old.top());
  27641. };
  27642. var MouseData = /*#__PURE__*/Object.freeze({
  27643. __proto__: null,
  27644. getData: getData$1,
  27645. getDelta: getDelta$1
  27646. });
  27647. var events$g = function (dragConfig, dragState, updateStartState) {
  27648. return [run(mousedown(), function (component, simulatedEvent) {
  27649. var raw = simulatedEvent.event().raw();
  27650. if (raw.button !== 0) {
  27651. return;
  27652. }
  27653. simulatedEvent.stop();
  27654. var stop$1 = function () {
  27655. return stop(component, Option.some(blocker), dragConfig, dragState);
  27656. };
  27657. var delayDrop = DelayedFunction(stop$1, 200);
  27658. var dragApi = {
  27659. drop: stop$1,
  27660. delayDrop: delayDrop.schedule,
  27661. forceDrop: stop$1,
  27662. move: function (event) {
  27663. delayDrop.cancel();
  27664. move$1(component, dragConfig, dragState, MouseData, event);
  27665. }
  27666. };
  27667. var blocker = createComponent(component, dragConfig.blockerClass, init$c(dragApi));
  27668. var start = function () {
  27669. updateStartState(component);
  27670. instigate(component, blocker);
  27671. };
  27672. start();
  27673. })];
  27674. };
  27675. var schema$u = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$g) })]);
  27676. var init$d = function (dragApi) {
  27677. return derive([
  27678. run(touchstart(), dragApi.forceDrop),
  27679. run(touchend(), dragApi.drop),
  27680. run(touchcancel(), dragApi.drop),
  27681. run(touchmove(), function (comp, simulatedEvent) {
  27682. dragApi.move(simulatedEvent.event());
  27683. })
  27684. ]);
  27685. };
  27686. var getDataFrom = function (touches) {
  27687. var touch = touches[0];
  27688. return Option.some(Position(touch.clientX, touch.clientY));
  27689. };
  27690. var getData$2 = function (event) {
  27691. var raw = event.raw();
  27692. var touches = raw.touches;
  27693. return touches.length === 1 ? getDataFrom(touches) : Option.none();
  27694. };
  27695. var getDelta$2 = function (old, nu) {
  27696. return Position(nu.left() - old.left(), nu.top() - old.top());
  27697. };
  27698. var TouchData = /*#__PURE__*/Object.freeze({
  27699. __proto__: null,
  27700. getData: getData$2,
  27701. getDelta: getDelta$2
  27702. });
  27703. var events$h = function (dragConfig, dragState, updateStartState) {
  27704. var blockerCell = Cell(Option.none());
  27705. return [
  27706. run(touchstart(), function (component, simulatedEvent) {
  27707. simulatedEvent.stop();
  27708. var stop$1 = function () {
  27709. stop(component, blockerCell.get(), dragConfig, dragState);
  27710. blockerCell.set(Option.none());
  27711. };
  27712. var dragApi = {
  27713. drop: stop$1,
  27714. delayDrop: function () {
  27715. },
  27716. forceDrop: stop$1,
  27717. move: function (event) {
  27718. move$1(component, dragConfig, dragState, TouchData, event);
  27719. }
  27720. };
  27721. var blocker = createComponent(component, dragConfig.blockerClass, init$d(dragApi));
  27722. blockerCell.set(Option.some(blocker));
  27723. var start = function () {
  27724. updateStartState(component);
  27725. instigate(component, blocker);
  27726. };
  27727. start();
  27728. }),
  27729. run(touchmove(), function (component, simulatedEvent) {
  27730. simulatedEvent.stop();
  27731. move$1(component, dragConfig, dragState, TouchData, simulatedEvent.event());
  27732. }),
  27733. run(touchend(), function (component, simulatedEvent) {
  27734. simulatedEvent.stop();
  27735. stop(component, blockerCell.get(), dragConfig, dragState);
  27736. blockerCell.set(Option.none());
  27737. }),
  27738. run(touchcancel(), function (component) {
  27739. stop(component, blockerCell.get(), dragConfig, dragState);
  27740. blockerCell.set(Option.none());
  27741. })
  27742. ];
  27743. };
  27744. var schema$v = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$h) })]);
  27745. var events$i = function (dragConfig, dragState, updateStartState) {
  27746. return __spreadArrays(events$g(dragConfig, dragState, updateStartState), events$h(dragConfig, dragState, updateStartState));
  27747. };
  27748. var schema$w = __spreadArrays(schema$t, [output('dragger', { handlers: handlers(events$i) })]);
  27749. var mouse = schema$u;
  27750. var touch = schema$v;
  27751. var mouseOrTouch = schema$w;
  27752. var DraggingBranches = /*#__PURE__*/Object.freeze({
  27753. __proto__: null,
  27754. mouse: mouse,
  27755. touch: touch,
  27756. mouseOrTouch: mouseOrTouch
  27757. });
  27758. var init$e = function () {
  27759. var previous = Option.none();
  27760. var startData = Option.none();
  27761. var reset = function () {
  27762. previous = Option.none();
  27763. startData = Option.none();
  27764. };
  27765. var calculateDelta = function (mode, nu) {
  27766. var result = previous.map(function (old) {
  27767. return mode.getDelta(old, nu);
  27768. });
  27769. previous = Option.some(nu);
  27770. return result;
  27771. };
  27772. var update = function (mode, dragEvent) {
  27773. return mode.getData(dragEvent).bind(function (nuData) {
  27774. return calculateDelta(mode, nuData);
  27775. });
  27776. };
  27777. var setStartData = function (data) {
  27778. startData = Option.some(data);
  27779. };
  27780. var getStartData = function () {
  27781. return startData;
  27782. };
  27783. var readState = constant({});
  27784. return nu$5({
  27785. readState: readState,
  27786. reset: reset,
  27787. update: update,
  27788. getStartData: getStartData,
  27789. setStartData: setStartData
  27790. });
  27791. };
  27792. var DragState = /*#__PURE__*/Object.freeze({
  27793. __proto__: null,
  27794. init: init$e
  27795. });
  27796. var Dragging = createModes$1({
  27797. branchKey: 'mode',
  27798. branches: DraggingBranches,
  27799. name: 'dragging',
  27800. active: {
  27801. events: function (dragConfig, dragState) {
  27802. var dragger = dragConfig.dragger;
  27803. return dragger.handlers(dragConfig, dragState);
  27804. }
  27805. },
  27806. extra: {
  27807. snap: function (sConfig) {
  27808. return {
  27809. sensor: sConfig.sensor,
  27810. range: sConfig.range,
  27811. output: sConfig.output,
  27812. extra: Option.from(sConfig.extra)
  27813. };
  27814. }
  27815. },
  27816. state: DragState,
  27817. apis: DraggingApis
  27818. });
  27819. var snapWidth = 40;
  27820. var snapOffset = snapWidth / 2;
  27821. var calcSnap = function (selectorOpt, td, x, y, width, height) {
  27822. return selectorOpt.fold(function () {
  27823. return Dragging.snap({
  27824. sensor: absolute$3(x - snapOffset, y - snapOffset),
  27825. range: Position(width, height),
  27826. output: absolute$3(Option.some(x), Option.some(y)),
  27827. extra: { td: td }
  27828. });
  27829. }, function (selectorHandle) {
  27830. var sensorLeft = x - snapOffset;
  27831. var sensorTop = y - snapOffset;
  27832. var sensorWidth = snapWidth;
  27833. var sensorHeight = snapWidth;
  27834. var rect = selectorHandle.element().dom().getBoundingClientRect();
  27835. return Dragging.snap({
  27836. sensor: absolute$3(sensorLeft, sensorTop),
  27837. range: Position(sensorWidth, sensorHeight),
  27838. output: absolute$3(Option.some(x - rect.width / 2), Option.some(y - rect.height / 2)),
  27839. extra: { td: td }
  27840. });
  27841. });
  27842. };
  27843. var getSnapsConfig = function (getSnapPoints, cell, onChange) {
  27844. var isSameCell = function (cellOpt, td) {
  27845. return cellOpt.exists(function (currentTd) {
  27846. return eq$1(currentTd, td);
  27847. });
  27848. };
  27849. return {
  27850. getSnapPoints: getSnapPoints,
  27851. leftAttr: 'data-drag-left',
  27852. topAttr: 'data-drag-top',
  27853. onSensor: function (component, extra) {
  27854. var td = extra.td;
  27855. if (!isSameCell(cell.get(), td)) {
  27856. cell.set(Option.some(td));
  27857. onChange(td);
  27858. }
  27859. },
  27860. mustSnap: true
  27861. };
  27862. };
  27863. var createSelector = function (snaps) {
  27864. return record(Button.sketch({
  27865. dom: {
  27866. tag: 'div',
  27867. classes: ['tox-selector']
  27868. },
  27869. buttonBehaviours: derive$1([
  27870. Dragging.config({
  27871. mode: 'mouseOrTouch',
  27872. blockerClass: 'blocker',
  27873. snaps: snaps
  27874. }),
  27875. Unselecting.config({})
  27876. ]),
  27877. eventOrder: {
  27878. mousedown: [
  27879. 'dragging',
  27880. 'alloy.base.behaviour'
  27881. ],
  27882. touchstart: [
  27883. 'dragging',
  27884. 'alloy.base.behaviour'
  27885. ]
  27886. }
  27887. }));
  27888. };
  27889. var setup$a = function (editor, sink) {
  27890. var tlTds = Cell([]);
  27891. var brTds = Cell([]);
  27892. var isVisible = Cell(false);
  27893. var startCell = Cell(Option.none());
  27894. var finishCell = Cell(Option.none());
  27895. var getTopLeftSnap = function (td) {
  27896. var box = absolute$1(td);
  27897. return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height);
  27898. };
  27899. var getTopLeftSnaps = function () {
  27900. return map(tlTds.get(), function (td) {
  27901. return getTopLeftSnap(td);
  27902. });
  27903. };
  27904. var getBottomRightSnap = function (td) {
  27905. var box = absolute$1(td);
  27906. return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height);
  27907. };
  27908. var getBottomRightSnaps = function () {
  27909. return map(brTds.get(), function (td) {
  27910. return getBottomRightSnap(td);
  27911. });
  27912. };
  27913. var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) {
  27914. finishCell.get().each(function (finish) {
  27915. editor.fire('TableSelectorChange', {
  27916. start: start,
  27917. finish: finish
  27918. });
  27919. });
  27920. });
  27921. var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) {
  27922. startCell.get().each(function (start) {
  27923. editor.fire('TableSelectorChange', {
  27924. start: start,
  27925. finish: finish
  27926. });
  27927. });
  27928. });
  27929. var memTopLeft = createSelector(topLeftSnaps);
  27930. var memBottomRight = createSelector(bottomRightSnaps);
  27931. var topLeft = build$1(memTopLeft.asSpec());
  27932. var bottomRight = build$1(memBottomRight.asSpec());
  27933. var showOrHideHandle = function (selector, cell, isAbove, isBelow) {
  27934. var cellRect = cell.dom().getBoundingClientRect();
  27935. remove$6(selector.element(), 'display');
  27936. var viewportHeight = defaultView(Element.fromDom(editor.getBody())).dom().innerHeight;
  27937. var aboveViewport = isAbove(cellRect);
  27938. var belowViewport = isBelow(cellRect, viewportHeight);
  27939. if (aboveViewport || belowViewport) {
  27940. set$2(selector.element(), 'display', 'none');
  27941. }
  27942. };
  27943. var snapTo = function (selector, cell, getSnapConfig, pos) {
  27944. var snap = getSnapConfig(cell);
  27945. Dragging.snapTo(selector, snap);
  27946. var isAbove = function (rect) {
  27947. return rect[pos] < 0;
  27948. };
  27949. var isBelow = function (rect, viewportHeight) {
  27950. return rect[pos] > viewportHeight;
  27951. };
  27952. showOrHideHandle(selector, cell, isAbove, isBelow);
  27953. };
  27954. var snapTopLeft = function (cell) {
  27955. return snapTo(topLeft, cell, getTopLeftSnap, 'top');
  27956. };
  27957. var snapLastTopLeft = function () {
  27958. return startCell.get().each(snapTopLeft);
  27959. };
  27960. var snapBottomRight = function (cell) {
  27961. return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom');
  27962. };
  27963. var snapLastBottomRight = function () {
  27964. return finishCell.get().each(snapBottomRight);
  27965. };
  27966. if (detect$3().deviceType.isTouch()) {
  27967. editor.on('TableSelectionChange', function (e) {
  27968. if (!isVisible.get()) {
  27969. attach$1(sink, topLeft);
  27970. attach$1(sink, bottomRight);
  27971. isVisible.set(true);
  27972. }
  27973. startCell.set(Option.some(e.start));
  27974. finishCell.set(Option.some(e.finish));
  27975. e.otherCells.each(function (otherCells) {
  27976. tlTds.set(otherCells.upOrLeftCells);
  27977. brTds.set(otherCells.downOrRightCells);
  27978. snapTopLeft(e.start);
  27979. snapBottomRight(e.finish);
  27980. });
  27981. });
  27982. editor.on('ResizeEditor ResizeWindow ScrollContent', function () {
  27983. snapLastTopLeft();
  27984. snapLastBottomRight();
  27985. });
  27986. editor.on('TableSelectionClear', function () {
  27987. if (isVisible.get()) {
  27988. detach(topLeft);
  27989. detach(bottomRight);
  27990. isVisible.set(false);
  27991. }
  27992. startCell.set(Option.none());
  27993. finishCell.set(Option.none());
  27994. });
  27995. }
  27996. };
  27997. var ResizeTypes;
  27998. (function (ResizeTypes) {
  27999. ResizeTypes[ResizeTypes['None'] = 0] = 'None';
  28000. ResizeTypes[ResizeTypes['Both'] = 1] = 'Both';
  28001. ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical';
  28002. }(ResizeTypes || (ResizeTypes = {})));
  28003. var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) {
  28004. var dimensions = {};
  28005. dimensions.height = calcCappedSize(originalHeight + deltas.top(), getMinHeightSetting(editor), getMaxHeightSetting(editor));
  28006. if (resizeType === ResizeTypes.Both) {
  28007. dimensions.width = calcCappedSize(originalWidth + deltas.left(), getMinWidthSetting(editor), getMaxWidthSetting(editor));
  28008. }
  28009. return dimensions;
  28010. };
  28011. var resize$3 = function (editor, deltas, resizeType) {
  28012. var container = Element.fromDom(editor.getContainer());
  28013. var dimensions = getDimensions(editor, deltas, resizeType, get$6(container), get$7(container));
  28014. each$1(dimensions, function (val, dim) {
  28015. return set$2(container, dim, numToPx(val));
  28016. });
  28017. fireResizeEditor(editor);
  28018. };
  28019. var isHidden$1 = function (elm) {
  28020. if (elm.nodeType === 1) {
  28021. if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) {
  28022. return true;
  28023. }
  28024. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  28025. return true;
  28026. }
  28027. }
  28028. return false;
  28029. };
  28030. var renderElementPath = function (editor, settings, providersBackstage) {
  28031. if (!settings.delimiter) {
  28032. settings.delimiter = '\xBB';
  28033. }
  28034. var getDataPath = function (data) {
  28035. var parts = data || [];
  28036. var newPathElements = map(parts, function (part, index) {
  28037. return Button.sketch({
  28038. dom: {
  28039. tag: 'div',
  28040. classes: ['tox-statusbar__path-item'],
  28041. attributes: {
  28042. 'role': 'button',
  28043. 'data-index': index,
  28044. 'tab-index': -1,
  28045. 'aria-level': index + 1
  28046. },
  28047. innerHtml: part.name
  28048. },
  28049. action: function (_btn) {
  28050. editor.focus();
  28051. editor.selection.select(part.element);
  28052. editor.nodeChanged();
  28053. },
  28054. buttonBehaviours: derive$1([
  28055. DisablingConfigs.button(providersBackstage.isReadOnly),
  28056. receivingConfig()
  28057. ])
  28058. });
  28059. });
  28060. var divider = {
  28061. dom: {
  28062. tag: 'div',
  28063. classes: ['tox-statusbar__path-divider'],
  28064. attributes: { 'aria-hidden': true },
  28065. innerHtml: ' ' + settings.delimiter + ' '
  28066. }
  28067. };
  28068. return foldl(newPathElements.slice(1), function (acc, element) {
  28069. var newAcc = acc;
  28070. newAcc.push(divider);
  28071. newAcc.push(element);
  28072. return newAcc;
  28073. }, [newPathElements[0]]);
  28074. };
  28075. var updatePath = function (parents) {
  28076. var newPath = [];
  28077. var i = parents.length;
  28078. while (i-- > 0) {
  28079. var parent_1 = parents[i];
  28080. if (parent_1.nodeType === 1 && !isHidden$1(parent_1)) {
  28081. var args = editor.fire('ResolveName', {
  28082. name: parent_1.nodeName.toLowerCase(),
  28083. target: parent_1
  28084. });
  28085. if (!args.isDefaultPrevented()) {
  28086. newPath.push({
  28087. name: args.name,
  28088. element: parent_1
  28089. });
  28090. }
  28091. if (args.isPropagationStopped()) {
  28092. break;
  28093. }
  28094. }
  28095. }
  28096. return newPath;
  28097. };
  28098. return {
  28099. dom: {
  28100. tag: 'div',
  28101. classes: ['tox-statusbar__path'],
  28102. attributes: { role: 'navigation' }
  28103. },
  28104. behaviours: derive$1([
  28105. Keying.config({
  28106. mode: 'flow',
  28107. selector: 'div[role=button]'
  28108. }),
  28109. Disabling.config({ disabled: providersBackstage.isReadOnly }),
  28110. receivingConfig(),
  28111. Tabstopping.config({}),
  28112. Replacing.config({}),
  28113. config('elementPathEvents', [runOnAttached(function (comp, _e) {
  28114. editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () {
  28115. return Keying.focusIn(comp);
  28116. });
  28117. editor.on('NodeChange', function (e) {
  28118. var newPath = updatePath(e.parents);
  28119. if (newPath.length > 0) {
  28120. Replacing.set(comp, getDataPath(newPath));
  28121. } else {
  28122. Replacing.set(comp, []);
  28123. }
  28124. });
  28125. })])
  28126. ]),
  28127. components: []
  28128. };
  28129. };
  28130. var renderWordCount = function (editor, providersBackstage) {
  28131. var replaceCountText = function (comp, count, mode) {
  28132. return Replacing.set(comp, [text(providersBackstage.translate([
  28133. '{0} ' + mode,
  28134. count[mode]
  28135. ]))]);
  28136. };
  28137. return Button.sketch({
  28138. dom: {
  28139. tag: 'button',
  28140. classes: ['tox-statusbar__wordcount']
  28141. },
  28142. components: [],
  28143. buttonBehaviours: derive$1([
  28144. DisablingConfigs.button(providersBackstage.isReadOnly),
  28145. receivingConfig(),
  28146. Tabstopping.config({}),
  28147. Replacing.config({}),
  28148. Representing.config({
  28149. store: {
  28150. mode: 'memory',
  28151. initialValue: {
  28152. mode: 'words',
  28153. count: {
  28154. words: 0,
  28155. characters: 0
  28156. }
  28157. }
  28158. }
  28159. }),
  28160. config('wordcount-events', [
  28161. runOnExecute(function (comp) {
  28162. var currentVal = Representing.getValue(comp);
  28163. var newMode = currentVal.mode === 'words' ? 'characters' : 'words';
  28164. Representing.setValue(comp, {
  28165. mode: newMode,
  28166. count: currentVal.count
  28167. });
  28168. replaceCountText(comp, currentVal.count, newMode);
  28169. }),
  28170. runOnAttached(function (comp) {
  28171. editor.on('wordCountUpdate', function (e) {
  28172. var mode = Representing.getValue(comp).mode;
  28173. Representing.setValue(comp, {
  28174. mode: mode,
  28175. count: e.wordCount
  28176. });
  28177. replaceCountText(comp, e.wordCount, mode);
  28178. });
  28179. })
  28180. ])
  28181. ]),
  28182. eventOrder: {
  28183. 'alloy.execute': [
  28184. 'disabling',
  28185. 'alloy.base.behaviour',
  28186. 'wordcount-events'
  28187. ]
  28188. }
  28189. });
  28190. };
  28191. var renderStatusbar = function (editor, providersBackstage) {
  28192. var renderResizeHandlerIcon = function (resizeType) {
  28193. return {
  28194. dom: {
  28195. tag: 'div',
  28196. classes: ['tox-statusbar__resize-handle'],
  28197. attributes: {
  28198. 'title': providersBackstage.translate('Resize'),
  28199. 'aria-hidden': 'true'
  28200. },
  28201. innerHtml: get$d('resize-handle', providersBackstage.icons)
  28202. },
  28203. behaviours: derive$1([Dragging.config({
  28204. mode: 'mouse',
  28205. repositionTarget: false,
  28206. onDrag: function (comp, target, delta) {
  28207. resize$3(editor, delta, resizeType);
  28208. },
  28209. blockerClass: 'tox-blocker'
  28210. })])
  28211. };
  28212. };
  28213. var renderBranding = function () {
  28214. var label = global$5.translate([
  28215. 'Powered by {0}',
  28216. 'Tiny'
  28217. ]);
  28218. 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>';
  28219. return {
  28220. dom: {
  28221. tag: 'span',
  28222. classes: ['tox-statusbar__branding'],
  28223. innerHtml: linkHtml
  28224. }
  28225. };
  28226. };
  28227. var getResizeType = function (editor) {
  28228. var fallback = !contains$1(editor.settings.plugins, 'autoresize');
  28229. var resize = editor.getParam('resize', fallback);
  28230. if (resize === false) {
  28231. return ResizeTypes.None;
  28232. } else if (resize === 'both') {
  28233. return ResizeTypes.Both;
  28234. } else {
  28235. return ResizeTypes.Vertical;
  28236. }
  28237. };
  28238. var getTextComponents = function () {
  28239. var components = [];
  28240. if (editor.getParam('elementpath', true, 'boolean')) {
  28241. components.push(renderElementPath(editor, {}, providersBackstage));
  28242. }
  28243. if (contains$1(editor.settings.plugins, 'wordcount')) {
  28244. components.push(renderWordCount(editor, providersBackstage));
  28245. }
  28246. if (editor.getParam('branding', true, 'boolean')) {
  28247. components.push(renderBranding());
  28248. }
  28249. if (components.length > 0) {
  28250. return [{
  28251. dom: {
  28252. tag: 'div',
  28253. classes: ['tox-statusbar__text-container']
  28254. },
  28255. components: components
  28256. }];
  28257. }
  28258. return [];
  28259. };
  28260. var getComponents = function () {
  28261. var components = getTextComponents();
  28262. var resizeType = getResizeType(editor);
  28263. if (resizeType !== ResizeTypes.None) {
  28264. components.push(renderResizeHandlerIcon(resizeType));
  28265. }
  28266. return components;
  28267. };
  28268. return {
  28269. dom: {
  28270. tag: 'div',
  28271. classes: ['tox-statusbar']
  28272. },
  28273. components: getComponents()
  28274. };
  28275. };
  28276. var setup$b = function (editor) {
  28277. var _a;
  28278. var isInline = editor.inline;
  28279. var mode = isInline ? Inline : Iframe;
  28280. var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader;
  28281. var lazyOuterContainer = Option.none();
  28282. var platform = detect$3();
  28283. var isIE = platform.browser.isIE();
  28284. var platformClasses = isIE ? ['tox-platform-ie'] : [];
  28285. var isTouch = platform.deviceType.isTouch();
  28286. var touchPlatformClass = 'tox-platform-touch';
  28287. var deviceClasses = isTouch ? [touchPlatformClass] : [];
  28288. var isToolbarBottom = isToolbarLocationBottom(editor);
  28289. var dirAttributes = global$5.isRtl() ? { attributes: { dir: 'rtl' } } : {};
  28290. var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) };
  28291. var lazyHeader = function () {
  28292. return lazyOuterContainer.bind(OuterContainer.getHeader);
  28293. };
  28294. var isHeaderDocked = function () {
  28295. return header.isDocked(lazyHeader);
  28296. };
  28297. var sink = build$1({
  28298. dom: __assign({
  28299. tag: 'div',
  28300. classes: [
  28301. 'tox',
  28302. 'tox-silver-sink',
  28303. 'tox-tinymce-aux'
  28304. ].concat(platformClasses).concat(deviceClasses)
  28305. }, dirAttributes),
  28306. behaviours: derive$1([Positioning.config({
  28307. useFixed: function () {
  28308. return isHeaderDocked();
  28309. }
  28310. })])
  28311. });
  28312. var lazySink = function () {
  28313. return Result.value(sink);
  28314. };
  28315. var memAnchorBar = record({
  28316. dom: {
  28317. tag: 'div',
  28318. classes: ['tox-anchorbar']
  28319. }
  28320. });
  28321. var lazyAnchorBar = function () {
  28322. return lazyOuterContainer.bind(function (container) {
  28323. return memAnchorBar.getOpt(container);
  28324. }).getOrDie('Could not find a anchor bar element');
  28325. };
  28326. var lazyToolbar = function () {
  28327. return lazyOuterContainer.bind(function (container) {
  28328. return OuterContainer.getToolbar(container);
  28329. }).getOrDie('Could not find more toolbar element');
  28330. };
  28331. var lazyThrobber = function () {
  28332. return lazyOuterContainer.bind(function (container) {
  28333. return OuterContainer.getThrobber(container);
  28334. }).getOrDie('Could not find throbber element');
  28335. };
  28336. var backstage = init$8(sink, editor, lazyAnchorBar);
  28337. var partMenubar = OuterContainer.parts().menubar({
  28338. dom: {
  28339. tag: 'div',
  28340. classes: ['tox-menubar']
  28341. },
  28342. backstage: backstage,
  28343. onEscape: function () {
  28344. editor.focus();
  28345. }
  28346. });
  28347. var toolbarMode = getToolbarMode(editor);
  28348. var partToolbar = OuterContainer.parts().toolbar(__assign({
  28349. dom: {
  28350. tag: 'div',
  28351. classes: ['tox-toolbar']
  28352. },
  28353. getSink: lazySink,
  28354. providers: backstage.shared.providers,
  28355. onEscape: function () {
  28356. editor.focus();
  28357. },
  28358. type: toolbarMode,
  28359. lazyToolbar: lazyToolbar,
  28360. lazyHeader: function () {
  28361. return lazyHeader().getOrDie('Could not find header element');
  28362. }
  28363. }, verticalDirAttributes));
  28364. var partMultipleToolbar = OuterContainer.parts()['multiple-toolbar']({
  28365. dom: {
  28366. tag: 'div',
  28367. classes: ['tox-toolbar-overlord']
  28368. },
  28369. providers: backstage.shared.providers,
  28370. onEscape: function () {
  28371. },
  28372. type: toolbarMode
  28373. });
  28374. var partSocket = OuterContainer.parts().socket({
  28375. dom: {
  28376. tag: 'div',
  28377. classes: ['tox-edit-area']
  28378. }
  28379. });
  28380. var partSidebar = OuterContainer.parts().sidebar({
  28381. dom: {
  28382. tag: 'div',
  28383. classes: ['tox-sidebar']
  28384. }
  28385. });
  28386. var partThrobber = OuterContainer.parts().throbber({
  28387. dom: {
  28388. tag: 'div',
  28389. classes: ['tox-throbber']
  28390. },
  28391. backstage: backstage
  28392. });
  28393. var sb = editor.getParam('statusbar', true, 'boolean');
  28394. var statusbar = sb && !isInline ? Option.some(renderStatusbar(editor, backstage.shared.providers)) : Option.none();
  28395. var socketSidebarContainer = {
  28396. dom: {
  28397. tag: 'div',
  28398. classes: ['tox-sidebar-wrap']
  28399. },
  28400. components: [
  28401. partSocket,
  28402. partSidebar
  28403. ]
  28404. };
  28405. var hasMultipleToolbar = isMultipleToolbars(editor);
  28406. var hasToolbar = isToolbarEnabled(editor);
  28407. var hasMenubar = isMenubarEnabled(editor);
  28408. var getPartToolbar = function () {
  28409. if (hasMultipleToolbar) {
  28410. return [partMultipleToolbar];
  28411. } else if (hasToolbar) {
  28412. return [partToolbar];
  28413. } else {
  28414. return [];
  28415. }
  28416. };
  28417. var partHeader = OuterContainer.parts().header({
  28418. dom: __assign({
  28419. tag: 'div',
  28420. classes: ['tox-editor-header']
  28421. }, verticalDirAttributes),
  28422. components: flatten([
  28423. hasMenubar ? [partMenubar] : [],
  28424. getPartToolbar(),
  28425. useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()]
  28426. ]),
  28427. sticky: isStickyToolbar(editor),
  28428. editor: editor,
  28429. sharedBackstage: backstage.shared
  28430. });
  28431. var editorComponents = flatten([
  28432. isToolbarBottom ? [] : [partHeader],
  28433. isInline ? [] : [socketSidebarContainer],
  28434. isToolbarBottom ? [partHeader] : []
  28435. ]);
  28436. var editorContainer = {
  28437. dom: {
  28438. tag: 'div',
  28439. classes: ['tox-editor-container']
  28440. },
  28441. components: editorComponents
  28442. };
  28443. var containerComponents = flatten([
  28444. [editorContainer],
  28445. isInline ? [] : statusbar.toArray(),
  28446. [partThrobber]
  28447. ]);
  28448. var isHidden = isDistractionFree(editor);
  28449. var attributes = __assign(__assign({ role: 'application' }, global$5.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {});
  28450. var outerContainer = build$1(OuterContainer.sketch({
  28451. dom: {
  28452. tag: 'div',
  28453. classes: [
  28454. 'tox',
  28455. 'tox-tinymce'
  28456. ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses),
  28457. styles: __assign({ visibility: 'hidden' }, isHidden ? {
  28458. opacity: '0',
  28459. border: '0'
  28460. } : {}),
  28461. attributes: attributes
  28462. },
  28463. components: containerComponents,
  28464. behaviours: derive$1([Keying.config({
  28465. mode: 'cyclic',
  28466. 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'
  28467. })])
  28468. }));
  28469. lazyOuterContainer = Option.some(outerContainer);
  28470. editor.shortcuts.add('alt+F9', 'focus menubar', function () {
  28471. OuterContainer.focusMenubar(outerContainer);
  28472. });
  28473. editor.shortcuts.add('alt+F10', 'focus toolbar', function () {
  28474. OuterContainer.focusToolbar(outerContainer);
  28475. });
  28476. var mothership = takeover(outerContainer);
  28477. var uiMothership = takeover(sink);
  28478. setup$3(editor, mothership, uiMothership);
  28479. var getUi = function () {
  28480. var channels = {
  28481. broadcastAll: uiMothership.broadcast,
  28482. broadcastOn: uiMothership.broadcastOn,
  28483. register: function () {
  28484. }
  28485. };
  28486. return { channels: channels };
  28487. };
  28488. var setEditorSize = function () {
  28489. var parsedHeight = numToPx(getHeightWithFallback(editor));
  28490. var parsedWidth = numToPx(getWidthWithFallback(editor));
  28491. if (!editor.inline) {
  28492. if (isValidValue('div', 'width', parsedWidth)) {
  28493. set$2(outerContainer.element(), 'width', parsedWidth);
  28494. }
  28495. if (isValidValue('div', 'height', parsedHeight)) {
  28496. set$2(outerContainer.element(), 'height', parsedHeight);
  28497. } else {
  28498. set$2(outerContainer.element(), 'height', '200px');
  28499. }
  28500. }
  28501. return parsedHeight;
  28502. };
  28503. var renderUI = function () {
  28504. header.setup(editor, backstage.shared, lazyHeader);
  28505. setup$8(editor, backstage);
  28506. setup$9(editor, lazySink, backstage);
  28507. setup$6(editor);
  28508. setup$7(editor, lazyThrobber, backstage.shared);
  28509. map$1(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) {
  28510. editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig);
  28511. });
  28512. var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars;
  28513. var toolbarOpt = getMultipleToolbarsSetting(editor);
  28514. var rawUiConfig = {
  28515. menuItems: menuItems,
  28516. menus: !editor.settings.menu ? {} : map$1(editor.settings.menu, function (menu) {
  28517. return __assign(__assign({}, menu), { items: menu.items });
  28518. }),
  28519. menubar: editor.settings.menubar,
  28520. toolbar: toolbarOpt.getOrThunk(function () {
  28521. return editor.getParam('toolbar', true);
  28522. }),
  28523. allowToolbarGroups: toolbarMode === ToolbarMode.floating,
  28524. buttons: buttons,
  28525. sidebar: sidebars
  28526. };
  28527. register$4(editor, contextToolbars, sink, { backstage: backstage });
  28528. setup$a(editor, sink);
  28529. var elm = editor.getElement();
  28530. var height = setEditorSize();
  28531. var uiComponents = {
  28532. mothership: mothership,
  28533. uiMothership: uiMothership,
  28534. outerContainer: outerContainer
  28535. };
  28536. var args = {
  28537. targetNode: elm,
  28538. height: height
  28539. };
  28540. return mode.render(editor, uiComponents, rawUiConfig, backstage, args);
  28541. };
  28542. return {
  28543. mothership: mothership,
  28544. uiMothership: uiMothership,
  28545. backstage: backstage,
  28546. renderUI: renderUI,
  28547. getUi: getUi
  28548. };
  28549. };
  28550. var describedBy = function (describedElement, describeElement) {
  28551. var describeId = Option.from(get$2(describedElement, 'id')).fold(function () {
  28552. var id = generate$1('dialog-describe');
  28553. set$1(describeElement, 'id', id);
  28554. return id;
  28555. }, identity);
  28556. set$1(describedElement, 'aria-describedby', describeId);
  28557. };
  28558. var labelledBy = function (labelledElement, labelElement) {
  28559. var labelId = Option.from(get$2(labelledElement, 'id')).fold(function () {
  28560. var id = generate$1('dialog-label');
  28561. set$1(labelElement, 'id', id);
  28562. return id;
  28563. }, identity);
  28564. set$1(labelledElement, 'aria-labelledby', labelId);
  28565. };
  28566. var schema$x = constant([
  28567. strict$1('lazySink'),
  28568. option('dragBlockClass'),
  28569. defaultedFunction('getBounds', win),
  28570. defaulted$1('useTabstopAt', constant(true)),
  28571. defaulted$1('eventOrder', {}),
  28572. field$1('modalBehaviours', [Keying]),
  28573. onKeyboardHandler('onExecute'),
  28574. onStrictKeyboardHandler('onEscape')
  28575. ]);
  28576. var basic = { sketch: identity };
  28577. var parts$f = constant([
  28578. optional({
  28579. name: 'draghandle',
  28580. overrides: function (detail, spec) {
  28581. return {
  28582. behaviours: derive$1([Dragging.config({
  28583. mode: 'mouse',
  28584. getTarget: function (handle) {
  28585. return ancestor$2(handle, '[role="dialog"]').getOr(handle);
  28586. },
  28587. 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),
  28588. getBounds: detail.getDragBounds
  28589. })])
  28590. };
  28591. }
  28592. }),
  28593. required({
  28594. schema: [strict$1('dom')],
  28595. name: 'title'
  28596. }),
  28597. required({
  28598. factory: basic,
  28599. schema: [strict$1('dom')],
  28600. name: 'close'
  28601. }),
  28602. required({
  28603. factory: basic,
  28604. schema: [strict$1('dom')],
  28605. name: 'body'
  28606. }),
  28607. optional({
  28608. factory: basic,
  28609. schema: [strict$1('dom')],
  28610. name: 'footer'
  28611. }),
  28612. external$1({
  28613. factory: {
  28614. sketch: function (spec, detail) {
  28615. return __assign(__assign({}, spec), {
  28616. dom: detail.dom,
  28617. components: detail.components
  28618. });
  28619. }
  28620. },
  28621. schema: [
  28622. defaulted$1('dom', {
  28623. tag: 'div',
  28624. styles: {
  28625. position: 'fixed',
  28626. left: '0px',
  28627. top: '0px',
  28628. right: '0px',
  28629. bottom: '0px'
  28630. }
  28631. }),
  28632. defaulted$1('components', [])
  28633. ],
  28634. name: 'blocker'
  28635. })
  28636. ]);
  28637. var factory$i = function (detail, components, spec, externals) {
  28638. var dialogBusyEvent = generate$1('alloy.dialog.busy');
  28639. var dialogIdleEvent = generate$1('alloy.dialog.idle');
  28640. var busyBehaviours = derive$1([
  28641. Keying.config({
  28642. mode: 'special',
  28643. onTab: function () {
  28644. return Option.some(true);
  28645. },
  28646. onShiftTab: function () {
  28647. return Option.some(true);
  28648. }
  28649. }),
  28650. Focusing.config({})
  28651. ]);
  28652. var showDialog = function (dialog) {
  28653. var sink = detail.lazySink(dialog).getOrDie();
  28654. var busyComp = Cell(Option.none());
  28655. var externalBlocker = externals.blocker();
  28656. var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), {
  28657. components: externalBlocker.components.concat([premade$1(dialog)]),
  28658. behaviours: derive$1([
  28659. Focusing.config({}),
  28660. config('dialog-blocker-events', [
  28661. runOnSource(focusin(), function () {
  28662. Keying.focusIn(dialog);
  28663. }),
  28664. run(dialogIdleEvent, function (_blocker, _se) {
  28665. if (has$1(dialog.element(), 'aria-busy')) {
  28666. remove$1(dialog.element(), 'aria-busy');
  28667. busyComp.get().each(function (bc) {
  28668. return Replacing.remove(dialog, bc);
  28669. });
  28670. }
  28671. }),
  28672. run(dialogBusyEvent, function (blocker, se) {
  28673. set$1(dialog.element(), 'aria-busy', 'true');
  28674. var getBusySpec = se.event().getBusySpec();
  28675. busyComp.get().each(function (bc) {
  28676. Replacing.remove(dialog, bc);
  28677. });
  28678. var busySpec = getBusySpec(dialog, busyBehaviours);
  28679. var busy = blocker.getSystem().build(busySpec);
  28680. busyComp.set(Option.some(busy));
  28681. Replacing.append(dialog, premade$1(busy));
  28682. if (busy.hasConfigured(Keying)) {
  28683. Keying.focusIn(busy);
  28684. }
  28685. })
  28686. ])
  28687. ])
  28688. }));
  28689. attach$1(sink, blocker);
  28690. Keying.focusIn(dialog);
  28691. };
  28692. var hideDialog = function (dialog) {
  28693. parent(dialog.element()).each(function (blockerDom) {
  28694. dialog.getSystem().getByDom(blockerDom).each(function (blocker) {
  28695. detach(blocker);
  28696. });
  28697. });
  28698. };
  28699. var getDialogBody = function (dialog) {
  28700. return getPartOrDie(dialog, detail, 'body');
  28701. };
  28702. var getDialogFooter = function (dialog) {
  28703. return getPartOrDie(dialog, detail, 'footer');
  28704. };
  28705. var setBusy = function (dialog, getBusySpec) {
  28706. emitWith(dialog, dialogBusyEvent, { getBusySpec: getBusySpec });
  28707. };
  28708. var setIdle = function (dialog) {
  28709. emit(dialog, dialogIdleEvent);
  28710. };
  28711. var modalEventsId = generate$1('modal-events');
  28712. var eventOrder = __assign(__assign({}, detail.eventOrder), { 'alloy.system.attached': [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []) });
  28713. return {
  28714. uid: detail.uid,
  28715. dom: detail.dom,
  28716. components: components,
  28717. apis: {
  28718. show: showDialog,
  28719. hide: hideDialog,
  28720. getBody: getDialogBody,
  28721. getFooter: getDialogFooter,
  28722. setIdle: setIdle,
  28723. setBusy: setBusy
  28724. },
  28725. eventOrder: eventOrder,
  28726. domModification: {
  28727. attributes: {
  28728. 'role': 'dialog',
  28729. 'aria-modal': 'true'
  28730. }
  28731. },
  28732. behaviours: augment(detail.modalBehaviours, [
  28733. Replacing.config({}),
  28734. Keying.config({
  28735. mode: 'cyclic',
  28736. onEnter: detail.onExecute,
  28737. onEscape: detail.onEscape,
  28738. useTabstopAt: detail.useTabstopAt
  28739. }),
  28740. config(modalEventsId, [runOnAttached(function (c) {
  28741. labelledBy(c.element(), getPartOrDie(c, detail, 'title').element());
  28742. describedBy(c.element(), getPartOrDie(c, detail, 'body').element());
  28743. })])
  28744. ])
  28745. };
  28746. };
  28747. var ModalDialog = composite$1({
  28748. name: 'ModalDialog',
  28749. configFields: schema$x(),
  28750. partFields: parts$f(),
  28751. factory: factory$i,
  28752. apis: {
  28753. show: function (apis, dialog) {
  28754. apis.show(dialog);
  28755. },
  28756. hide: function (apis, dialog) {
  28757. apis.hide(dialog);
  28758. },
  28759. getBody: function (apis, dialog) {
  28760. return apis.getBody(dialog);
  28761. },
  28762. getFooter: function (apis, dialog) {
  28763. return apis.getFooter(dialog);
  28764. },
  28765. setBusy: function (apis, dialog, getBusySpec) {
  28766. apis.setBusy(dialog, getBusySpec);
  28767. },
  28768. setIdle: function (apis, dialog) {
  28769. apis.setIdle(dialog);
  28770. }
  28771. }
  28772. });
  28773. var alertBannerFields = [
  28774. strictString('type'),
  28775. strictString('text'),
  28776. strictStringEnum('level', [
  28777. 'info',
  28778. 'warn',
  28779. 'error',
  28780. 'success'
  28781. ]),
  28782. strictString('icon'),
  28783. defaulted$1('url', '')
  28784. ];
  28785. var alertBannerSchema = objOf(alertBannerFields);
  28786. var createBarFields = function (itemsField) {
  28787. return [
  28788. strictString('type'),
  28789. itemsField
  28790. ];
  28791. };
  28792. var buttonFields = [
  28793. strictString('type'),
  28794. strictString('text'),
  28795. defaultedBoolean('disabled', false),
  28796. defaultedBoolean('primary', false),
  28797. field('name', 'name', defaultedThunk(function () {
  28798. return generate$1('button-name');
  28799. }), string),
  28800. optionString('icon'),
  28801. defaultedBoolean('borderless', false)
  28802. ];
  28803. var buttonSchema = objOf(buttonFields);
  28804. var checkboxFields = [
  28805. strictString('type'),
  28806. strictString('name'),
  28807. strictString('label'),
  28808. defaultedBoolean('disabled', false)
  28809. ];
  28810. var checkboxSchema = objOf(checkboxFields);
  28811. var checkboxDataProcessor = boolean;
  28812. var formComponentFields = [
  28813. strictString('type'),
  28814. strictString('name')
  28815. ];
  28816. var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]);
  28817. var colorInputFields = formComponentWithLabelFields;
  28818. var colorInputSchema = objOf(colorInputFields);
  28819. var colorInputDataProcessor = string;
  28820. var colorPickerFields = formComponentWithLabelFields;
  28821. var colorPickerSchema = objOf(colorPickerFields);
  28822. var colorPickerDataProcessor = string;
  28823. var dropZoneFields = formComponentWithLabelFields;
  28824. var dropZoneSchema = objOf(dropZoneFields);
  28825. var dropZoneDataProcessor = arrOfVal();
  28826. var createGridFields = function (itemsField) {
  28827. return [
  28828. strictString('type'),
  28829. strictNumber('columns'),
  28830. itemsField
  28831. ];
  28832. };
  28833. var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]);
  28834. var iframeSchema = objOf(iframeFields);
  28835. var iframeDataProcessor = string;
  28836. var inputFields = formComponentWithLabelFields.concat([
  28837. optionString('inputMode'),
  28838. optionString('placeholder'),
  28839. defaultedBoolean('maximized', false),
  28840. defaultedBoolean('disabled', false)
  28841. ]);
  28842. var inputSchema = objOf(inputFields);
  28843. var inputDataProcessor = string;
  28844. var selectBoxFields = formComponentWithLabelFields.concat([
  28845. strictArrayOfObj('items', [
  28846. strictString('text'),
  28847. strictString('value')
  28848. ]),
  28849. defaultedNumber('size', 1),
  28850. defaultedBoolean('disabled', false)
  28851. ]);
  28852. var selectBoxSchema = objOf(selectBoxFields);
  28853. var selectBoxDataProcessor = string;
  28854. var sizeInputFields = formComponentWithLabelFields.concat([
  28855. defaultedBoolean('constrain', true),
  28856. defaultedBoolean('disabled', false)
  28857. ]);
  28858. var sizeInputSchema = objOf(sizeInputFields);
  28859. var sizeInputDataProcessor = objOf([
  28860. strictString('width'),
  28861. strictString('height')
  28862. ]);
  28863. var textAreaFields = formComponentWithLabelFields.concat([
  28864. optionString('placeholder'),
  28865. defaultedBoolean('maximized', false),
  28866. defaultedBoolean('disabled', false)
  28867. ]);
  28868. var textAreaSchema = objOf(textAreaFields);
  28869. var textAreaDataProcessor = string;
  28870. var urlInputFields = formComponentWithLabelFields.concat([
  28871. defaultedStringEnum('filetype', 'file', [
  28872. 'image',
  28873. 'media',
  28874. 'file'
  28875. ]),
  28876. defaulted$1('disabled', false)
  28877. ]);
  28878. var urlInputSchema = objOf(urlInputFields);
  28879. var urlInputDataProcessor = objOf([
  28880. strictString('value'),
  28881. defaulted$1('meta', {})
  28882. ]);
  28883. var customEditorFields = formComponentFields.concat([
  28884. defaultedString('tag', 'textarea'),
  28885. strictString('scriptId'),
  28886. strictString('scriptUrl'),
  28887. defaultedPostMsg('settings', undefined)
  28888. ]);
  28889. var customEditorFieldsOld = formComponentFields.concat([
  28890. defaultedString('tag', 'textarea'),
  28891. strictFunction('init')
  28892. ]);
  28893. var customEditorSchema = valueOf(function (v) {
  28894. return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () {
  28895. return asRaw('customeditor.new', objOfOnly(customEditorFields), v);
  28896. });
  28897. });
  28898. var customEditorDataProcessor = string;
  28899. var htmlPanelFields = [
  28900. strictString('type'),
  28901. strictString('html'),
  28902. defaultedStringEnum('presets', 'presentation', [
  28903. 'presentation',
  28904. 'document'
  28905. ])
  28906. ];
  28907. var htmlPanelSchema = objOf(htmlPanelFields);
  28908. var imageToolsFields = formComponentWithLabelFields.concat([strictOf('currentState', objOf([
  28909. strict$1('blob'),
  28910. strictString('url')
  28911. ]))]);
  28912. var imageToolsSchema = objOf(imageToolsFields);
  28913. var collectionFields = formComponentWithLabelFields.concat([defaulted$1('columns', 'auto')]);
  28914. var collectionSchema = objOf(collectionFields);
  28915. var collectionDataProcessor = arrOfObj$1([
  28916. strictString('value'),
  28917. strictString('text'),
  28918. strictString('icon')
  28919. ]);
  28920. var createLabelFields = function (itemsField) {
  28921. return [
  28922. strictString('type'),
  28923. strictString('label'),
  28924. itemsField
  28925. ];
  28926. };
  28927. var tableFields = [
  28928. strictString('type'),
  28929. strictArrayOf('header', string),
  28930. strictArrayOf('cells', arrOf(string))
  28931. ];
  28932. var tableSchema = objOf(tableFields);
  28933. var createItemsField = function (name) {
  28934. return field('items', 'items', strict(), arrOf(valueOf(function (v) {
  28935. return asRaw('Checking item of ' + name, itemSchema$2, v).fold(function (sErr) {
  28936. return Result.error(formatError(sErr));
  28937. }, function (passValue) {
  28938. return Result.value(passValue);
  28939. });
  28940. })));
  28941. };
  28942. var itemSchema$2 = valueThunkOf(function () {
  28943. return chooseProcessor('type', {
  28944. alertbanner: alertBannerSchema,
  28945. bar: objOf(createBarFields(createItemsField('bar'))),
  28946. button: buttonSchema,
  28947. checkbox: checkboxSchema,
  28948. colorinput: colorInputSchema,
  28949. colorpicker: colorPickerSchema,
  28950. dropzone: dropZoneSchema,
  28951. grid: objOf(createGridFields(createItemsField('grid'))),
  28952. iframe: iframeSchema,
  28953. input: inputSchema,
  28954. selectbox: selectBoxSchema,
  28955. sizeinput: sizeInputSchema,
  28956. textarea: textAreaSchema,
  28957. urlinput: urlInputSchema,
  28958. customeditor: customEditorSchema,
  28959. htmlpanel: htmlPanelSchema,
  28960. imagetools: imageToolsSchema,
  28961. collection: collectionSchema,
  28962. label: objOf(createLabelFields(createItemsField('label'))),
  28963. table: tableSchema,
  28964. panel: panelSchema
  28965. });
  28966. });
  28967. var panelFields = [
  28968. strictString('type'),
  28969. defaulted$1('classes', []),
  28970. strictArrayOf('items', itemSchema$2)
  28971. ];
  28972. var panelSchema = objOf(panelFields);
  28973. var tabFields = [
  28974. field('name', 'name', defaultedThunk(function () {
  28975. return generate$1('tab-name');
  28976. }), string),
  28977. strictString('title'),
  28978. strictArrayOf('items', itemSchema$2)
  28979. ];
  28980. var tabPanelFields = [
  28981. strictString('type'),
  28982. strictArrayOfObj('tabs', tabFields)
  28983. ];
  28984. var tabPanelSchema = objOf(tabPanelFields);
  28985. var dialogToggleMenuItemSchema = objOf([
  28986. strictString('type'),
  28987. strictString('name')
  28988. ].concat(commonMenuItemFields));
  28989. var dialogToggleMenuItemDataProcessor = boolean;
  28990. var baseButtonFields = [
  28991. field('name', 'name', defaultedThunk(function () {
  28992. return generate$1('button-name');
  28993. }), string),
  28994. optionString('icon'),
  28995. defaultedStringEnum('align', 'end', [
  28996. 'start',
  28997. 'end'
  28998. ]),
  28999. defaultedBoolean('primary', false),
  29000. defaultedBoolean('disabled', false)
  29001. ];
  29002. var dialogButtonFields = __spreadArrays(baseButtonFields, [strictString('text')]);
  29003. var normalButtonFields = __spreadArrays([strictStringEnum('type', [
  29004. 'submit',
  29005. 'cancel',
  29006. 'custom'
  29007. ])], dialogButtonFields);
  29008. var menuButtonFields = __spreadArrays([
  29009. strictStringEnum('type', ['menu']),
  29010. optionString('text'),
  29011. optionString('tooltip'),
  29012. optionString('icon'),
  29013. strictArrayOf('items', dialogToggleMenuItemSchema)
  29014. ], baseButtonFields);
  29015. var dialogButtonSchema = choose$1('type', {
  29016. submit: normalButtonFields,
  29017. cancel: normalButtonFields,
  29018. custom: normalButtonFields,
  29019. menu: menuButtonFields
  29020. });
  29021. var dialogButtonFields$1 = dialogButtonFields;
  29022. var dialogButtonSchema$1 = dialogButtonSchema;
  29023. var dialogSchema = objOf([
  29024. strictString('title'),
  29025. strictOf('body', chooseProcessor('type', {
  29026. panel: panelSchema,
  29027. tabpanel: tabPanelSchema
  29028. })),
  29029. defaultedString('size', 'normal'),
  29030. strictArrayOf('buttons', dialogButtonSchema$1),
  29031. defaulted$1('initialData', {}),
  29032. defaultedFunction('onAction', noop),
  29033. defaultedFunction('onChange', noop),
  29034. defaultedFunction('onSubmit', noop),
  29035. defaultedFunction('onClose', noop),
  29036. defaultedFunction('onCancel', noop),
  29037. defaulted$1('onTabChange', noop)
  29038. ]);
  29039. var createDialog = function (spec) {
  29040. return asRaw('dialog', dialogSchema, spec);
  29041. };
  29042. var getAllObjects = function (obj) {
  29043. if (isObject(obj)) {
  29044. return [obj].concat(bind(values(obj), getAllObjects));
  29045. } else if (isArray(obj)) {
  29046. return bind(obj, getAllObjects);
  29047. } else {
  29048. return [];
  29049. }
  29050. };
  29051. var isNamedItem = function (obj) {
  29052. return isString(obj.type) && isString(obj.name);
  29053. };
  29054. var dataProcessors = {
  29055. checkbox: checkboxDataProcessor,
  29056. colorinput: colorInputDataProcessor,
  29057. colorpicker: colorPickerDataProcessor,
  29058. dropzone: dropZoneDataProcessor,
  29059. input: inputDataProcessor,
  29060. iframe: iframeDataProcessor,
  29061. sizeinput: sizeInputDataProcessor,
  29062. selectbox: selectBoxDataProcessor,
  29063. size: sizeInputDataProcessor,
  29064. textarea: textAreaDataProcessor,
  29065. urlinput: urlInputDataProcessor,
  29066. customeditor: customEditorDataProcessor,
  29067. collection: collectionDataProcessor,
  29068. togglemenuitem: dialogToggleMenuItemDataProcessor
  29069. };
  29070. var getDataProcessor = function (item) {
  29071. return Option.from(dataProcessors[item.type]);
  29072. };
  29073. var getNamedItems = function (structure) {
  29074. return filter(getAllObjects(structure), isNamedItem);
  29075. };
  29076. var createDataValidator = function (structure) {
  29077. var namedItems = getNamedItems(structure);
  29078. var fields = bind(namedItems, function (item) {
  29079. return getDataProcessor(item).fold(function () {
  29080. return [];
  29081. }, function (schema) {
  29082. return [strictOf(item.name, schema)];
  29083. });
  29084. });
  29085. return objOf(fields);
  29086. };
  29087. var urlDialogButtonSchema = objOf(__spreadArrays([strictStringEnum('type', [
  29088. 'cancel',
  29089. 'custom'
  29090. ])], dialogButtonFields$1));
  29091. var urlDialogSchema = objOf([
  29092. strictString('title'),
  29093. strictString('url'),
  29094. optionNumber('height'),
  29095. optionNumber('width'),
  29096. optionArrayOf('buttons', urlDialogButtonSchema),
  29097. defaultedFunction('onAction', noop),
  29098. defaultedFunction('onCancel', noop),
  29099. defaultedFunction('onClose', noop),
  29100. defaultedFunction('onMessage', noop)
  29101. ]);
  29102. var createUrlDialog = function (spec) {
  29103. return asRaw('dialog', urlDialogSchema, spec);
  29104. };
  29105. var extract$1 = function (structure) {
  29106. var internalDialog = getOrDie(createDialog(structure));
  29107. var dataValidator = createDataValidator(structure);
  29108. var initialData = structure.initialData;
  29109. return {
  29110. internalDialog: internalDialog,
  29111. dataValidator: dataValidator,
  29112. initialData: initialData
  29113. };
  29114. };
  29115. var DialogManager = {
  29116. open: function (factory, structure) {
  29117. var extraction = extract$1(structure);
  29118. return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator);
  29119. },
  29120. openUrl: function (factory, structure) {
  29121. var internalDialog = getOrDie(createUrlDialog(structure));
  29122. return factory(internalDialog);
  29123. },
  29124. redial: function (structure) {
  29125. return extract$1(structure);
  29126. }
  29127. };
  29128. var toValidValues = function (values) {
  29129. var errors = [];
  29130. var result = {};
  29131. each$1(values, function (value, name) {
  29132. value.fold(function () {
  29133. errors.push(name);
  29134. }, function (v) {
  29135. result[name] = v;
  29136. });
  29137. });
  29138. return errors.length > 0 ? Result.error(errors) : Result.value(result);
  29139. };
  29140. var renderBodyPanel = function (spec, backstage) {
  29141. var memForm = record(Form.sketch(function (parts) {
  29142. return {
  29143. dom: {
  29144. tag: 'div',
  29145. classes: ['tox-form'].concat(spec.classes)
  29146. },
  29147. components: map(spec.items, function (item) {
  29148. return interpretInForm(parts, item, backstage);
  29149. })
  29150. };
  29151. }));
  29152. return {
  29153. dom: {
  29154. tag: 'div',
  29155. classes: ['tox-dialog__body']
  29156. },
  29157. components: [{
  29158. dom: {
  29159. tag: 'div',
  29160. classes: ['tox-dialog__body-content']
  29161. },
  29162. components: [memForm.asSpec()]
  29163. }],
  29164. behaviours: derive$1([
  29165. Keying.config({
  29166. mode: 'acyclic',
  29167. useTabstopAt: not(isPseudoStop)
  29168. }),
  29169. ComposingConfigs.memento(memForm),
  29170. RepresentingConfigs.memento(memForm, {
  29171. postprocess: function (formValue) {
  29172. return toValidValues(formValue).fold(function (err) {
  29173. domGlobals.console.error(err);
  29174. return {};
  29175. }, function (vals) {
  29176. return vals;
  29177. });
  29178. }
  29179. })
  29180. ])
  29181. };
  29182. };
  29183. var factory$j = function (detail, _spec) {
  29184. return {
  29185. uid: detail.uid,
  29186. dom: detail.dom,
  29187. components: detail.components,
  29188. events: events$7(detail.action),
  29189. behaviours: augment(detail.tabButtonBehaviours, [
  29190. Focusing.config({}),
  29191. Keying.config({
  29192. mode: 'execution',
  29193. useSpace: true,
  29194. useEnter: true
  29195. }),
  29196. Representing.config({
  29197. store: {
  29198. mode: 'memory',
  29199. initialValue: detail.value
  29200. }
  29201. })
  29202. ]),
  29203. domModification: detail.domModification
  29204. };
  29205. };
  29206. var TabButton = single$2({
  29207. name: 'TabButton',
  29208. configFields: [
  29209. defaulted$1('uid', undefined),
  29210. strict$1('value'),
  29211. field('dom', 'dom', mergeWithThunk(function () {
  29212. return {
  29213. attributes: {
  29214. 'role': 'tab',
  29215. 'id': generate$1('aria'),
  29216. 'aria-selected': 'false'
  29217. }
  29218. };
  29219. }), anyValue$1()),
  29220. option('action'),
  29221. defaulted$1('domModification', {}),
  29222. field$1('tabButtonBehaviours', [
  29223. Focusing,
  29224. Keying,
  29225. Representing
  29226. ]),
  29227. strict$1('view')
  29228. ],
  29229. factory: factory$j
  29230. });
  29231. var schema$y = constant([
  29232. strict$1('tabs'),
  29233. strict$1('dom'),
  29234. defaulted$1('clickToDismiss', false),
  29235. field$1('tabbarBehaviours', [
  29236. Highlighting,
  29237. Keying
  29238. ]),
  29239. markers([
  29240. 'tabClass',
  29241. 'selectedClass'
  29242. ])
  29243. ]);
  29244. var tabsPart = group({
  29245. factory: TabButton,
  29246. name: 'tabs',
  29247. unit: 'tab',
  29248. overrides: function (barDetail) {
  29249. var dismissTab$1 = function (tabbar, button) {
  29250. Highlighting.dehighlight(tabbar, button);
  29251. emitWith(tabbar, dismissTab(), {
  29252. tabbar: tabbar,
  29253. button: button
  29254. });
  29255. };
  29256. var changeTab$1 = function (tabbar, button) {
  29257. Highlighting.highlight(tabbar, button);
  29258. emitWith(tabbar, changeTab(), {
  29259. tabbar: tabbar,
  29260. button: button
  29261. });
  29262. };
  29263. return {
  29264. action: function (button) {
  29265. var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie();
  29266. var activeButton = Highlighting.isHighlighted(tabbar, button);
  29267. var response = function () {
  29268. if (activeButton && barDetail.clickToDismiss) {
  29269. return dismissTab$1;
  29270. } else if (!activeButton) {
  29271. return changeTab$1;
  29272. } else {
  29273. return noop;
  29274. }
  29275. }();
  29276. response(tabbar, button);
  29277. },
  29278. domModification: { classes: [barDetail.markers.tabClass] }
  29279. };
  29280. }
  29281. });
  29282. var parts$g = constant([tabsPart]);
  29283. var factory$k = function (detail, components, _spec, _externals) {
  29284. return {
  29285. 'uid': detail.uid,
  29286. 'dom': detail.dom,
  29287. components: components,
  29288. 'debug.sketcher': 'Tabbar',
  29289. 'domModification': { attributes: { role: 'tablist' } },
  29290. 'behaviours': augment(detail.tabbarBehaviours, [
  29291. Highlighting.config({
  29292. highlightClass: detail.markers.selectedClass,
  29293. itemClass: detail.markers.tabClass,
  29294. onHighlight: function (tabbar, tab) {
  29295. set$1(tab.element(), 'aria-selected', 'true');
  29296. },
  29297. onDehighlight: function (tabbar, tab) {
  29298. set$1(tab.element(), 'aria-selected', 'false');
  29299. }
  29300. }),
  29301. Keying.config({
  29302. mode: 'flow',
  29303. getInitial: function (tabbar) {
  29304. return Highlighting.getHighlighted(tabbar).map(function (tab) {
  29305. return tab.element();
  29306. });
  29307. },
  29308. selector: '.' + detail.markers.tabClass,
  29309. executeOnMove: true
  29310. })
  29311. ])
  29312. };
  29313. };
  29314. var Tabbar = composite$1({
  29315. name: 'Tabbar',
  29316. configFields: schema$y(),
  29317. partFields: parts$g(),
  29318. factory: factory$k
  29319. });
  29320. var factory$l = function (detail, _spec) {
  29321. return {
  29322. uid: detail.uid,
  29323. dom: detail.dom,
  29324. behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]),
  29325. domModification: { attributes: { role: 'tabpanel' } }
  29326. };
  29327. };
  29328. var Tabview = single$2({
  29329. name: 'Tabview',
  29330. configFields: [field$1('tabviewBehaviours', [Replacing])],
  29331. factory: factory$l
  29332. });
  29333. var schema$z = constant([
  29334. defaulted$1('selectFirst', true),
  29335. onHandler('onChangeTab'),
  29336. onHandler('onDismissTab'),
  29337. defaulted$1('tabs', []),
  29338. field$1('tabSectionBehaviours', [])
  29339. ]);
  29340. var barPart = required({
  29341. factory: Tabbar,
  29342. schema: [
  29343. strict$1('dom'),
  29344. strictObjOf('markers', [
  29345. strict$1('tabClass'),
  29346. strict$1('selectedClass')
  29347. ])
  29348. ],
  29349. name: 'tabbar',
  29350. defaults: function (detail) {
  29351. return { tabs: detail.tabs };
  29352. }
  29353. });
  29354. var viewPart = required({
  29355. factory: Tabview,
  29356. name: 'tabview'
  29357. });
  29358. var parts$h = constant([
  29359. barPart,
  29360. viewPart
  29361. ]);
  29362. var factory$m = function (detail, components, _spec, _externals) {
  29363. var changeTab$1 = function (button) {
  29364. var tabValue = Representing.getValue(button);
  29365. getPart(button, detail, 'tabview').each(function (tabview) {
  29366. var tabWithValue = find(detail.tabs, function (t) {
  29367. return t.value === tabValue;
  29368. });
  29369. tabWithValue.each(function (tabData) {
  29370. var panel = tabData.view();
  29371. getOpt(button.element(), 'id').each(function (id) {
  29372. set$1(tabview.element(), 'aria-labelledby', id);
  29373. });
  29374. Replacing.set(tabview, panel);
  29375. detail.onChangeTab(tabview, button, panel);
  29376. });
  29377. });
  29378. };
  29379. var changeTabBy = function (section, byPred) {
  29380. getPart(section, detail, 'tabbar').each(function (tabbar) {
  29381. byPred(tabbar).each(emitExecute);
  29382. });
  29383. };
  29384. return {
  29385. uid: detail.uid,
  29386. dom: detail.dom,
  29387. components: components,
  29388. behaviours: get$c(detail.tabSectionBehaviours),
  29389. events: derive(flatten([
  29390. detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) {
  29391. changeTabBy(section, Highlighting.getFirst);
  29392. })] : [],
  29393. [
  29394. run(changeTab(), function (section, simulatedEvent) {
  29395. var button = simulatedEvent.event().button();
  29396. changeTab$1(button);
  29397. }),
  29398. run(dismissTab(), function (section, simulatedEvent) {
  29399. var button = simulatedEvent.event().button();
  29400. detail.onDismissTab(section, button);
  29401. })
  29402. ]
  29403. ])),
  29404. apis: {
  29405. getViewItems: function (section) {
  29406. return getPart(section, detail, 'tabview').map(function (tabview) {
  29407. return Replacing.contents(tabview);
  29408. }).getOr([]);
  29409. },
  29410. showTab: function (section, tabKey) {
  29411. var getTabIfNotActive = function (tabbar) {
  29412. var candidates = Highlighting.getCandidates(tabbar);
  29413. var optTab = find(candidates, function (c) {
  29414. return Representing.getValue(c) === tabKey;
  29415. });
  29416. return optTab.filter(function (tab) {
  29417. return !Highlighting.isHighlighted(tabbar, tab);
  29418. });
  29419. };
  29420. changeTabBy(section, getTabIfNotActive);
  29421. }
  29422. }
  29423. };
  29424. };
  29425. var TabSection = composite$1({
  29426. name: 'TabSection',
  29427. configFields: schema$z(),
  29428. partFields: parts$h(),
  29429. factory: factory$m,
  29430. apis: {
  29431. getViewItems: function (apis, component) {
  29432. return apis.getViewItems(component);
  29433. },
  29434. showTab: function (apis, component, tabKey) {
  29435. apis.showTab(component, tabKey);
  29436. }
  29437. }
  29438. });
  29439. var measureHeights = function (allTabs, tabview, tabviewComp) {
  29440. return map(allTabs, function (_tab, i) {
  29441. Replacing.set(tabviewComp, allTabs[i].view());
  29442. var rect = tabview.dom().getBoundingClientRect();
  29443. Replacing.set(tabviewComp, []);
  29444. return rect.height;
  29445. });
  29446. };
  29447. var getMaxHeight = function (heights) {
  29448. return head(sort(heights, function (a, b) {
  29449. if (a > b) {
  29450. return -1;
  29451. } else if (a < b) {
  29452. return +1;
  29453. } else {
  29454. return 0;
  29455. }
  29456. }));
  29457. };
  29458. var getMaxTabviewHeight = function (dialog, tabview, tablist) {
  29459. var documentElement$1 = documentElement(dialog).dom();
  29460. var rootElm = ancestor$2(dialog, '.tox-dialog-wrap').getOr(dialog);
  29461. var isFixed = get$4(rootElm, 'position') === 'fixed';
  29462. var maxHeight;
  29463. if (isFixed) {
  29464. maxHeight = Math.max(documentElement$1.clientHeight, domGlobals.window.innerHeight);
  29465. } else {
  29466. maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight);
  29467. }
  29468. var tabviewHeight = get$6(tabview);
  29469. var isTabListBeside = tabview.dom().offsetLeft >= tablist.dom().offsetLeft + get$7(tablist);
  29470. var currentTabHeight = isTabListBeside ? Math.max(get$6(tablist), tabviewHeight) : tabviewHeight;
  29471. var dialogTopMargin = parseInt(get$4(dialog, 'margin-top'), 10) || 0;
  29472. var dialogBottomMargin = parseInt(get$4(dialog, 'margin-bottom'), 10) || 0;
  29473. var dialogHeight = get$6(dialog) + dialogTopMargin + dialogBottomMargin;
  29474. var chromeHeight = dialogHeight - currentTabHeight;
  29475. return maxHeight - chromeHeight;
  29476. };
  29477. var showTab = function (allTabs, comp) {
  29478. head(allTabs).each(function (tab) {
  29479. return TabSection.showTab(comp, tab.value);
  29480. });
  29481. };
  29482. var setTabviewHeight = function (tabview, height) {
  29483. set$2(tabview, 'height', height + 'px');
  29484. if (!detect$3().browser.isIE()) {
  29485. set$2(tabview, 'flex-basis', height + 'px');
  29486. } else {
  29487. remove$6(tabview, 'flex-basis');
  29488. }
  29489. };
  29490. var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) {
  29491. ancestor$2(dialogBody, '[role="dialog"]').each(function (dialog) {
  29492. descendant$1(dialog, '[role="tablist"]').each(function (tablist) {
  29493. maxTabHeight.get().map(function (height) {
  29494. set$2(tabview, 'height', '0');
  29495. set$2(tabview, 'flex-basis', '0');
  29496. return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist));
  29497. }).each(function (height) {
  29498. setTabviewHeight(tabview, height);
  29499. });
  29500. });
  29501. });
  29502. };
  29503. var getTabview = function (dialog) {
  29504. return descendant$1(dialog, '[role="tabpanel"]');
  29505. };
  29506. var setMode = function (allTabs) {
  29507. var smartTabHeight = function () {
  29508. var maxTabHeight = Cell(Option.none());
  29509. var extraEvents = [
  29510. runOnAttached(function (comp) {
  29511. var dialog = comp.element();
  29512. getTabview(dialog).each(function (tabview) {
  29513. set$2(tabview, 'visibility', 'hidden');
  29514. comp.getSystem().getByDom(tabview).toOption().each(function (tabviewComp) {
  29515. var heights = measureHeights(allTabs, tabview, tabviewComp);
  29516. var maxTabHeightOpt = getMaxHeight(heights);
  29517. maxTabHeight.set(maxTabHeightOpt);
  29518. });
  29519. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29520. remove$6(tabview, 'visibility');
  29521. showTab(allTabs, comp);
  29522. global$2.requestAnimationFrame(function () {
  29523. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29524. });
  29525. });
  29526. }),
  29527. run(windowResize(), function (comp) {
  29528. var dialog = comp.element();
  29529. getTabview(dialog).each(function (tabview) {
  29530. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29531. });
  29532. }),
  29533. run(formResizeEvent, function (comp, _se) {
  29534. var dialog = comp.element();
  29535. getTabview(dialog).each(function (tabview) {
  29536. var oldFocus = active();
  29537. set$2(tabview, 'visibility', 'hidden');
  29538. var oldHeight = getRaw(tabview, 'height').map(function (h) {
  29539. return parseInt(h, 10);
  29540. });
  29541. remove$6(tabview, 'height');
  29542. remove$6(tabview, 'flex-basis');
  29543. var newHeight = tabview.dom().getBoundingClientRect().height;
  29544. var hasGrown = oldHeight.forall(function (h) {
  29545. return newHeight > h;
  29546. });
  29547. if (hasGrown) {
  29548. maxTabHeight.set(Option.from(newHeight));
  29549. updateTabviewHeight(dialog, tabview, maxTabHeight);
  29550. } else {
  29551. oldHeight.each(function (h) {
  29552. setTabviewHeight(tabview, h);
  29553. });
  29554. }
  29555. remove$6(tabview, 'visibility');
  29556. oldFocus.each(focus$1);
  29557. });
  29558. })
  29559. ];
  29560. var selectFirst = false;
  29561. return {
  29562. extraEvents: extraEvents,
  29563. selectFirst: selectFirst
  29564. };
  29565. }();
  29566. var naiveTabHeight = function () {
  29567. var extraEvents = [];
  29568. var selectFirst = true;
  29569. return {
  29570. extraEvents: extraEvents,
  29571. selectFirst: selectFirst
  29572. };
  29573. }();
  29574. return {
  29575. smartTabHeight: smartTabHeight,
  29576. naiveTabHeight: naiveTabHeight
  29577. };
  29578. };
  29579. var SendDataToSectionChannel = 'send-data-to-section';
  29580. var SendDataToViewChannel = 'send-data-to-view';
  29581. var renderTabPanel = function (spec, backstage) {
  29582. var storedValue = Cell({});
  29583. var updateDataWithForm = function (form) {
  29584. var formData = Representing.getValue(form);
  29585. var validData = toValidValues(formData).getOr({});
  29586. var currentData = storedValue.get();
  29587. var newData = deepMerge(currentData, validData);
  29588. storedValue.set(newData);
  29589. };
  29590. var setDataOnForm = function (form) {
  29591. var tabData = storedValue.get();
  29592. Representing.setValue(form, tabData);
  29593. };
  29594. var oldTab = Cell(null);
  29595. var allTabs = map(spec.tabs, function (tab) {
  29596. return {
  29597. value: tab.name,
  29598. dom: {
  29599. tag: 'div',
  29600. classes: ['tox-dialog__body-nav-item'],
  29601. innerHtml: backstage.shared.providers.translate(tab.title)
  29602. },
  29603. view: function () {
  29604. return [Form.sketch(function (parts) {
  29605. return {
  29606. dom: {
  29607. tag: 'div',
  29608. classes: ['tox-form']
  29609. },
  29610. components: map(tab.items, function (item) {
  29611. return interpretInForm(parts, item, backstage);
  29612. }),
  29613. formBehaviours: derive$1([
  29614. Keying.config({
  29615. mode: 'acyclic',
  29616. useTabstopAt: not(isPseudoStop)
  29617. }),
  29618. config('TabView.form.events', [
  29619. runOnAttached(setDataOnForm),
  29620. runOnDetached(updateDataWithForm)
  29621. ]),
  29622. Receiving.config({
  29623. channels: wrapAll$1([
  29624. {
  29625. key: SendDataToSectionChannel,
  29626. value: { onReceive: updateDataWithForm }
  29627. },
  29628. {
  29629. key: SendDataToViewChannel,
  29630. value: { onReceive: setDataOnForm }
  29631. }
  29632. ])
  29633. })
  29634. ])
  29635. };
  29636. })];
  29637. }
  29638. };
  29639. });
  29640. var tabMode = setMode(allTabs).smartTabHeight;
  29641. return TabSection.sketch({
  29642. dom: {
  29643. tag: 'div',
  29644. classes: ['tox-dialog__body']
  29645. },
  29646. onChangeTab: function (section, button, _viewItems) {
  29647. var name = Representing.getValue(button);
  29648. emitWith(section, formTabChangeEvent, {
  29649. name: name,
  29650. oldName: oldTab.get()
  29651. });
  29652. oldTab.set(name);
  29653. },
  29654. tabs: allTabs,
  29655. components: [
  29656. TabSection.parts().tabbar({
  29657. dom: {
  29658. tag: 'div',
  29659. classes: ['tox-dialog__body-nav']
  29660. },
  29661. components: [Tabbar.parts().tabs({})],
  29662. markers: {
  29663. tabClass: 'tox-tab',
  29664. selectedClass: 'tox-dialog__body-nav-item--active'
  29665. },
  29666. tabbarBehaviours: derive$1([Tabstopping.config({})])
  29667. }),
  29668. TabSection.parts().tabview({
  29669. dom: {
  29670. tag: 'div',
  29671. classes: ['tox-dialog__body-content']
  29672. }
  29673. })
  29674. ],
  29675. selectFirst: tabMode.selectFirst,
  29676. tabSectionBehaviours: derive$1([
  29677. config('tabpanel', tabMode.extraEvents),
  29678. Keying.config({ mode: 'acyclic' }),
  29679. Composing.config({
  29680. find: function (comp) {
  29681. return head(TabSection.getViewItems(comp));
  29682. }
  29683. }),
  29684. Representing.config({
  29685. store: {
  29686. mode: 'manual',
  29687. getValue: function (tsection) {
  29688. tsection.getSystem().broadcastOn([SendDataToSectionChannel], {});
  29689. return storedValue.get();
  29690. },
  29691. setValue: function (tsection, value) {
  29692. storedValue.set(value);
  29693. tsection.getSystem().broadcastOn([SendDataToViewChannel], {});
  29694. }
  29695. }
  29696. })
  29697. ])
  29698. });
  29699. };
  29700. var dialogChannel = generate$1('update-dialog');
  29701. var titleChannel = generate$1('update-title');
  29702. var bodyChannel = generate$1('update-body');
  29703. var footerChannel = generate$1('update-footer');
  29704. var bodySendMessageChannel = generate$1('body-send-message');
  29705. var renderBody = function (spec, id, backstage, ariaAttrs) {
  29706. var renderComponents = function (incoming) {
  29707. switch (incoming.body.type) {
  29708. case 'tabpanel': {
  29709. return [renderTabPanel(incoming.body, backstage)];
  29710. }
  29711. default: {
  29712. return [renderBodyPanel(incoming.body, backstage)];
  29713. }
  29714. }
  29715. };
  29716. var updateState = function (_comp, incoming) {
  29717. return Option.some({
  29718. isTabPanel: function () {
  29719. return incoming.body.type === 'tabpanel';
  29720. }
  29721. });
  29722. };
  29723. var ariaAttributes = { 'aria-live': 'polite' };
  29724. return {
  29725. dom: {
  29726. tag: 'div',
  29727. classes: ['tox-dialog__content-js'],
  29728. attributes: __assign(__assign({}, id.map(function (x) {
  29729. return { id: x };
  29730. }).getOr({})), ariaAttrs ? ariaAttributes : {})
  29731. },
  29732. components: [],
  29733. behaviours: derive$1([
  29734. ComposingConfigs.childAt(0),
  29735. Reflecting.config({
  29736. channel: bodyChannel,
  29737. updateState: updateState,
  29738. renderComponents: renderComponents,
  29739. initialData: spec
  29740. })
  29741. ])
  29742. };
  29743. };
  29744. var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) {
  29745. return renderBody(spec, Option.some(contentId), backstage, ariaAttrs);
  29746. };
  29747. var renderModalBody = function (spec, backstage) {
  29748. var bodySpec = renderBody(spec, Option.none(), backstage, false);
  29749. return ModalDialog.parts().body(bodySpec);
  29750. };
  29751. var renderIframeBody = function (spec) {
  29752. var bodySpec = {
  29753. dom: {
  29754. tag: 'div',
  29755. classes: ['tox-dialog__content-js']
  29756. },
  29757. components: [{
  29758. dom: {
  29759. tag: 'div',
  29760. classes: ['tox-dialog__body-iframe']
  29761. },
  29762. components: [craft({
  29763. dom: {
  29764. tag: 'iframe',
  29765. attributes: { src: spec.url }
  29766. },
  29767. behaviours: derive$1([
  29768. Tabstopping.config({}),
  29769. Focusing.config({})
  29770. ])
  29771. })]
  29772. }],
  29773. behaviours: derive$1([Keying.config({
  29774. mode: 'acyclic',
  29775. useTabstopAt: not(isPseudoStop)
  29776. })])
  29777. };
  29778. return ModalDialog.parts().body(bodySpec);
  29779. };
  29780. var isTouch = global$6.deviceType.isTouch();
  29781. var hiddenHeader = function (title, close) {
  29782. return {
  29783. dom: {
  29784. tag: 'div',
  29785. styles: { display: 'none' },
  29786. classes: ['tox-dialog__header']
  29787. },
  29788. components: [
  29789. title,
  29790. close
  29791. ]
  29792. };
  29793. };
  29794. var pClose = function (onClose, providersBackstage) {
  29795. return ModalDialog.parts().close(Button.sketch({
  29796. dom: {
  29797. tag: 'button',
  29798. classes: [
  29799. 'tox-button',
  29800. 'tox-button--icon',
  29801. 'tox-button--naked'
  29802. ],
  29803. attributes: {
  29804. 'type': 'button',
  29805. 'aria-label': providersBackstage.translate('Close')
  29806. }
  29807. },
  29808. action: onClose,
  29809. buttonBehaviours: derive$1([Tabstopping.config({})])
  29810. }));
  29811. };
  29812. var pUntitled = function () {
  29813. return ModalDialog.parts().title({
  29814. dom: {
  29815. tag: 'div',
  29816. classes: ['tox-dialog__title'],
  29817. innerHtml: '',
  29818. styles: { display: 'none' }
  29819. }
  29820. });
  29821. };
  29822. var pBodyMessage = function (message, providersBackstage) {
  29823. return ModalDialog.parts().body({
  29824. dom: {
  29825. tag: 'div',
  29826. classes: ['tox-dialog__body']
  29827. },
  29828. components: [{
  29829. dom: {
  29830. tag: 'div',
  29831. classes: ['tox-dialog__body-content']
  29832. },
  29833. components: [{ dom: fromHtml$2('<p>' + providersBackstage.translate(message) + '</p>') }]
  29834. }]
  29835. });
  29836. };
  29837. var pFooter = function (buttons) {
  29838. return ModalDialog.parts().footer({
  29839. dom: {
  29840. tag: 'div',
  29841. classes: ['tox-dialog__footer']
  29842. },
  29843. components: buttons
  29844. });
  29845. };
  29846. var pFooterGroup = function (startButtons, endButtons) {
  29847. return [
  29848. Container.sketch({
  29849. dom: {
  29850. tag: 'div',
  29851. classes: ['tox-dialog__footer-start']
  29852. },
  29853. components: startButtons
  29854. }),
  29855. Container.sketch({
  29856. dom: {
  29857. tag: 'div',
  29858. classes: ['tox-dialog__footer-end']
  29859. },
  29860. components: endButtons
  29861. })
  29862. ];
  29863. };
  29864. var renderDialog = function (spec) {
  29865. var _a;
  29866. var dialogClass = 'tox-dialog';
  29867. var blockerClass = dialogClass + '-wrap';
  29868. var blockerBackdropClass = blockerClass + '__backdrop';
  29869. var scrollLockClass = dialogClass + '__disable-scroll';
  29870. return ModalDialog.sketch({
  29871. lazySink: spec.lazySink,
  29872. onEscape: function (comp) {
  29873. spec.onEscape(comp);
  29874. return Option.some(true);
  29875. },
  29876. useTabstopAt: function (elem) {
  29877. return !isPseudoStop(elem);
  29878. },
  29879. dom: {
  29880. tag: 'div',
  29881. classes: [dialogClass].concat(spec.extraClasses),
  29882. styles: __assign({ position: 'relative' }, spec.extraStyles)
  29883. },
  29884. components: __spreadArrays([
  29885. spec.header,
  29886. spec.body
  29887. ], spec.footer.toArray()),
  29888. parts: {
  29889. blocker: {
  29890. dom: fromHtml$2('<div class="' + blockerClass + '"></div>'),
  29891. components: [{
  29892. dom: {
  29893. tag: 'div',
  29894. classes: isTouch ? [
  29895. blockerBackdropClass,
  29896. blockerBackdropClass + '--opaque'
  29897. ] : [blockerBackdropClass]
  29898. }
  29899. }]
  29900. }
  29901. },
  29902. dragBlockClass: blockerClass,
  29903. modalBehaviours: derive$1(__spreadArrays([
  29904. Focusing.config({}),
  29905. config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  29906. Keying.focusIn(comp);
  29907. })])),
  29908. config('scroll-lock', [
  29909. runOnAttached(function () {
  29910. add$2(body(), scrollLockClass);
  29911. }),
  29912. runOnDetached(function () {
  29913. remove$4(body(), scrollLockClass);
  29914. })
  29915. ])
  29916. ], spec.extraBehaviours)),
  29917. eventOrder: __assign((_a = {}, _a[execute()] = ['dialog-events'], _a[attachedToDom()] = [
  29918. 'scroll-lock',
  29919. 'dialog-events',
  29920. 'alloy.base.behaviour'
  29921. ], _a[detachedFromDom()] = [
  29922. 'alloy.base.behaviour',
  29923. 'dialog-events',
  29924. 'scroll-lock'
  29925. ], _a), spec.eventOrder)
  29926. });
  29927. };
  29928. var renderClose = function (providersBackstage) {
  29929. return Button.sketch({
  29930. dom: {
  29931. tag: 'button',
  29932. classes: [
  29933. 'tox-button',
  29934. 'tox-button--icon',
  29935. 'tox-button--naked'
  29936. ],
  29937. attributes: {
  29938. 'type': 'button',
  29939. 'aria-label': providersBackstage.translate('Close'),
  29940. 'title': providersBackstage.translate('Close')
  29941. }
  29942. },
  29943. components: [{
  29944. dom: {
  29945. tag: 'div',
  29946. classes: ['tox-icon'],
  29947. innerHtml: '<svg width="24" height="24" xmlns="http://www.w3.org/2000/svg">' + '<path d="M17.953 7.453L13.422 12l4.531 4.547-1.406 1.406L12 ' + '13.422l-4.547 4.531-1.406-1.406L10.578 12 6.047 ' + '7.453l1.406-1.406L12 10.578l4.547-4.531z" ' + 'fill-rule="evenodd"></path></svg>'
  29948. }
  29949. }],
  29950. action: function (comp) {
  29951. emit(comp, formCancelEvent);
  29952. }
  29953. });
  29954. };
  29955. var renderTitle = function (spec, id, providersBackstage) {
  29956. var renderComponents = function (data) {
  29957. return [text(providersBackstage.translate(data.title))];
  29958. };
  29959. return {
  29960. dom: {
  29961. tag: 'div',
  29962. classes: ['tox-dialog__title'],
  29963. attributes: __assign({}, id.map(function (x) {
  29964. return { id: x };
  29965. }).getOr({}))
  29966. },
  29967. components: renderComponents(spec),
  29968. behaviours: derive$1([Reflecting.config({
  29969. channel: titleChannel,
  29970. renderComponents: renderComponents
  29971. })])
  29972. };
  29973. };
  29974. var renderDragHandle = function () {
  29975. return { dom: fromHtml$2('<div class="tox-dialog__draghandle"></div>') };
  29976. };
  29977. var renderInlineHeader = function (spec, titleId, providersBackstage) {
  29978. return Container.sketch({
  29979. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  29980. components: [
  29981. renderTitle(spec, Option.some(titleId), providersBackstage),
  29982. renderDragHandle(),
  29983. renderClose(providersBackstage)
  29984. ],
  29985. containerBehaviours: derive$1([Dragging.config({
  29986. mode: 'mouse',
  29987. blockerClass: 'blocker',
  29988. getTarget: function (handle) {
  29989. return closest$3(handle, '[role="dialog"]').getOrDie();
  29990. },
  29991. snaps: {
  29992. getSnapPoints: function () {
  29993. return [];
  29994. },
  29995. leftAttr: 'data-drag-left',
  29996. topAttr: 'data-drag-top'
  29997. }
  29998. })])
  29999. });
  30000. };
  30001. var renderModalHeader = function (spec, providersBackstage) {
  30002. var pTitle = ModalDialog.parts().title(renderTitle(spec, Option.none(), providersBackstage));
  30003. var pHandle = ModalDialog.parts().draghandle(renderDragHandle());
  30004. var pClose = ModalDialog.parts().close(renderClose(providersBackstage));
  30005. var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]);
  30006. return Container.sketch({
  30007. dom: fromHtml$2('<div class="tox-dialog__header"></div>'),
  30008. components: components
  30009. });
  30010. };
  30011. var getHeader = function (title, backstage) {
  30012. return renderModalHeader({
  30013. title: backstage.shared.providers.translate(title),
  30014. draggable: backstage.dialog.isDraggableModal()
  30015. }, backstage.shared.providers);
  30016. };
  30017. var getEventExtras = function (lazyDialog, extra) {
  30018. return {
  30019. onClose: function () {
  30020. return extra.closeWindow();
  30021. },
  30022. onBlock: function (blockEvent) {
  30023. ModalDialog.setBusy(lazyDialog(), function (d, bs) {
  30024. return {
  30025. dom: {
  30026. tag: 'div',
  30027. classes: ['tox-dialog__busy-spinner'],
  30028. attributes: { 'aria-label': blockEvent.message() },
  30029. styles: {
  30030. left: '0px',
  30031. right: '0px',
  30032. bottom: '0px',
  30033. top: '0px',
  30034. position: 'absolute'
  30035. }
  30036. },
  30037. behaviours: bs,
  30038. components: [{ dom: fromHtml$2('<div class="tox-spinner"><div></div><div></div><div></div></div>') }]
  30039. };
  30040. });
  30041. },
  30042. onUnblock: function () {
  30043. ModalDialog.setIdle(lazyDialog());
  30044. }
  30045. };
  30046. };
  30047. var renderModalDialog = function (spec, initialData, dialogEvents, backstage) {
  30048. var _a;
  30049. var updateState = function (_comp, incoming) {
  30050. return Option.some(incoming);
  30051. };
  30052. return build$1(renderDialog(__assign(__assign({}, spec), {
  30053. lazySink: backstage.shared.getSink,
  30054. extraBehaviours: __spreadArrays([
  30055. Reflecting.config({
  30056. channel: dialogChannel,
  30057. updateState: updateState,
  30058. initialData: initialData
  30059. }),
  30060. RepresentingConfigs.memory({})
  30061. ], spec.extraBehaviours),
  30062. onEscape: function (comp) {
  30063. emit(comp, formCancelEvent);
  30064. },
  30065. dialogEvents: dialogEvents,
  30066. eventOrder: (_a = {}, _a[receive()] = [
  30067. 'reflecting',
  30068. 'receiving'
  30069. ], _a[attachedToDom()] = [
  30070. 'scroll-lock',
  30071. 'reflecting',
  30072. 'messages',
  30073. 'dialog-events',
  30074. 'alloy.base.behaviour'
  30075. ], _a[detachedFromDom()] = [
  30076. 'alloy.base.behaviour',
  30077. 'dialog-events',
  30078. 'messages',
  30079. 'reflecting',
  30080. 'scroll-lock'
  30081. ], _a)
  30082. })));
  30083. };
  30084. var mapMenuButtons = function (buttons) {
  30085. var mapItems = function (button) {
  30086. var items = map(button.items, function (item) {
  30087. var cell = Cell(false);
  30088. return __assign(__assign({}, item), { storage: cell });
  30089. });
  30090. return __assign(__assign({}, button), { items: items });
  30091. };
  30092. return map(buttons, function (button) {
  30093. if (button.type === 'menu') {
  30094. return mapItems(button);
  30095. }
  30096. return button;
  30097. });
  30098. };
  30099. var extractCellsToObject = function (buttons) {
  30100. return foldl(buttons, function (acc, button) {
  30101. if (button.type === 'menu') {
  30102. var menuButton = button;
  30103. return foldl(menuButton.items, function (innerAcc, item) {
  30104. innerAcc[item.name] = item.storage;
  30105. return innerAcc;
  30106. }, acc);
  30107. }
  30108. return acc;
  30109. }, {});
  30110. };
  30111. var initCommonEvents = function (fireApiEvent, extras) {
  30112. return [
  30113. runWithTarget(focusin(), onFocus$1),
  30114. fireApiEvent(formCloseEvent, function (_api, spec) {
  30115. extras.onClose();
  30116. spec.onClose();
  30117. }),
  30118. fireApiEvent(formCancelEvent, function (api, spec, _event, self) {
  30119. spec.onCancel(api);
  30120. emit(self, formCloseEvent);
  30121. }),
  30122. run(formUnblockEvent, function (_c, _se) {
  30123. return extras.onUnblock();
  30124. }),
  30125. run(formBlockEvent, function (_c, se) {
  30126. return extras.onBlock(se.event());
  30127. })
  30128. ];
  30129. };
  30130. var initUrlDialog = function (getInstanceApi, extras) {
  30131. var fireApiEvent = function (eventName, f) {
  30132. return run(eventName, function (c, se) {
  30133. withSpec(c, function (spec, _c) {
  30134. f(getInstanceApi(), spec, se.event(), c);
  30135. });
  30136. });
  30137. };
  30138. var withSpec = function (c, f) {
  30139. Reflecting.getState(c).get().each(function (currentDialog) {
  30140. f(currentDialog, c);
  30141. });
  30142. };
  30143. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [fireApiEvent(formActionEvent, function (api, spec, event) {
  30144. spec.onAction(api, { name: event.name() });
  30145. })]);
  30146. };
  30147. var initDialog = function (getInstanceApi, extras, getSink) {
  30148. var fireApiEvent = function (eventName, f) {
  30149. return run(eventName, function (c, se) {
  30150. withSpec(c, function (spec, _c) {
  30151. f(getInstanceApi(), spec, se.event(), c);
  30152. });
  30153. });
  30154. };
  30155. var withSpec = function (c, f) {
  30156. Reflecting.getState(c).get().each(function (currentDialogInit) {
  30157. f(currentDialogInit.internalDialog, c);
  30158. });
  30159. };
  30160. return __spreadArrays(initCommonEvents(fireApiEvent, extras), [
  30161. fireApiEvent(formSubmitEvent, function (api, spec) {
  30162. return spec.onSubmit(api);
  30163. }),
  30164. fireApiEvent(formChangeEvent, function (api, spec, event) {
  30165. spec.onChange(api, { name: event.name() });
  30166. }),
  30167. fireApiEvent(formActionEvent, function (api, spec, event, component) {
  30168. var focusIn = function () {
  30169. return Keying.focusIn(component);
  30170. };
  30171. var isDisabled = function (focused) {
  30172. return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) {
  30173. return val === 'true';
  30174. });
  30175. };
  30176. var current = active();
  30177. spec.onAction(api, {
  30178. name: event.name(),
  30179. value: event.value()
  30180. });
  30181. active().fold(focusIn, function (focused) {
  30182. if (isDisabled(focused)) {
  30183. focusIn();
  30184. } else if (current.exists(function (cur) {
  30185. return contains$2(focused, cur) && isDisabled(cur);
  30186. })) {
  30187. focusIn();
  30188. } else {
  30189. getSink().toOption().filter(function (sink) {
  30190. return !contains$2(sink.element(), focused);
  30191. }).each(focusIn);
  30192. }
  30193. });
  30194. }),
  30195. fireApiEvent(formTabChangeEvent, function (api, spec, event) {
  30196. spec.onTabChange(api, {
  30197. newTabName: event.name(),
  30198. oldTabName: event.oldName()
  30199. });
  30200. }),
  30201. runOnDetached(function (component) {
  30202. var api = getInstanceApi();
  30203. Representing.setValue(component, api.getData());
  30204. })
  30205. ]);
  30206. };
  30207. var SilverDialogEvents = {
  30208. initUrlDialog: initUrlDialog,
  30209. initDialog: initDialog
  30210. };
  30211. var makeButton = function (button, backstage) {
  30212. return renderFooterButton(button, button.type, backstage);
  30213. };
  30214. var lookup$2 = function (compInSystem, footerButtons, buttonName) {
  30215. return find(footerButtons, function (button) {
  30216. return button.name === buttonName;
  30217. }).bind(function (memButton) {
  30218. return memButton.memento.getOpt(compInSystem);
  30219. });
  30220. };
  30221. var renderComponents = function (_data, state) {
  30222. var footerButtons = state.map(function (s) {
  30223. return s.footerButtons;
  30224. }).getOr([]);
  30225. var buttonGroups = partition(footerButtons, function (button) {
  30226. return button.align === 'start';
  30227. });
  30228. var makeGroup = function (edge, buttons) {
  30229. return Container.sketch({
  30230. dom: {
  30231. tag: 'div',
  30232. classes: ['tox-dialog__footer-' + edge]
  30233. },
  30234. components: map(buttons, function (button) {
  30235. return button.memento.asSpec();
  30236. })
  30237. });
  30238. };
  30239. var startButtons = makeGroup('start', buttonGroups.pass);
  30240. var endButtons = makeGroup('end', buttonGroups.fail);
  30241. return [
  30242. startButtons,
  30243. endButtons
  30244. ];
  30245. };
  30246. var renderFooter = function (initSpec, backstage) {
  30247. var updateState = function (_comp, data) {
  30248. var footerButtons = map(data.buttons, function (button) {
  30249. var memButton = record(makeButton(button, backstage));
  30250. return {
  30251. name: button.name,
  30252. align: button.align,
  30253. memento: memButton
  30254. };
  30255. });
  30256. var lookupByName = function (compInSystem, buttonName) {
  30257. return lookup$2(compInSystem, footerButtons, buttonName);
  30258. };
  30259. return Option.some({
  30260. lookupByName: lookupByName,
  30261. footerButtons: footerButtons
  30262. });
  30263. };
  30264. return {
  30265. dom: fromHtml$2('<div class="tox-dialog__footer"></div>'),
  30266. components: [],
  30267. behaviours: derive$1([Reflecting.config({
  30268. channel: footerChannel,
  30269. initialData: initSpec,
  30270. updateState: updateState,
  30271. renderComponents: renderComponents
  30272. })])
  30273. };
  30274. };
  30275. var renderInlineFooter = function (initSpec, backstage) {
  30276. return renderFooter(initSpec, backstage);
  30277. };
  30278. var renderModalFooter = function (initSpec, backstage) {
  30279. return ModalDialog.parts().footer(renderFooter(initSpec, backstage));
  30280. };
  30281. var getCompByName = function (access, name) {
  30282. var root = access.getRoot();
  30283. if (root.getSystem().isConnected()) {
  30284. var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper());
  30285. return Form.getField(form_1, name).fold(function () {
  30286. var footer = access.getFooter();
  30287. var footerState = Reflecting.getState(footer);
  30288. return footerState.get().bind(function (f) {
  30289. return f.lookupByName(form_1, name);
  30290. });
  30291. }, function (comp) {
  30292. return Option.some(comp);
  30293. });
  30294. } else {
  30295. return Option.none();
  30296. }
  30297. };
  30298. var validateData = function (access, data) {
  30299. var root = access.getRoot();
  30300. return Reflecting.getState(root).get().map(function (dialogState) {
  30301. return getOrDie(asRaw('data', dialogState.dataValidator, data));
  30302. }).getOr(data);
  30303. };
  30304. var getDialogApi = function (access, doRedial, menuItemStates) {
  30305. var withRoot = function (f) {
  30306. var root = access.getRoot();
  30307. if (root.getSystem().isConnected()) {
  30308. f(root);
  30309. }
  30310. };
  30311. var getData = function () {
  30312. var root = access.getRoot();
  30313. var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root;
  30314. var representedValues = Representing.getValue(valueComp);
  30315. var menuItemCurrentState = map$1(menuItemStates, function (cell) {
  30316. return cell.get();
  30317. });
  30318. return __assign(__assign({}, representedValues), menuItemCurrentState);
  30319. };
  30320. var setData = function (newData) {
  30321. withRoot(function (_) {
  30322. var prevData = instanceApi.getData();
  30323. var mergedData = __assign(__assign({}, prevData), newData);
  30324. var newInternalData = validateData(access, mergedData);
  30325. var form = access.getFormWrapper();
  30326. Representing.setValue(form, newInternalData);
  30327. each$1(menuItemStates, function (v, k) {
  30328. if (has(mergedData, k)) {
  30329. v.set(mergedData[k]);
  30330. }
  30331. });
  30332. });
  30333. };
  30334. var disable = function (name) {
  30335. getCompByName(access, name).each(Disabling.disable);
  30336. };
  30337. var enable = function (name) {
  30338. getCompByName(access, name).each(Disabling.enable);
  30339. };
  30340. var focus = function (name) {
  30341. getCompByName(access, name).each(Focusing.focus);
  30342. };
  30343. var block = function (message) {
  30344. if (!isString(message)) {
  30345. throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  30346. }
  30347. withRoot(function (root) {
  30348. emitWith(root, formBlockEvent, { message: message });
  30349. });
  30350. };
  30351. var unblock = function () {
  30352. withRoot(function (root) {
  30353. emit(root, formUnblockEvent);
  30354. });
  30355. };
  30356. var showTab = function (name) {
  30357. withRoot(function (_) {
  30358. var body = access.getBody();
  30359. var bodyState = Reflecting.getState(body);
  30360. if (bodyState.get().exists(function (b) {
  30361. return b.isTabPanel();
  30362. })) {
  30363. Composing.getCurrent(body).each(function (tabSection) {
  30364. TabSection.showTab(tabSection, name);
  30365. });
  30366. }
  30367. });
  30368. };
  30369. var redial = function (d) {
  30370. withRoot(function (root) {
  30371. var dialogInit = doRedial(d);
  30372. root.getSystem().broadcastOn([dialogChannel], dialogInit);
  30373. root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog);
  30374. root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog);
  30375. root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog);
  30376. instanceApi.setData(dialogInit.initialData);
  30377. });
  30378. };
  30379. var close = function () {
  30380. withRoot(function (root) {
  30381. emit(root, formCloseEvent);
  30382. });
  30383. };
  30384. var instanceApi = {
  30385. getData: getData,
  30386. setData: setData,
  30387. disable: disable,
  30388. enable: enable,
  30389. focus: focus,
  30390. block: block,
  30391. unblock: unblock,
  30392. showTab: showTab,
  30393. redial: redial,
  30394. close: close
  30395. };
  30396. return instanceApi;
  30397. };
  30398. var renderDialog$1 = function (dialogInit, extra, backstage) {
  30399. var header = getHeader(dialogInit.internalDialog.title, backstage);
  30400. var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage);
  30401. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30402. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30403. var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage);
  30404. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30405. return instanceApi;
  30406. }, getEventExtras(function () {
  30407. return dialog;
  30408. }, extra), backstage.shared.getSink);
  30409. var dialogSize = dialogInit.internalDialog.size !== 'normal' ? dialogInit.internalDialog.size === 'large' ? ['tox-dialog--width-lg'] : ['tox-dialog--width-md'] : [];
  30410. var spec = {
  30411. header: header,
  30412. body: body,
  30413. footer: Option.some(footer),
  30414. extraClasses: dialogSize,
  30415. extraBehaviours: [],
  30416. extraStyles: {}
  30417. };
  30418. var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage);
  30419. var modalAccess = function () {
  30420. var getForm = function () {
  30421. var outerForm = ModalDialog.getBody(dialog);
  30422. return Composing.getCurrent(outerForm).getOr(outerForm);
  30423. };
  30424. return {
  30425. getRoot: function () {
  30426. return dialog;
  30427. },
  30428. getBody: function () {
  30429. return ModalDialog.getBody(dialog);
  30430. },
  30431. getFooter: function () {
  30432. return ModalDialog.getFooter(dialog);
  30433. },
  30434. getFormWrapper: getForm
  30435. };
  30436. }();
  30437. var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells);
  30438. return {
  30439. dialog: dialog,
  30440. instanceApi: instanceApi
  30441. };
  30442. };
  30443. var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) {
  30444. var _a, _b;
  30445. var dialogLabelId = generate$1('dialog-label');
  30446. var dialogContentId = generate$1('dialog-content');
  30447. var updateState = function (_comp, incoming) {
  30448. return Option.some(incoming);
  30449. };
  30450. var memHeader = record(renderInlineHeader({
  30451. title: dialogInit.internalDialog.title,
  30452. draggable: true
  30453. }, dialogLabelId, backstage.shared.providers));
  30454. var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs));
  30455. var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons);
  30456. var objOfCells = extractCellsToObject(storagedMenuButtons);
  30457. var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage));
  30458. var dialogEvents = SilverDialogEvents.initDialog(function () {
  30459. return instanceApi;
  30460. }, {
  30461. onBlock: function () {
  30462. },
  30463. onUnblock: function () {
  30464. },
  30465. onClose: function () {
  30466. return extra.closeWindow();
  30467. }
  30468. }, backstage.shared.getSink);
  30469. var dialog = build$1({
  30470. dom: {
  30471. tag: 'div',
  30472. classes: [
  30473. 'tox-dialog',
  30474. 'tox-dialog-inline'
  30475. ],
  30476. attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = '' + dialogContentId, _a)
  30477. },
  30478. eventOrder: (_b = {}, _b[receive()] = [
  30479. Reflecting.name(),
  30480. Receiving.name()
  30481. ], _b[execute()] = ['execute-on-form'], _b[attachedToDom()] = [
  30482. 'reflecting',
  30483. 'execute-on-form'
  30484. ], _b),
  30485. behaviours: derive$1([
  30486. Keying.config({
  30487. mode: 'cyclic',
  30488. onEscape: function (c) {
  30489. emit(c, formCloseEvent);
  30490. return Option.some(true);
  30491. },
  30492. useTabstopAt: function (elem) {
  30493. return !isPseudoStop(elem) && (name(elem) !== 'button' || get$2(elem, 'disabled') !== 'disabled');
  30494. }
  30495. }),
  30496. Reflecting.config({
  30497. channel: dialogChannel,
  30498. updateState: updateState,
  30499. initialData: dialogInit
  30500. }),
  30501. Focusing.config({}),
  30502. config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) {
  30503. Keying.focusIn(comp);
  30504. })])),
  30505. RepresentingConfigs.memory({})
  30506. ]),
  30507. components: [
  30508. memHeader.asSpec(),
  30509. memBody.asSpec(),
  30510. memFooter.asSpec()
  30511. ]
  30512. });
  30513. var instanceApi = getDialogApi({
  30514. getRoot: function () {
  30515. return dialog;
  30516. },
  30517. getFooter: function () {
  30518. return memFooter.get(dialog);
  30519. },
  30520. getBody: function () {
  30521. return memBody.get(dialog);
  30522. },
  30523. getFormWrapper: function () {
  30524. var body = memBody.get(dialog);
  30525. return Composing.getCurrent(body).getOr(body);
  30526. }
  30527. }, extra.redial, objOfCells);
  30528. return {
  30529. dialog: dialog,
  30530. instanceApi: instanceApi
  30531. };
  30532. };
  30533. var global$g = tinymce.util.Tools.resolve('tinymce.util.URI');
  30534. var getUrlDialogApi = function (root) {
  30535. var withRoot = function (f) {
  30536. if (root.getSystem().isConnected()) {
  30537. f(root);
  30538. }
  30539. };
  30540. var block = function (message) {
  30541. if (!isString(message)) {
  30542. throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument');
  30543. }
  30544. withRoot(function (root) {
  30545. emitWith(root, formBlockEvent, { message: message });
  30546. });
  30547. };
  30548. var unblock = function () {
  30549. withRoot(function (root) {
  30550. emit(root, formUnblockEvent);
  30551. });
  30552. };
  30553. var close = function () {
  30554. withRoot(function (root) {
  30555. emit(root, formCloseEvent);
  30556. });
  30557. };
  30558. var sendMessage = function (data) {
  30559. withRoot(function (root) {
  30560. root.getSystem().broadcastOn([bodySendMessageChannel], data);
  30561. });
  30562. };
  30563. return {
  30564. block: block,
  30565. unblock: unblock,
  30566. close: close,
  30567. sendMessage: sendMessage
  30568. };
  30569. };
  30570. var SUPPORTED_MESSAGE_ACTIONS = [
  30571. 'insertContent',
  30572. 'setContent',
  30573. 'execCommand',
  30574. 'close',
  30575. 'block',
  30576. 'unblock'
  30577. ];
  30578. var isSupportedMessage = function (data) {
  30579. return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1;
  30580. };
  30581. var isCustomMessage = function (data) {
  30582. return !isSupportedMessage(data) && isObject(data) && has(data, 'mceAction');
  30583. };
  30584. var handleMessage = function (editor, api, data) {
  30585. switch (data.mceAction) {
  30586. case 'insertContent':
  30587. editor.insertContent(data.content);
  30588. break;
  30589. case 'setContent':
  30590. editor.setContent(data.content);
  30591. break;
  30592. case 'execCommand':
  30593. var ui = isBoolean(data.ui) ? data.ui : false;
  30594. editor.execCommand(data.cmd, ui, data.value);
  30595. break;
  30596. case 'close':
  30597. api.close();
  30598. break;
  30599. case 'block':
  30600. api.block(data.message);
  30601. break;
  30602. case 'unblock':
  30603. api.unblock();
  30604. break;
  30605. }
  30606. };
  30607. var renderUrlDialog = function (internalDialog, extra, editor, backstage) {
  30608. var _a;
  30609. var header = getHeader(internalDialog.title, backstage);
  30610. var body = renderIframeBody(internalDialog);
  30611. var footer = internalDialog.buttons.bind(function (buttons) {
  30612. if (buttons.length === 0) {
  30613. return Option.none();
  30614. } else {
  30615. return Option.some(renderModalFooter({ buttons: buttons }, backstage));
  30616. }
  30617. });
  30618. var dialogEvents = SilverDialogEvents.initUrlDialog(function () {
  30619. return instanceApi;
  30620. }, getEventExtras(function () {
  30621. return dialog;
  30622. }, extra));
  30623. var styles = __assign(__assign({}, internalDialog.height.fold(function () {
  30624. return {};
  30625. }, function (height) {
  30626. return {
  30627. 'height': height + 'px',
  30628. 'max-height': height + 'px'
  30629. };
  30630. })), internalDialog.width.fold(function () {
  30631. return {};
  30632. }, function (width) {
  30633. return {
  30634. 'width': width + 'px',
  30635. 'max-width': width + 'px'
  30636. };
  30637. }));
  30638. var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : [];
  30639. var iframeUri = new global$g(internalDialog.url, { base_uri: new global$g(domGlobals.window.location.href) });
  30640. var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : '');
  30641. var messageHandlerUnbinder = Cell(Option.none());
  30642. var extraBehaviours = [
  30643. config('messages', [
  30644. runOnAttached(function () {
  30645. var unbind = bind$3(Element.fromDom(domGlobals.window), 'message', function (e) {
  30646. if (iframeUri.isSameOrigin(new global$g(e.raw().origin))) {
  30647. var data = e.raw().data;
  30648. if (isSupportedMessage(data)) {
  30649. handleMessage(editor, instanceApi, data);
  30650. } else if (isCustomMessage(data)) {
  30651. internalDialog.onMessage(instanceApi, data);
  30652. }
  30653. }
  30654. });
  30655. messageHandlerUnbinder.set(Option.some(unbind));
  30656. }),
  30657. runOnDetached(function () {
  30658. messageHandlerUnbinder.get().each(function (unbinder) {
  30659. return unbinder.unbind();
  30660. });
  30661. })
  30662. ]),
  30663. Receiving.config({
  30664. channels: (_a = {}, _a[bodySendMessageChannel] = {
  30665. onReceive: function (comp, data) {
  30666. descendant$1(comp.element(), 'iframe').each(function (iframeEle) {
  30667. var iframeWin = iframeEle.dom().contentWindow;
  30668. iframeWin.postMessage(data, iframeDomain);
  30669. });
  30670. }
  30671. }, _a)
  30672. })
  30673. ];
  30674. var spec = {
  30675. header: header,
  30676. body: body,
  30677. footer: footer,
  30678. extraClasses: classes,
  30679. extraBehaviours: extraBehaviours,
  30680. extraStyles: styles
  30681. };
  30682. var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage);
  30683. var instanceApi = getUrlDialogApi(dialog);
  30684. return {
  30685. dialog: dialog,
  30686. instanceApi: instanceApi
  30687. };
  30688. };
  30689. var setup$c = function (extras) {
  30690. var sharedBackstage = extras.backstage.shared;
  30691. var open = function (message, callback) {
  30692. var closeDialog = function () {
  30693. ModalDialog.hide(alertDialog);
  30694. callback();
  30695. };
  30696. var memFooterClose = record(renderFooterButton({
  30697. name: 'close-alert',
  30698. text: 'OK',
  30699. primary: true,
  30700. align: 'end',
  30701. disabled: false,
  30702. icon: Option.none()
  30703. }, 'cancel', extras.backstage));
  30704. var titleSpec = pUntitled();
  30705. var closeSpec = pClose(closeDialog, sharedBackstage.providers);
  30706. var alertDialog = build$1(renderDialog({
  30707. lazySink: function () {
  30708. return sharedBackstage.getSink();
  30709. },
  30710. header: hiddenHeader(titleSpec, closeSpec),
  30711. body: pBodyMessage(message, sharedBackstage.providers),
  30712. footer: Option.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))),
  30713. onEscape: closeDialog,
  30714. extraClasses: ['tox-alert-dialog'],
  30715. extraBehaviours: [],
  30716. extraStyles: {},
  30717. dialogEvents: [run(formCancelEvent, closeDialog)],
  30718. eventOrder: {}
  30719. }));
  30720. ModalDialog.show(alertDialog);
  30721. var footerCloseButton = memFooterClose.get(alertDialog);
  30722. Focusing.focus(footerCloseButton);
  30723. };
  30724. return { open: open };
  30725. };
  30726. var setup$d = function (extras) {
  30727. var sharedBackstage = extras.backstage.shared;
  30728. var open = function (message, callback) {
  30729. var closeDialog = function (state) {
  30730. ModalDialog.hide(confirmDialog);
  30731. callback(state);
  30732. };
  30733. var memFooterYes = record(renderFooterButton({
  30734. name: 'yes',
  30735. text: 'Yes',
  30736. primary: true,
  30737. align: 'end',
  30738. disabled: false,
  30739. icon: Option.none()
  30740. }, 'submit', extras.backstage));
  30741. var footerNo = renderFooterButton({
  30742. name: 'no',
  30743. text: 'No',
  30744. primary: false,
  30745. align: 'end',
  30746. disabled: false,
  30747. icon: Option.none()
  30748. }, 'cancel', extras.backstage);
  30749. var titleSpec = pUntitled();
  30750. var closeSpec = pClose(function () {
  30751. return closeDialog(false);
  30752. }, sharedBackstage.providers);
  30753. var confirmDialog = build$1(renderDialog({
  30754. lazySink: function () {
  30755. return sharedBackstage.getSink();
  30756. },
  30757. header: hiddenHeader(titleSpec, closeSpec),
  30758. body: pBodyMessage(message, sharedBackstage.providers),
  30759. footer: Option.some(pFooter(pFooterGroup([], [
  30760. footerNo,
  30761. memFooterYes.asSpec()
  30762. ]))),
  30763. onEscape: function () {
  30764. return closeDialog(false);
  30765. },
  30766. extraClasses: ['tox-confirm-dialog'],
  30767. extraBehaviours: [],
  30768. extraStyles: {},
  30769. dialogEvents: [
  30770. run(formCancelEvent, function () {
  30771. return closeDialog(false);
  30772. }),
  30773. run(formSubmitEvent, function () {
  30774. return closeDialog(true);
  30775. })
  30776. ],
  30777. eventOrder: {}
  30778. }));
  30779. ModalDialog.show(confirmDialog);
  30780. var footerYesButton = memFooterYes.get(confirmDialog);
  30781. Focusing.focus(footerYesButton);
  30782. };
  30783. return { open: open };
  30784. };
  30785. var validateData$1 = function (data, validator) {
  30786. return getOrDie(asRaw('data', validator, data));
  30787. };
  30788. var isAlertOrConfirmDialog = function (target) {
  30789. return closest$4(target, '.tox-alert-dialog') || closest$4(target, '.tox-confirm-dialog');
  30790. };
  30791. var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) {
  30792. if (isStickyToolbar && isToolbarLocationTop) {
  30793. return [];
  30794. } else {
  30795. return [Docking.config({
  30796. contextual: {
  30797. lazyContext: function () {
  30798. return Option.some(box(Element.fromDom(editor.getContentAreaContainer())));
  30799. },
  30800. fadeInClass: 'tox-dialog-dock-fadein',
  30801. fadeOutClass: 'tox-dialog-dock-fadeout',
  30802. transitionClass: 'tox-dialog-dock-transition'
  30803. },
  30804. modes: ['top']
  30805. })];
  30806. }
  30807. };
  30808. var setup$e = function (extras) {
  30809. var backstage = extras.backstage;
  30810. var editor = extras.editor;
  30811. var isStickyToolbar$1 = isStickyToolbar(editor);
  30812. var alertDialog = setup$c(extras);
  30813. var confirmDialog = setup$d(extras);
  30814. var open = function (config, params, closeWindow) {
  30815. if (params !== undefined && params.inline === 'toolbar') {
  30816. return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs);
  30817. } else if (params !== undefined && params.inline === 'cursor') {
  30818. return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs);
  30819. } else {
  30820. return openModalDialog(config, closeWindow);
  30821. }
  30822. };
  30823. var openUrl = function (config, closeWindow) {
  30824. return openModalUrlDialog(config, closeWindow);
  30825. };
  30826. var openModalUrlDialog = function (config, closeWindow) {
  30827. var factory = function (contents) {
  30828. var dialog = renderUrlDialog(contents, {
  30829. closeWindow: function () {
  30830. ModalDialog.hide(dialog.dialog);
  30831. closeWindow(dialog.instanceApi);
  30832. }
  30833. }, editor, backstage);
  30834. ModalDialog.show(dialog.dialog);
  30835. return dialog.instanceApi;
  30836. };
  30837. return DialogManager.openUrl(factory, config);
  30838. };
  30839. var openModalDialog = function (config, closeWindow) {
  30840. var factory = function (contents, internalInitialData, dataValidator) {
  30841. var initialData = internalInitialData;
  30842. var dialogInit = {
  30843. dataValidator: dataValidator,
  30844. initialData: initialData,
  30845. internalDialog: contents
  30846. };
  30847. var dialog = renderDialog$1(dialogInit, {
  30848. redial: DialogManager.redial,
  30849. closeWindow: function () {
  30850. ModalDialog.hide(dialog.dialog);
  30851. closeWindow(dialog.instanceApi);
  30852. }
  30853. }, backstage);
  30854. ModalDialog.show(dialog.dialog);
  30855. dialog.instanceApi.setData(initialData);
  30856. return dialog.instanceApi;
  30857. };
  30858. return DialogManager.open(factory, config);
  30859. };
  30860. var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) {
  30861. var factory = function (contents, internalInitialData, dataValidator) {
  30862. var initialData = validateData$1(internalInitialData, dataValidator);
  30863. var inlineDialog = value$3();
  30864. var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop();
  30865. var dialogInit = {
  30866. dataValidator: dataValidator,
  30867. initialData: initialData,
  30868. internalDialog: contents
  30869. };
  30870. var refreshDocking = function () {
  30871. return inlineDialog.on(function (dialog) {
  30872. InlineView.reposition(dialog);
  30873. Docking.refresh(dialog);
  30874. });
  30875. };
  30876. var dialogUi = renderInlineDialog(dialogInit, {
  30877. redial: DialogManager.redial,
  30878. closeWindow: function () {
  30879. inlineDialog.on(InlineView.hide);
  30880. editor.off('ResizeEditor', refreshDocking);
  30881. inlineDialog.clear();
  30882. closeWindow(dialogUi.instanceApi);
  30883. }
  30884. }, backstage, ariaAttrs);
  30885. var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({
  30886. lazySink: backstage.shared.getSink,
  30887. dom: {
  30888. tag: 'div',
  30889. classes: []
  30890. },
  30891. fireDismissalEventInstead: {}
  30892. }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), {
  30893. inlineBehaviours: derive$1(__spreadArrays([config('window-manager-inline-events', [run(dismissRequested(), function (_comp, _se) {
  30894. emit(dialogUi.dialog, formCancelEvent);
  30895. })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop))),
  30896. isExtraPart: function (_comp, target) {
  30897. return isAlertOrConfirmDialog(target);
  30898. }
  30899. })));
  30900. inlineDialog.set(inlineDialogComp);
  30901. InlineView.showWithin(inlineDialogComp, anchor, premade$1(dialogUi.dialog), Option.some(body()));
  30902. if (!isStickyToolbar$1 || !isToolbarLocationTop) {
  30903. Docking.refresh(inlineDialogComp);
  30904. editor.on('ResizeEditor', refreshDocking);
  30905. }
  30906. dialogUi.instanceApi.setData(initialData);
  30907. Keying.focusIn(dialogUi.dialog);
  30908. return dialogUi.instanceApi;
  30909. };
  30910. return DialogManager.open(factory, config$1);
  30911. };
  30912. var confirm = function (message, callback) {
  30913. confirmDialog.open(message, function (state) {
  30914. callback(state);
  30915. });
  30916. };
  30917. var alert = function (message, callback) {
  30918. alertDialog.open(message, function () {
  30919. callback();
  30920. });
  30921. };
  30922. var close = function (instanceApi) {
  30923. instanceApi.close();
  30924. };
  30925. return {
  30926. open: open,
  30927. openUrl: openUrl,
  30928. alert: alert,
  30929. close: close,
  30930. confirm: confirm
  30931. };
  30932. };
  30933. function Theme () {
  30934. global$1.add('silver', function (editor) {
  30935. var _a = setup$b(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi;
  30936. Autocompleter.register(editor, backstage.shared);
  30937. var windowMgr = setup$e({
  30938. editor: editor,
  30939. backstage: backstage
  30940. });
  30941. return {
  30942. renderUI: renderUI,
  30943. getWindowManagerImpl: constant(windowMgr),
  30944. getNotificationManagerImpl: function () {
  30945. return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership);
  30946. },
  30947. ui: getUi()
  30948. };
  30949. });
  30950. }
  30951. Theme();
  30952. }(window));